README 外链图片转存 OSS

This commit is contained in:
lxp
2026-11-03 17:27:22 +08:00
parent c5be9835bf
commit 175c49e0e7
35 changed files with 1557 additions and 99 deletions
@@ -17,6 +17,7 @@ import com.linkerbot.vibemake.service.migration.*;
import com.linkerbot.vibemake.service.oss.OssResourcePaths;
import com.linkerbot.vibemake.service.oss.UrdfResources;
import com.linkerbot.vibemake.service.support.*;
import com.linkerbot.vibemake.service.readme.*;
import lombok.RequiredArgsConstructor;
@@ -47,6 +48,7 @@ public class AdminImportService {
private final UrdfResources urdfResources;
private final ObjectMapper json;
private final TransactionTemplate transactions;
private final ReadmeRepository readmes;
public ImportPreview preview(String url) {
management.requireAdmin();
@@ -306,12 +308,15 @@ public class AdminImportService {
} else if ("REVIEW".equals(task.getStatus())) {
if (task.getReceiptJson() == null)
throw BusinessException.conflict("迁移结果不明,需要运维核对,禁止重发");
if ("MIGRATED".equals(task.getPhase())) {
if (readmeState(task) != null) {
GiteaClient.RemoteRepository remote = engine().verifyReceipt(task.getSourceRepositoryUrl(), project.getGiteaRepoName(), receipt(task));
readmes.resume(task.getProjectCode(), remote.repository(), readmeState(task), state -> saveReadme(task, remote, state));
} else if ("MIGRATED".equals(task.getPhase())) {
engine().verifyReceipt(
task.getSourceRepositoryUrl(),
project.getGiteaRepoName(),
receipt(task));
} else if (Set.of("NORMALIZING", "BRANCH_READY").contains(task.getPhase())
} else if (Set.of("NORMALIZING", "BRANCH_READY", "README_IMAGES").contains(task.getPhase())
&& task.getTargetSha() != null) {
engine().verifyNormalized(
task.getSourceRepositoryUrl(),
@@ -367,8 +372,8 @@ public class AdminImportService {
if ("CLEANING".equals(task.getPhase())) return false;
if ("FAILED".equals(task.getStatus())) return true;
return task.getReceiptJson() != null
&& ("MIGRATED".equals(task.getPhase())
|| Set.of("NORMALIZING", "BRANCH_READY").contains(task.getPhase())
&& (readmeState(task) != null || "MIGRATED".equals(task.getPhase())
|| Set.of("NORMALIZING", "BRANCH_READY", "README_IMAGES").contains(task.getPhase())
&& task.getTargetSha() != null);
}
@@ -658,7 +663,10 @@ public class AdminImportService {
recoverMissingReceipt(task, project);
}
RepositoryMigration.Result result;
if ("BRANCH_READY".equals(task.getPhase()) && task.getReceiptJson() != null) {
if (readmeState(task) != null) {
GiteaClient.RemoteRepository remote = engine().verifyReceipt(task.getSourceRepositoryUrl(), project.getGiteaRepoName(), receipt(task));
result = new RepositoryMigration.Result(remote, task.getTargetSha());
} else if ("BRANCH_READY".equals(task.getPhase()) && task.getReceiptJson() != null) {
result =
engine().verifyNormalized(
task.getSourceRepositoryUrl(),
@@ -729,16 +737,20 @@ public class AdminImportService {
}
});
}
ReadmeRepository.State imageState = migrateReadme(task, result);
String finalSha = imageState.resultSha;
List<String> warnings;
try {
warnings =
gitea.migrationWarnings(
result.remote().repository(),
result.sha(),
finalSha,
properties.getMaxFileBytes());
} catch (RuntimeException error) {
warnings = List.of("兼容性扫描未完成,请检查大文件、LFS、子模块及符号链接");
}
warnings = new ArrayList<>(warnings);
warnings.addAll(imageState.warnings);
String warningsJson = json.writeValueAsString(warnings);
transactions.executeWithoutResult(
status -> {
@@ -771,7 +783,7 @@ public class AdminImportService {
task.getOperatorUserCode(),
task.getTaskCode(),
task.getProjectCode(),
result.sha());
finalSha);
} catch (IOException error) {
throw new IllegalStateException("迁移收据持久化未确认", error);
}
@@ -782,7 +794,7 @@ public class AdminImportService {
try {
ProjectImportTask task = find(code);
boolean review =
Set.of("CLEANING", "MIGRATING", "VERIFYING", "MIGRATED", "NORMALIZING", "BRANCH_READY")
Set.of("CLEANING", "MIGRATING", "VERIFYING", "MIGRATED", "NORMALIZING", "BRANCH_READY", "README_IMAGES")
.contains(task.getPhase());
if (error instanceof GiteaFailure failure && failure.uncertain()) review = true;
if (error instanceof MigrationFailure failure
@@ -844,7 +856,7 @@ public class AdminImportService {
status -> {
task.setPhase(phase);
save(task);
if (Set.of("CLEANING", "MIGRATING", "NORMALIZING").contains(phase)) {
if (Set.of("CLEANING", "MIGRATING", "NORMALIZING", "README_IMAGES").contains(phase)) {
int updated =
projects.update(
null,
@@ -865,7 +877,7 @@ public class AdminImportService {
private GiteaClient.RemoteRepository receipt(ProjectImportTask task) {
if (task.getReceiptJson() == null) return null;
try {
return json.readValue(task.getReceiptJson(), GiteaClient.RemoteRepository.class);
return ReadmeMigrationReceipt.repository(json, task.getReceiptJson());
} catch (IOException error) {
throw new IllegalStateException("迁移收据无效");
}
@@ -874,4 +886,28 @@ public class AdminImportService {
private RepositoryMigration engine() {
return new RepositoryMigration(gitea, properties.getGitea().getOwner());
}
private ReadmeRepository.State readmeState(ProjectImportTask task) {
try { return ReadmeMigrationReceipt.state(json, task.getReceiptJson()); }
catch (IOException error) { throw new IllegalStateException("README 收据无效"); }
}
private void saveReadme(ProjectImportTask task, GiteaClient.RemoteRepository remote, ReadmeRepository.State state) {
try { task.setReceiptJson(ReadmeMigrationReceipt.encode(json, remote, state)); }
catch (IOException error) { throw new IllegalStateException("README 收据编码失败"); }
task.setPhase("README_IMAGES");
save(task);
}
private ReadmeRepository.State migrateReadme(ProjectImportTask task, RepositoryMigration.Result result) {
ReadmeRepository.State previous = readmeState(task);
phase(task, "README_IMAGES");
ReadmeRepository.Prepared prepared = previous == null
? readmes.prepare(task.getProjectCode(), result.remote().repository(), result.sha(), true) : null;
ReadmeRepository.State state = readmes.apply(task.getProjectCode(), result.remote().repository(), result.sha(), "main", prepared, previous,
next -> saveReadme(task, result.remote(), next));
if (!state.resultSha.equals(gitea.head(result.remote().repository())))
throw new MigrationFailure("README_MAIN_CHANGED", "README 处理后的 main 版本已变化");
return state;
}
}
@@ -0,0 +1,37 @@
package com.linkerbot.vibemake.service.config;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.Max;
@Getter
@Setter
@Component
@Validated
@ConfigurationProperties(prefix = "vibemake.readme-images")
public class ReadmeImageProperties {
private boolean enabled = true;
@Min(1) @Max(50 * 1024 * 1024)
private int maxBytes = 20 * 1024 * 1024;
@Min(1) @Max(4)
private int concurrency = 2;
/** 完整 URL 的正则表达式;只用于配置,不记录匹配到的原始地址。 */
private List<String> preserveUrlPatterns = new ArrayList<>();
@jakarta.validation.constraints.AssertTrue(message = "README 保留地址规则必须是合法的正则表达式")
public boolean isPreserveUrlPatternsValid() {
if (preserveUrlPatterns == null) return false;
try {
for (String expression : preserveUrlPatterns) java.util.regex.Pattern.compile(expression);
return true;
} catch (IllegalArgumentException | NullPointerException error) {
return false;
}
}
}
@@ -45,6 +45,12 @@ public interface GiteaClient {
throw new UnsupportedOperationException("未实现仓库写入凭据核对");
}
default String findWriteReceipt(Repository repository, String branch, String baseSha,
String operationCode, String requestDigest) {
if ("main".equals(branch)) return findWriteReceipt(repository, baseSha, operationCode, requestDigest);
throw new UnsupportedOperationException("未实现分支写入凭据核对");
}
record RemoteRepository(long id, String owner, String name, boolean privateRepo,
boolean mirror, boolean empty, String originalUrl, String defaultBranch) {
public Repository repository() { return new Repository(id, owner, name); }
@@ -99,5 +105,11 @@ public interface GiteaClient {
String authorName,
String authorCode);
default CommitView commit(Repository repository, String branch, List<Change> changes,
String message, String authorName, String authorCode) {
if ("main".equals(branch)) return commit(repository, changes, message, authorName, authorCode);
throw new UnsupportedOperationException("未实现指定分支提交");
}
PageResponse<HistoryEntry> history(Repository repository, long page, long size);
}
@@ -490,6 +490,12 @@ public class RestGiteaClient implements GiteaClient {
String message,
String authorName,
String authorCode) {
return commit(repo, "main", changes, message, authorName, authorCode);
}
@Override
public CommitView commit(Repository repo, String branch, List<Change> changes,
String message, String authorName, String authorCode) {
List<Map<String, Object>> files = new ArrayList<>();
for (Change change : changes) {
Map<String, Object> item = new LinkedHashMap<>();
@@ -503,7 +509,7 @@ public class RestGiteaClient implements GiteaClient {
Map<String, Object> body =
Map.of(
"branch",
"main",
branch,
"files",
files,
"message",
@@ -550,10 +556,16 @@ public class RestGiteaClient implements GiteaClient {
@Override
public String findWriteReceipt(Repository repo, String baseSha, String operationCode,
String requestDigest) {
return findWriteReceipt(repo, "main", baseSha, operationCode, requestDigest);
}
@Override
public String findWriteReceipt(Repository repo, String branch, String baseSha, String operationCode,
String requestDigest) {
// 普通文件写入被项目锁串行化,未知期间禁止下一次写入。限制扫描量防止异常仓库拖垮任务。
// 超出扫描范围不推断失败,留在处理中并交给管理员兜底。
String suffix = WriteReceipt.suffix(operationCode, requestDigest);
String head = head(repo);
String head = branch(repo, branch);
String found = null;
for (int page = 1; page <= 20; page++) {
JsonNode entries = parse(request("GET", repoPath(repo)
@@ -573,7 +585,7 @@ public class RestGiteaClient implements GiteaClient {
}
if (entries.size() < 50) break;
}
if (!head.equals(head(repo)))
if (!head.equals(branch(repo, branch)))
throw new GiteaFailure(409, "WRITE_RECEIPT_BRANCH_CHANGED", "核对期间分支版本已变化", false);
return found;
}
@@ -66,7 +66,8 @@ public class OssResourcePaths {
if (root != null && !root.isBlank() && path.startsWith(root + "/"))
path = path.substring(root.length());
if (!path.startsWith("/project-covers/") && !path.startsWith("/urdf/")
&& !path.startsWith("/project-resources/")) throw invalidPath();
&& !path.startsWith("/project-resources/")
&& !path.startsWith("/readme-images/")) throw invalidPath();
String relative = path.substring(1);
if (relative.endsWith("/")) relative = relative.substring(0, relative.length() - 1);
try {
@@ -0,0 +1,201 @@
package com.linkerbot.vibemake.service.readme;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.Locale;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.helpers.DefaultHandler;
/** 公开图片下载:DNS 校验与实际连接共用解析结果,不附加任何业务凭据。 */
public class ExternalImageDownloader {
private static final java.util.concurrent.ScheduledExecutorService TIMEOUTS =
java.util.concurrent.Executors.newSingleThreadScheduledExecutor(task -> {
Thread thread = new Thread(task, "readme-image-timeouts");
thread.setDaemon(true);
return thread;
});
public record Image(byte[] bytes, String contentType, String extension) {}
public static class Failure extends RuntimeException {
public Failure(String code) { super(code); }
public String code() { return getMessage(); }
}
private final int maxBytes;
public ExternalImageDownloader(int maxBytes) {
if (maxBytes < 1 || maxBytes > 50 * 1024 * 1024) throw new IllegalArgumentException("图片大小限制不合法");
this.maxBytes = maxBytes;
}
public Image download(String url) throws Exception {
long deadline = System.nanoTime() + Duration.ofSeconds(45).toNanos();
for (int attempt = 0; ; attempt++) {
try { return fetch(url, deadline); }
catch (IOException error) {
if (System.nanoTime() >= deadline) throw new Failure("IMAGE_DOWNLOAD_TIMEOUT");
if (attempt >= 2 || Thread.currentThread().isInterrupted()) throw error;
}
}
}
private Image fetch(String url, long deadline) throws Exception {
URI uri = URI.create(url.startsWith("//") ? "https:" + url : url);
try (CloseableHttpClient client = HttpClients.custom().disableAutomaticRetries().disableRedirectHandling().disableCookieManagement()
.setDnsResolver(host -> {
InetAddress[] addresses = InetAddress.getAllByName(host);
for (InetAddress address : addresses) validateAddress(address);
return addresses;
}).build()) {
for (int redirects = 0; redirects <= 5; redirects++) {
validateUri(uri);
int remaining = (int) Math.min(Integer.MAX_VALUE, (deadline - System.nanoTime()) / 1_000_000);
if (remaining <= 0 || Thread.currentThread().isInterrupted()) throw new Failure("IMAGE_DOWNLOAD_TIMEOUT");
HttpGet request = new HttpGet(uri);
request.setConfig(RequestConfig.custom().setConnectTimeout(Math.min(10000, remaining))
.setSocketTimeout(Math.min(15000, remaining)).setConnectionRequestTimeout(Math.min(10000, remaining)).build());
request.setHeader("User-Agent", "vibemake-image-migration/1");
request.setHeader("Accept", "image/*");
java.util.concurrent.ScheduledFuture<?> timeout = TIMEOUTS.schedule(request::abort, remaining, java.util.concurrent.TimeUnit.MILLISECONDS);
try (CloseableHttpResponse response = client.execute(request)) {
int status = response.getStatusLine().getStatusCode();
if (status >= 300 && status < 400) {
if (response.getFirstHeader("Location") == null) throw new Failure("IMAGE_REDIRECT_INVALID");
URI next = uri.resolve(response.getFirstHeader("Location").getValue());
if ("https".equalsIgnoreCase(uri.getScheme()) && !"https".equalsIgnoreCase(next.getScheme()))
throw new Failure("IMAGE_REDIRECT_DOWNGRADE");
uri = next;
request.abort();
continue;
}
if (status != 200) throw new Failure("IMAGE_HTTP_" + status);
if (response.getEntity() == null) throw new Failure("IMAGE_EMPTY");
if (response.getEntity().getContentLength() > maxBytes) throw new Failure("IMAGE_TOO_LARGE");
try (InputStream input = response.getEntity().getContent()) {
return image(read(input, maxBytes, deadline), true);
} finally { request.abort(); }
} finally { timeout.cancel(false); request.abort(); }
}
}
throw new Failure("IMAGE_REDIRECT_LIMIT");
}
public static void validateUri(URI uri) {
String scheme = uri.getScheme();
if (!("https".equalsIgnoreCase(scheme) || "http".equalsIgnoreCase(scheme)) || uri.getHost() == null
|| uri.getRawUserInfo() != null || (uri.getPort() != -1 && uri.getPort() != ("https".equalsIgnoreCase(scheme) ? 443 : 80)))
throw new Failure("IMAGE_URL_INVALID");
}
public static void validateAddress(InetAddress address) {
byte[] bytes = address.getAddress();
boolean reservedIpv4 = bytes.length == 4 && ((bytes[0] & 255) == 0 || (bytes[0] & 255) >= 224
|| (bytes[0] & 255) == 100 && ((bytes[1] & 255) & 192) == 64
|| (bytes[0] & 255) == 198 && ((bytes[1] & 255) == 18 || (bytes[1] & 255) == 19));
// 只允许 IPv6 全球单播 2000::/3,包含 IPv4 映射时 InetAddress 会还原为 IPv4。
boolean reservedIpv6 = bytes.length == 16 && (bytes[0] & 224) != 32;
if (address.isAnyLocalAddress() || address.isLoopbackAddress() || address.isLinkLocalAddress()
|| address.isSiteLocalAddress() || address.isMulticastAddress() || reservedIpv4 || reservedIpv6)
throw new Failure("IMAGE_PRIVATE_ADDRESS");
}
public static byte[] read(InputStream input, int limit, long deadline) throws Exception {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[8192];
int count;
while ((count = input.read(buffer)) != -1) {
if (System.nanoTime() > deadline || Thread.currentThread().isInterrupted()) throw new Failure("IMAGE_DOWNLOAD_TIMEOUT");
if (count > limit - output.size()) throw new Failure("IMAGE_TOO_LARGE");
output.write(buffer, 0, count);
}
return output.toByteArray();
}
public static Image image(byte[] bytes, boolean allowSvg) throws Exception {
if (bytes.length >= 3 && (bytes[0] & 255) == 255 && (bytes[1] & 255) == 216 && (bytes[2] & 255) == 255)
return new Image(bytes, "image/jpeg", "jpg");
if (bytes.length >= 8 && Arrays.equals(Arrays.copyOf(bytes, 8), new byte[] {(byte)137,80,78,71,13,10,26,10}))
return new Image(bytes, "image/png", "png");
if (bytes.length >= 6 && new String(bytes, 0, 6, StandardCharsets.US_ASCII).matches("GIF8[79]a"))
return new Image(bytes, "image/gif", "gif");
if (bytes.length >= 12 && new String(bytes, 0, 4, StandardCharsets.US_ASCII).equals("RIFF")
&& new String(bytes, 8, 4, StandardCharsets.US_ASCII).equals("WEBP"))
return new Image(bytes, "image/webp", "webp");
if (allowSvg && new String(bytes, StandardCharsets.UTF_8).stripLeading().matches("(?s)(?:\\uFEFF)?<.*")) {
byte[] safe = stripExternalSvgDoctype(bytes);
validateSvg(safe);
return new Image(safe, "image/svg+xml", "svg");
}
throw new Failure("IMAGE_FORMAT_UNSUPPORTED");
}
/** 旧 Illustrator/Creative Commons SVG 常带外部 DTD;移除纯外部声明,仍拒绝内部实体。 */
private static byte[] stripExternalSvgDoctype(byte[] bytes) {
String text = new String(bytes, StandardCharsets.UTF_8);
String quoted = "(?:\"[^\"<>\\[\\]]*\"|'[^'<>\\[\\]]*')";
java.util.regex.Matcher declaration = java.util.regex.Pattern.compile(
"(?is)<!DOCTYPE\\s+svg\\s+(?:PUBLIC\\s+" + quoted + "\\s+" + quoted + "|SYSTEM\\s+" + quoted + ")\\s*>").matcher(text);
java.util.regex.Matcher root = java.util.regex.Pattern.compile("(?i)<svg(?=[\\s>])").matcher(text);
if (root.find() && declaration.find() && declaration.start() < root.start())
return (text.substring(0, declaration.start()) + text.substring(declaration.end())).getBytes(StandardCharsets.UTF_8);
return bytes;
}
private static void validateSvg(byte[] bytes) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
javax.xml.parsers.DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new DefaultHandler());
Element root;
try { root = builder.parse(new ByteArrayInputStream(bytes)).getDocumentElement(); }
catch (org.xml.sax.SAXException error) { throw new Failure("IMAGE_SVG_UNSAFE"); }
if (!"svg".equals(root.getLocalName()) || !"http://www.w3.org/2000/svg".equals(root.getNamespaceURI()))
throw new Failure("IMAGE_FORMAT_UNSUPPORTED");
NodeList elements = root.getElementsByTagName("*");
for (int index = -1; index < elements.getLength(); index++) {
Element element = index == -1 ? root : (Element) elements.item(index);
String name = element.getLocalName();
if ("script".equalsIgnoreCase(name) || "foreignObject".equalsIgnoreCase(name)
|| "animate".equalsIgnoreCase(name) || "set".equalsIgnoreCase(name)) throw new Failure("IMAGE_SVG_UNSAFE");
NamedNodeMap attributes = element.getAttributes();
for (int attribute = 0; attribute < attributes.getLength(); attribute++) {
org.w3c.dom.Node item = attributes.item(attribute);
String key = item.getLocalName() == null ? item.getNodeName() : item.getLocalName();
String value = item.getNodeValue().strip();
if (key.toLowerCase(Locale.ROOT).startsWith("on")
|| "href".equalsIgnoreCase(key) && !value.startsWith("#")
|| unsafeCss(value)) throw new Failure("IMAGE_SVG_UNSAFE");
}
if ("style".equalsIgnoreCase(name) && unsafeCss(element.getTextContent())) throw new Failure("IMAGE_SVG_UNSAFE");
}
}
private static boolean unsafeCss(String value) {
String normalized = value.toLowerCase(Locale.ROOT);
if (normalized.contains("@import") || normalized.contains("\\")) return true;
java.util.regex.Matcher urls = java.util.regex.Pattern.compile("url\\(\\s*(['\"]?)(.*?)\\1\\s*\\)", java.util.regex.Pattern.DOTALL).matcher(normalized);
while (urls.find()) if (!urls.group(2).strip().startsWith("#")) return true;
return false;
}
}
@@ -0,0 +1,77 @@
package com.linkerbot.vibemake.service.readme;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.linkerbot.vibemake.service.config.OssProperties;
import jakarta.annotation.PreDestroy;
import java.io.ByteArrayInputStream;
import java.util.Map;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
/** 封面与 README 共用的按摘要核验、禁止覆盖上传;客户端按需初始化。 */
@Component
public class ImageOssUploader implements AutoCloseable {
private final OssProperties properties;
private OSS client;
public ImageOssUploader(OssProperties properties) { this.properties = properties; }
private synchronized OSS client() {
if (client != null) return client;
OssProperties checked = new OssProperties();
BeanUtils.copyProperties(properties, checked);
checked.setEnabled(true);
if (!checked.isConfigurationValid()) throw new ExternalImageDownloader.Failure("OSS_CONFIGURATION_MISSING");
ClientBuilderConfiguration configuration = new ClientBuilderConfiguration();
configuration.setSignatureVersion(SignVersion.V4);
configuration.setConnectionTimeout(10000);
configuration.setSocketTimeout(20000);
configuration.setRequestTimeoutEnabled(true);
configuration.setRequestTimeout(30000);
configuration.setMaxErrorRetry(1);
client = OSSClientBuilder.create().endpoint(properties.resolvedEndpoint()).region(properties.getRegion())
.credentialsProvider(new DefaultCredentialProvider(properties.getAccessKeyId(), properties.getAccessKeySecret()))
.clientConfiguration(configuration).build();
return client;
}
public void upload(String key, ExternalImageDownloader.Image image, String sha256) {
ObjectMetadata existing = metadata(key);
if (existing != null) { verify(existing, image, sha256); return; }
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(image.bytes().length);
metadata.setContentType(image.contentType());
metadata.setCacheControl("public, max-age=31536000, immutable");
metadata.setUserMetadata(Map.of("sha256", sha256));
metadata.setHeader("x-oss-forbid-overwrite", "true");
try {
client().putObject(new PutObjectRequest(properties.getBucket(), key, new ByteArrayInputStream(image.bytes()), metadata));
} catch (OSSException error) {
if (!"FileAlreadyExists".equals(error.getErrorCode())) throw new ExternalImageDownloader.Failure("OSS_PUT_" + error.getErrorCode());
}
ObjectMetadata uploaded = metadata(key);
if (uploaded == null) throw new ExternalImageDownloader.Failure("OSS_VERIFY_MISSING");
verify(uploaded, image, sha256);
}
private ObjectMetadata metadata(String key) {
try { return client().getObjectMetadata(properties.getBucket(), key); }
catch (OSSException error) {
if ("NoSuchKey".equals(error.getErrorCode())) return null;
throw new ExternalImageDownloader.Failure("OSS_HEAD_" + error.getErrorCode());
}
}
private void verify(ObjectMetadata metadata, ExternalImageDownloader.Image image, String digest) {
if (metadata.getContentLength() != image.bytes().length || !digest.equals(metadata.getUserMetadata().get("sha256"))
|| !image.contentType().equals(metadata.getContentType())) throw new ExternalImageDownloader.Failure("OSS_VERIFY_MISMATCH");
}
@Override @PreDestroy public synchronized void close() { if (client != null) { client.shutdown(); client = null; } }
}
@@ -0,0 +1,225 @@
package com.linkerbot.vibemake.service.readme;
import com.linkerbot.vibemake.service.config.OssProperties;
import com.linkerbot.vibemake.service.config.ReadmeImageProperties;
import com.linkerbot.vibemake.service.oss.OssResourcePaths;
import com.vladsch.flexmark.ast.*;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Document;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import com.vladsch.flexmark.util.sequence.Escaping;
import java.net.URI;
import java.security.MessageDigest;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/** 解析和原位替换,不经过 Markdown/HTML 全文重新渲染。 */
@Component
public class ReadmeImages {
public record Reference(int start, int end, String url, String prefix, String suffix, boolean html) {
public Reference(int start, int end, String url, String prefix, String suffix) {
this(start, end, url, prefix, suffix, false);
}
}
public record Scan(List<Reference> images, int external, int local, int managed, int badges) {}
public record Result(String content, int replaced, int failed, int badges, List<String> warnings) {}
@FunctionalInterface public interface Transfer { String store(String url) throws Exception; }
private static final Logger log = LoggerFactory.getLogger(ReadmeImages.class);
private static final Pattern PROTECTED_HTML = Pattern.compile("(?is)<!--.*?-->|<(pre|code|script|style)\\b[^>]*>.*?</\\1\\s*>");
private static final Pattern TAG = Pattern.compile("(?is)<(img|source)\\b(?:[^>\"']|\"[^\"]*\"|'[^']*')*>");
private static final Pattern ATTRIBUTE = Pattern.compile("([\\w:-]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+)))?");
private final ReadmeImageProperties settings;
private final OssProperties oss;
private final Transfer transfer;
private final Map<String, String> successful = new ConcurrentHashMap<>();
@org.springframework.beans.factory.annotation.Autowired
public ReadmeImages(ReadmeImageProperties settings, OssProperties oss, OssResourcePaths paths, ImageOssUploader uploader) {
this(settings, oss, url -> {
ExternalImageDownloader downloader = new ExternalImageDownloader(settings.getMaxBytes());
ExternalImageDownloader.Image image = downloader.download(url);
String digest = digest(image.bytes());
String path = "/readme-images/" + digest + "." + image.extension();
uploader.upload(paths.objectKey(path), image, digest);
String publicUrl = paths.publicUrl(path);
if (!digest.equals(digest(downloader.download(publicUrl).bytes())))
throw new ExternalImageDownloader.Failure("OSS_PUBLIC_VERIFY_MISMATCH");
return publicUrl;
});
}
public ReadmeImages(ReadmeImageProperties settings, OssProperties oss, Transfer transfer) {
this.settings = settings;
this.oss = oss;
this.transfer = transfer;
}
public Scan scan(String content) {
Document document = Parser.builder().build().parse(content);
List<Reference> references = new ArrayList<>();
Set<Reference> unique = new LinkedHashSet<>();
Set<com.vladsch.flexmark.ast.Reference> linked = new HashSet<>();
for (Node node : document.getDescendants())
if (node instanceof LinkRef link && link.getReferenceNode(document) != null) linked.add(link.getReferenceNode(document));
List<int[]> protectedRanges = new ArrayList<>();
Matcher protectedHtml = PROTECTED_HTML.matcher(content);
while (protectedHtml.find()) protectedRanges.add(new int[] {protectedHtml.start(), protectedHtml.end()});
for (Node node : document.getDescendants()) {
if (protectedRanges.stream().anyMatch(range -> node.getStartOffset() >= range[0] && node.getStartOffset() < range[1])) continue;
if (node instanceof Image image) add(unique, image.getUrl());
else if (node instanceof ImageRef image) {
com.vladsch.flexmark.ast.Reference definition = image.getReferenceNode(document);
if (definition == null) continue;
if (!linked.contains(definition)) add(unique, definition.getUrl());
else {
// 图片与普通链接共享定义时,只将图片改为内联写法,普通链接仍指向原地址。
String prefix = content.substring(image.getStartOffset(), image.getTextClosingMarker().getEndOffset()) + "(<";
String title = definition.getTitleOpeningMarker().isNotNull()
? " " + definition.getTitleOpeningMarker() + definition.getTitle() + definition.getTitleClosingMarker() : "";
unique.add(new Reference(image.getStartOffset(), image.getEndOffset(), Escaping.unescapeString(definition.getUrl().toString()), prefix, ">" + title + ")"));
}
} else if (node instanceof HtmlInline || node instanceof HtmlBlock) {
Matcher tags = TAG.matcher(node.getChars());
while (tags.find()) {
int offset = node.getStartOffset() + tags.start();
if (protectedRanges.stream().anyMatch(range -> offset >= range[0] && offset < range[1])) continue;
Matcher attributes = ATTRIBUTE.matcher(tags.group());
attributes.region(tags.group(1).length() + 1, tags.group().length());
while (attributes.find()) {
String name = attributes.group(1).toLowerCase(Locale.ROOT);
int group = attributes.group(2) != null ? 2 : attributes.group(3) != null ? 3 : 4;
String value = attributes.group(group);
if (value == null) continue;
int start = offset + attributes.start(group);
if ("src".equals(name) && "img".equalsIgnoreCase(tags.group(1)))
unique.add(new Reference(start, start + value.length(), Escaping.unescapeHtml(value), "", "", true));
else if ("srcset".equals(name)) srcset(unique, value, start);
}
}
}
}
int external = 0, local = 0, managed = 0, badges = 0;
for (Reference reference : unique) {
String url = reference.url();
if (!url.matches("(?is)^(?:https?:)?//.*")) { local++; continue; }
external++;
if (managed(url)) { managed++; continue; }
if (badge(url)) { badges++; continue; }
references.add(reference);
}
references.sort(Comparator.comparingInt(Reference::start));
return new Scan(List.copyOf(references), external, local, managed, badges);
}
private static void add(Set<Reference> references, BasedSequence value) {
references.add(new Reference(value.getStartOffset(), value.getEndOffset(), Escaping.unescapeString(value.toString()), "", ""));
}
private static void srcset(Set<Reference> references, String value, int offset) {
int index = 0;
while (index < value.length()) {
while (index < value.length() && (Character.isWhitespace(value.charAt(index)) || value.charAt(index) == ',')) index++;
int start = index;
while (index < value.length() && !Character.isWhitespace(value.charAt(index))) index++;
int end = index;
while (end > start && value.charAt(end - 1) == ',') end--;
if (end > start) references.add(new Reference(offset + start, offset + end, Escaping.unescapeHtml(value.substring(start, end)), "", "", true));
if (end != index) continue;
while (index < value.length() && value.charAt(index) != ',') index++;
}
}
public Result replace(String projectCode, String content) {
Scan scan = scan(content);
if (!settings.isEnabled()) return new Result(content, 0, scan.images().size(), scan.badges(),
scan.images().isEmpty() ? List.of() : List.of("README 图片转存未启用,保留原链"));
Map<String, Future<String>> jobs = new LinkedHashMap<>();
try (ExecutorService executor = Executors.newFixedThreadPool(Math.max(1, Math.min(4, settings.getConcurrency())))) {
for (Reference reference : scan.images()) jobs.computeIfAbsent(reference.url(), url -> executor.submit(() -> {
String cached = successful.get(url);
if (cached != null) return cached;
String stored = transfer.store(url);
log.info("README 图片已转存 projectCode={} sourceHost={}", projectCode, host(url));
if (successful.size() < 4096) successful.put(url, stored);
return stored;
}));
Map<String, String> replacements = new HashMap<>();
List<String> warnings = new ArrayList<>();
for (Map.Entry<String, Future<String>> job : jobs.entrySet()) {
try { replacements.put(job.getKey(), job.getValue().get()); }
catch (InterruptedException error) {
Thread.currentThread().interrupt();
throw new IllegalStateException("README 图片转存被中断");
} catch (ExecutionException error) {
Throwable cause = error.getCause();
String code = cause instanceof ExternalImageDownloader.Failure failure ? failure.code() : cause.getClass().getSimpleName();
warnings.add("README 图片转存失败 host=" + host(job.getKey()) + " code=" + code);
log.warn("README 图片转存失败 projectCode={} sourceHost={} code={}", projectCode, host(job.getKey()), code);
}
}
StringBuilder result = new StringBuilder(content);
int replaced = 0;
List<Reference> reverse = new ArrayList<>(scan.images());
Collections.reverse(reverse);
for (Reference reference : reverse) {
String stored = replacements.get(reference.url());
if (stored == null) continue;
String fragment = uri(reference.url()).getRawFragment();
if (fragment != null) stored += "#" + fragment;
if (reference.html()) stored = stored.replace("&", "&amp;").replace("\"", "&quot;")
.replace("'", "&#39;").replace("<", "&lt;").replace(">", "&gt;");
result.replace(reference.start(), reference.end(), reference.prefix() + stored + reference.suffix());
replaced++;
}
return new Result(result.toString(), replaced, scan.images().size() - replaced, scan.badges(), List.copyOf(warnings));
}
}
private boolean managed(String value) {
try {
URI uri = uri(value);
List<String> bases = new ArrayList<>(oss.getLegacyPublicBaseUrls());
bases.add(oss.publicBaseUrl());
if (!oss.getBucket().isBlank() && !oss.getRegion().isBlank()) bases.add(oss.uploadUrl());
for (String baseValue : bases) {
URI base = URI.create(baseValue);
String path = base.getPath().replaceAll("/+$", "");
if (base.getHost() != null && base.getHost().equalsIgnoreCase(uri.getHost())
&& (uri.getPort() == -1 ? 443 : uri.getPort()) == (base.getPort() == -1 ? 443 : base.getPort())
&& (path.isEmpty() || uri.getPath().equals(path) || uri.getPath().startsWith(path + "/"))) return true;
}
} catch (IllegalArgumentException | NullPointerException ignored) { /* 非法历史 URL 进入失败报告。 */ }
return false;
}
private boolean badge(String value) {
try {
URI uri = uri(value);
String host = uri.getHost().toLowerCase(Locale.ROOT);
String path = uri.getPath().toLowerCase(Locale.ROOT);
if (host.equals("shields.io") || host.endsWith(".shields.io")
|| host.equals("build.ros2.org") || host.equals("build.ros.org")
|| host.equals("github.com") && (path.contains("/actions/") && path.endsWith("/badge.svg") || path.endsWith("/workflows/ci/badge.svg"))
|| (host.endsWith("travis-ci.org") || host.endsWith("travis-ci.com") || host.equals("codecov.io") || host.equals("coveralls.io"))
|| (path.contains("/badge/") || path.contains("/badges/")) && path.endsWith(".svg")) return true;
return settings.getPreserveUrlPatterns().stream().anyMatch(pattern -> Pattern.matches(pattern, value));
} catch (IllegalArgumentException | NullPointerException ignored) { return false; }
}
private static URI uri(String value) { return URI.create(value.startsWith("//") ? "https:" + value : value); }
public static String host(String value) {
try { String host = uri(value).getHost(); return host == null ? "invalid" : host; }
catch (IllegalArgumentException error) { return "invalid"; }
}
public static String digest(byte[] bytes) {
try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); }
catch (java.security.NoSuchAlgorithmException error) { throw new IllegalStateException(error); }
}
}
@@ -0,0 +1,27 @@
package com.linkerbot.vibemake.service.readme;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.linkerbot.vibemake.service.gitea.GiteaClient;
import java.io.IOException;
/** 兼容旧收据,在既有 JSON 中保存 README 进度,来源 SHA 不被图片提交覆盖。 */
public final class ReadmeMigrationReceipt {
private ReadmeMigrationReceipt() {}
public static GiteaClient.RemoteRepository repository(ObjectMapper json, String value) throws IOException {
ObjectNode node = (ObjectNode) json.readTree(value);
node.remove("readmeImages");
return json.treeToValue(node, GiteaClient.RemoteRepository.class);
}
public static ReadmeRepository.State state(ObjectMapper json, String value) throws IOException {
if (value == null) return null;
JsonNode node = json.readTree(value).get("readmeImages");
return node == null || node.isNull() ? null : json.treeToValue(node, ReadmeRepository.State.class);
}
public static String encode(ObjectMapper json, GiteaClient.RemoteRepository repository, ReadmeRepository.State state) throws IOException {
ObjectNode node = json.valueToTree(repository);
node.set("readmeImages", json.valueToTree(state));
return json.writeValueAsString(node);
}
}
@@ -0,0 +1,154 @@
package com.linkerbot.vibemake.service.readme;
import com.linkerbot.vibemake.bean.Contracts.TreeEntry;
import com.linkerbot.vibemake.service.gitea.GiteaClient;
import com.linkerbot.vibemake.service.gitea.GiteaFailure;
import com.linkerbot.vibemake.service.gitea.WriteReceipt;
import java.nio.ByteBuffer;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/** 调用方负责项目锁和状态持久化;状态先落盘,再进行任何 Git 写入。 */
@Component
public class ReadmeRepository {
public static class State {
public String branch;
public String baseSha;
public String path;
public String blobSha;
public String operationCode;
public String digest;
public String resultSha;
public String stage;
public int replaced;
public int failed;
public int badges;
public List<String> warnings = new ArrayList<>();
}
public record Prepared(String path, String blobSha, String original, ReadmeImages.Scan scan, ReadmeImages.Result result) {}
@FunctionalInterface public interface Checkpoint { void save(State state); }
private static final Logger log = LoggerFactory.getLogger(ReadmeRepository.class);
private final GiteaClient gitea;
private final ReadmeImages images;
public ReadmeRepository(GiteaClient gitea, ReadmeImages images) { this.gitea = gitea; this.images = images; }
public Prepared prepare(String code, GiteaClient.Repository repository, String sha, boolean execute) {
try {
List<TreeEntry> entries = gitea.tree(repository, sha, "");
List<TreeEntry> readmes = entries.stream().filter(entry -> "file".equals(entry.type()) && "readme.md".equalsIgnoreCase(entry.name())).toList();
if (readmes.isEmpty()) return new Prepared(null, null, "", images.scan(""), new ReadmeImages.Result("", 0, 0, 0, List.of()));
// 同时出现两个仅大小写不同的 README 时不猜测前端选择。
if (readmes.size() != 1) throw new ExternalImageDownloader.Failure("README_AMBIGUOUS");
GiteaClient.StoredFile file = gitea.file(repository, sha, readmes.getFirst().path());
String content = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(file.bytes())).toString();
ReadmeImages.Scan scan = images.scan(content);
ReadmeImages.Result result = execute ? images.replace(code, content) : new ReadmeImages.Result(content, 0, 0, scan.badges(), List.of());
return new Prepared(file.path(), file.blobSha(), content, scan, result);
} catch (java.nio.charset.CharacterCodingException | RuntimeException error) {
if (Thread.currentThread().isInterrupted()) throw new IllegalStateException("README 检查被中断");
String failure = error instanceof com.linkerbot.vibemake.common.BusinessException business ? business.code()
: error instanceof ExternalImageDownloader.Failure image ? image.code() : error.getClass().getSimpleName();
log.warn("README 检查未完成 projectCode={} commitSha={} code={}", code, sha, failure);
return new Prepared(null, null, "", images.scan(""), new ReadmeImages.Result("", 0, 1, 0,
List.of("README 检查未完成 code=" + failure + ",保留原文")));
}
}
public State apply(String code, GiteaClient.Repository repository, String base, String branch,
Prepared prepared, State previous, Checkpoint checkpoint) {
if (previous != null) return resume(code, repository, previous, checkpoint);
State state = new State();
state.branch = branch;
state.baseSha = base;
state.path = prepared.path();
state.blobSha = prepared.blobSha();
state.replaced = prepared.result().replaced();
state.failed = prepared.result().failed();
state.badges = prepared.result().badges();
state.warnings = new ArrayList<>(prepared.result().warnings());
if (prepared.original().equals(prepared.result().content())) {
state.resultSha = base;
state.stage = "DONE";
checkpoint.save(state);
return state;
}
state.operationCode = UUID.randomUUID().toString().replace("-", "");
state.digest = ReadmeImages.digest(prepared.result().content().getBytes(StandardCharsets.UTF_8));
state.stage = "BRANCH";
checkpoint.save(state);
ensureBranch(repository, state);
if (!base.equals(gitea.branch(repository, branch))) throw conflict("README_BASE_CHANGED");
state.stage = "COMMITTING";
checkpoint.save(state);
try {
state.resultSha = gitea.commit(repository, branch,
List.of(new GiteaClient.Change("update", state.path, state.blobSha, prepared.result().content().getBytes(StandardCharsets.UTF_8))),
"转存 README 外链图片至 OSS" + WriteReceipt.suffix(state.operationCode, state.digest), "Vibemake", "readme-images").commitSha();
} catch (GiteaFailure error) {
if (!error.uncertain()) {
state.stage = "REJECTED";
checkpoint.save(state);
throw error;
}
return resume(code, repository, state, checkpoint);
}
verify(repository, state);
state.stage = "DONE";
checkpoint.save(state);
log.info("README 图片提交完成 projectCode={} branch={} baseSha={} commitSha={} replaced={} failed={}",
code, branch, base, state.resultSha, state.replaced, state.failed);
return state;
}
public State resume(String code, GiteaClient.Repository repository, State state, Checkpoint checkpoint) {
if ("REJECTED".equals(state.stage)) throw conflict("README_COMMIT_REJECTED");
if ("BRANCH".equals(state.stage)) {
// 即使没有提交请求记录,也不能在恢复时丢弃已保存的操作意图。
throw unknown();
}
if (!Objects.equals(state.baseSha, state.resultSha)) {
String receipt = gitea.findWriteReceipt(repository, state.branch, state.baseSha, state.operationCode, state.digest);
if (receipt == null) throw unknown();
if (state.resultSha != null && !state.resultSha.equals(receipt)) throw conflict("README_RECEIPT_MISMATCH");
state.resultSha = receipt;
verify(repository, state);
}
state.stage = "DONE";
checkpoint.save(state);
log.info("README 图片提交已核对 projectCode={} commitSha={}", code, state.resultSha);
return state;
}
private void ensureBranch(GiteaClient.Repository repository, State state) {
if ("main".equals(state.branch)) return;
try {
if (!state.baseSha.equals(gitea.branch(repository, state.branch))) throw conflict("README_BRANCH_CONFLICT");
} catch (GiteaFailure missing) {
if (missing.status() != 404) throw missing;
gitea.createBranch(repository, state.branch, state.baseSha);
}
}
public void verify(GiteaClient.Repository repository, State state) {
if (state.resultSha == null) throw unknown();
if (state.baseSha.equals(state.resultSha)) return;
if (!state.digest.equals(ReadmeImages.digest(gitea.file(repository, state.resultSha, state.path).bytes())))
throw conflict("README_CONTENT_MISMATCH");
Map<String, TreeEntry> before = treeWithoutReadme(repository, state.baseSha, state.path);
Map<String, TreeEntry> after = treeWithoutReadme(repository, state.resultSha, state.path);
if (!before.equals(after)) throw conflict("README_UNEXPECTED_FILES");
}
private Map<String, TreeEntry> treeWithoutReadme(GiteaClient.Repository repository, String sha, String path) {
Map<String, TreeEntry> result = new TreeMap<>();
for (TreeEntry entry : gitea.tree(repository, sha, "")) if (!entry.path().equals(path)) result.put(entry.path(), entry);
return result;
}
private static GiteaFailure conflict(String code) { return new GiteaFailure(409, code, "README 处理版本或收据发生变化", false); }
private static GiteaFailure unknown() { return new GiteaFailure(503, "README_RESULT_UNKNOWN", "README 提交结果待核对,禁止重发", true); }
}
@@ -0,0 +1,40 @@
package com.linkerbot.vibemake.service.readme;
import static org.assertj.core.api.Assertions.*;
import java.net.InetAddress;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
class ExternalImageDownloaderTest {
@Test void validatesSvgWithoutExternalEntitiesScriptsOrRemoteResources() throws Exception {
String svg = "<svg xmlns='http://www.w3.org/2000/svg'><defs><linearGradient id='a'/></defs><path fill='url(#a)' d='M0 0'/></svg>";
assertThat(ExternalImageDownloader.image(svg.getBytes(StandardCharsets.UTF_8), true).extension()).isEqualTo("svg");
for (String unsafe : new String[] {
"<!DOCTYPE svg [<!ENTITY x SYSTEM 'file:///etc/passwd'>]><svg xmlns='http://www.w3.org/2000/svg'>&x;</svg>",
"<svg xmlns='http://www.w3.org/2000/svg' onload='alert(1)'/>",
"<svg xmlns='http://www.w3.org/2000/svg'><script>alert(1)</script></svg>",
"<svg xmlns='http://www.w3.org/2000/svg'><image href='https://example.com/a.png'/></svg>",
"<svg xmlns='http://www.w3.org/2000/svg'><path fill='url(https://example.com/a.svg)'/></svg>"}) {
assertThatThrownBy(() -> ExternalImageDownloader.image(unsafe.getBytes(StandardCharsets.UTF_8), true))
.isInstanceOf(ExternalImageDownloader.Failure.class).hasMessage("IMAGE_SVG_UNSAFE");
}
}
@Test void rejectsPrivateAndReservedAddressesAndCredentialBearingUrls() throws Exception {
for (String address : new String[] {"127.0.0.1", "10.1.2.3", "169.254.169.254", "100.64.0.1", "198.18.0.1", "::1", "fc00::1", "::ffff:127.0.0.1"})
assertThatThrownBy(() -> ExternalImageDownloader.validateAddress(InetAddress.getByName(address)))
.hasMessage("IMAGE_PRIVATE_ADDRESS");
ExternalImageDownloader.validateAddress(InetAddress.getByName("8.8.8.8"));
assertThatThrownBy(() -> ExternalImageDownloader.validateUri(URI.create("https://user:secret@example.com/a.png")))
.hasMessage("IMAGE_URL_INVALID");
}
@Test void legacySvgExternalDoctypeIsRemovedWithoutResolvingIt() throws Exception {
String svg = "<?xml version='1.0'?><!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://127.0.0.1:1/never-fetch.dtd'>"
+ "<svg xmlns='http://www.w3.org/2000/svg'><path d='M0 0'/></svg>";
ExternalImageDownloader.Image image = ExternalImageDownloader.image(svg.getBytes(StandardCharsets.UTF_8), true);
assertThat(image.extension()).isEqualTo("svg");
assertThat(new String(image.bytes(), StandardCharsets.UTF_8)).doesNotContain("DOCTYPE", "127.0.0.1").contains("<path d='M0 0'/>");
}
}
@@ -0,0 +1,80 @@
package com.linkerbot.vibemake.service.readme;
import static org.assertj.core.api.Assertions.*;
import com.linkerbot.vibemake.service.config.OssProperties;
import com.linkerbot.vibemake.service.config.ReadmeImageProperties;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
class ReadmeImagesTest {
private OssProperties oss() {
OssProperties properties = new OssProperties();
properties.setPublicBaseUrl("https://assets.example.com");
properties.setRootDirectory("vibemake");
return properties;
}
@Test void replacesOnlyImageDestinationsAndKeepsFormattingCodeLocalLinksAndBadges() {
String original = "\uFEFF# 介绍\r\n![a](https://github.com/user-attachments/assets/a \"图\")\r\n"
+ "<img width=2215 height='884' alt=\"image\" src=\"https://github.com/user-attachments/assets/a\" />\r\n"
+ "![local](./img/a.png) [普通](https://github.com/user-attachments/assets/a)\r\n"
+ "![badge](https://img.shields.io/badge/build-pass-green.svg)\r\n"
+ "`![code](https://example.com/code.png)`\r\n```html\r\n<img src=\"https://example.com/code.png\">\r\n```\r\n"
+ "<!-- <img src=\"https://example.com/comment.png\"> -->\r\n<pre><img src=\"https://example.com/pre.png\"></pre>\r\n";
AtomicInteger downloads = new AtomicInteger();
ReadmeImages images = new ReadmeImages(new ReadmeImageProperties(), oss(), url -> { downloads.incrementAndGet(); return "https://assets.example.com/vibemake/readme-images/a.png"; });
ReadmeImages.Result result = images.replace("project", original);
assertThat(result.replaced()).isEqualTo(2);
assertThat(downloads).hasValue(1);
assertThat(result.content()).isEqualTo(original.replace("![a](https://github.com/user-attachments/assets/a", "![a](https://assets.example.com/vibemake/readme-images/a.png")
.replace("src=\"https://github.com/user-attachments/assets/a\"", "src=\"https://assets.example.com/vibemake/readme-images/a.png\""));
assertThat(images.scan(result.content()).images()).isEmpty();
assertThat(result.badges()).isEqualTo(1);
}
@Test void handlesReferenceImagesWithoutChangingSharedOrdinaryLinks() {
ReadmeImages images = new ReadmeImages(new ReadmeImageProperties(), oss(), url -> "https://assets.example.com/a.png");
String original = "![one][image]\n\n[image]: https://example.com/a.png \"原图\"\n\n![two][shared] [普通][shared]\n\n[shared]: https://example.com/b.png \"标题\"\n";
ReadmeImages.Result result = images.replace("project", original);
assertThat(result.content()).contains("[image]: https://assets.example.com/a.png \"原图\"")
.contains("![two](<https://assets.example.com/a.png> \"标题\") [普通][shared]")
.contains("[shared]: https://example.com/b.png \"标题\"");
assertThat(result.replaced()).isEqualTo(2);
}
@Test void handlesPictureSrcsetHtmlEntitiesAndFailuresWithoutBreakingOtherImages() {
ReadmeImages images = new ReadmeImages(new ReadmeImageProperties(), oss(), url -> {
if (url.contains("fail")) throw new ExternalImageDownloader.Failure("IMAGE_HTTP_404");
return "https://assets.example.com/" + (url.contains("large") ? "large.png" : "small.png");
});
String original = "<picture><source srcset=\"https://example.com/small.png?a=1&amp;b=2 1x, https://example.com/large.png 2x\">"
+ "<img src='https://example.com/fail.png' srcset='local.png 1x, https://example.com/large.png 2x' title='src=\"https://example.com/no.png\"'></picture>";
ReadmeImages.Result result = images.replace("project", original);
assertThat(result.replaced()).isEqualTo(3);
assertThat(result.failed()).isEqualTo(1);
assertThat(result.content()).contains("src='https://example.com/fail.png'")
.contains("srcset=\"https://assets.example.com/small.png 1x, https://assets.example.com/large.png 2x\"")
.contains("title='src=\"https://example.com/no.png\"'")
.contains("local.png 1x");
assertThat(result.warnings()).allMatch(warning -> !warning.contains("?"));
}
@Test void supportsCustomBadgeRulesAndSkipsManagedCdn() {
ReadmeImageProperties settings = new ReadmeImageProperties();
settings.setPreserveUrlPatterns(java.util.List.of("https://status\\.example\\.com/.*"));
ReadmeImages images = new ReadmeImages(settings, oss(), url -> { throw new AssertionError(); });
ReadmeImages.Scan scan = images.scan("![a](https://assets.example.com/vibemake/a.png) ![b](https://status.example.com/ci.svg) ![c](../a.png)");
assertThat(scan.images()).isEmpty();
assertThat(scan.managed()).isEqualTo(1);
assertThat(scan.badges()).isEqualTo(1);
assertThat(scan.local()).isEqualTo(1);
}
@Test void preservesImageFragmentsAndDoesNotDownloadTwiceOnRepeatedReferences() {
ReadmeImages images = new ReadmeImages(new ReadmeImageProperties(), oss(), url -> "https://assets.example.com/a.svg");
ReadmeImages.Result result = images.replace("project", "![a](https://example.com/a.svg#dark-mode-only)");
assertThat(result.content()).isEqualTo("![a](https://assets.example.com/a.svg#dark-mode-only)");
result = images.replace("project", "<img src='https://example.com/a.svg#id&#39;x&amp;y'>");
assertThat(result.content()).isEqualTo("<img src='https://assets.example.com/a.svg#id&#39;x&amp;y'>");
}
}
@@ -0,0 +1,82 @@
package com.linkerbot.vibemake.service.readme;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
import com.linkerbot.vibemake.bean.Contracts.CommitView;
import com.linkerbot.vibemake.bean.Contracts.TreeEntry;
import com.linkerbot.vibemake.service.config.OssProperties;
import com.linkerbot.vibemake.service.config.ReadmeImageProperties;
import com.linkerbot.vibemake.service.gitea.GiteaClient;
import com.linkerbot.vibemake.service.gitea.GiteaFailure;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.Test;
class ReadmeRepositoryTest {
private static final String BASE = "a".repeat(40);
private static final String NEXT = "b".repeat(40);
private final GiteaClient remote = mock(GiteaClient.class);
private final GiteaClient.Repository repository = new GiteaClient.Repository(1, "org", "repo");
private final AtomicReference<byte[]> changed = new AtomicReference<>();
private ReadmeRepository worker() {
OssProperties oss = new OssProperties();
oss.setPublicBaseUrl("https://assets.example.com");
ReadmeImages images = new ReadmeImages(new ReadmeImageProperties(), oss, url -> "https://assets.example.com/a.png");
when(remote.tree(eq(repository), anyString(), eq(""))).thenAnswer(call -> List.of(
new TreeEntry("README.md", "README.md", "file", 10, call.getArgument(1).equals(BASE) ? "old" : "new"),
new TreeEntry("code", "code", "dir", 0, "untouched")));
when(remote.file(eq(repository), eq(BASE), eq("README.md"))).thenReturn(new GiteaClient.StoredFile("README.md", "old", "![a](https://example.com/a.png)".getBytes(StandardCharsets.UTF_8)));
when(remote.file(eq(repository), eq(NEXT), eq("README.md"))).thenAnswer(call -> new GiteaClient.StoredFile("README.md", "new", changed.get()));
when(remote.branch(eq(repository), anyString())).thenReturn(BASE);
return new ReadmeRepository(remote, images);
}
@Test void durableIntentPrecedesCommitAndResponseLossUsesReceiptWithoutRepeatingWrite() {
ReadmeRepository worker = worker();
AtomicReference<ReadmeRepository.State> saved = new AtomicReference<>();
when(remote.commit(eq(repository), eq("main"), anyList(), anyString(), anyString(), anyString())).thenAnswer(call -> {
assertThat(saved.get().stage).isEqualTo("COMMITTING");
List<GiteaClient.Change> changes = call.getArgument(2);
changed.set(changes.getFirst().bytes());
throw new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "timeout", true);
});
when(remote.findWriteReceipt(eq(repository), eq("main"), eq(BASE), anyString(), anyString())).thenReturn(NEXT);
ReadmeRepository.State state = worker.apply("project", repository, BASE, "main", worker.prepare("project", repository, BASE, true), null, saved::set);
assertThat(state.resultSha).isEqualTo(NEXT);
assertThat(state.stage).isEqualTo("DONE");
worker.apply("project", repository, BASE, "main", null, state, saved::set);
verify(remote, times(1)).commit(eq(repository), eq("main"), anyList(), anyString(), anyString(), anyString());
}
@Test void unknownCommitResultIsNeverAutomaticallyReissued() {
ReadmeRepository worker = worker();
AtomicReference<ReadmeRepository.State> saved = new AtomicReference<>();
when(remote.commit(eq(repository), eq("main"), anyList(), anyString(), anyString(), anyString()))
.thenThrow(new GiteaFailure(504, "REMOTE_RESULT_UNKNOWN", "timeout", true));
assertThatThrownBy(() -> worker.apply("project", repository, BASE, "main", worker.prepare("project", repository, BASE, true), null, saved::set))
.isInstanceOfSatisfying(GiteaFailure.class, error -> assertThat(error.uncertain()).isTrue());
assertThatThrownBy(() -> worker.apply("project", repository, BASE, "main", null, saved.get(), saved::set)).hasMessageContaining("待核对");
verify(remote, times(1)).commit(eq(repository), eq("main"), anyList(), anyString(), anyString(), anyString());
}
@Test void oldPublishedSnapshotUsesSeparateBranchAndRejectsOtherFileChanges() {
ReadmeRepository worker = worker();
String branch = "maintenance/readme-oss/project/run";
when(remote.branch(repository, branch)).thenThrow(new GiteaFailure(404, "NOT_FOUND", "missing", false)).thenReturn(BASE);
when(remote.commit(eq(repository), eq(branch), anyList(), anyString(), anyString(), anyString())).thenAnswer(call -> {
List<GiteaClient.Change> changes = call.getArgument(2);
changed.set(changes.getFirst().bytes());
return new CommitView(NEXT, "image repair");
});
ReadmeRepository.State state = worker.apply("project", repository, BASE, branch, worker.prepare("project", repository, BASE, true), null, ignored -> {});
assertThat(state.resultSha).isEqualTo(NEXT);
verify(remote).createBranch(repository, branch, BASE);
verify(remote, never()).commit(eq(repository), eq("main"), anyList(), anyString(), anyString(), anyString());
when(remote.tree(repository, NEXT, "")).thenReturn(List.of(new TreeEntry("README.md", "README.md", "file", 10, "new"), new TreeEntry("code", "code", "dir", 0, "changed")));
assertThatThrownBy(() -> worker.verify(repository, state)).isInstanceOfSatisfying(GiteaFailure.class,
error -> assertThat(error.code()).isEqualTo("README_UNEXPECTED_FILES"));
}
}