Initialize Compose Launcher source and deployment

This commit is contained in:
tongtong committed 2026-11-26 02:34:19 +08:00
commit 12a8c24441
77 files changed
+9594

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
/data/
/target/
+12
View File
@@ -0,0 +1,12 @@
FROM eclipse-temurin:17-jre-jammy
WORKDIR /app
ENV TZ=Asia/Shanghai \
JAVA_TOOL_OPTIONS="-Xms64m -Xmx192m -XX:MaxMetaspaceSize=128m -XX:+UseSerialGC -XX:+ExitOnOutOfMemoryError -Djava.security.egd=file:/dev/./urandom"
COPY target/vibe-launcher-backend.jar /app/app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
+95
View File
@@ -0,0 +1,95 @@
apiVersion: v1
kind: Namespace
metadata:
name: vibe-launcher
labels:
name: vibe-launcher
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: vibe-launcher-backend
namespace: vibe-launcher
labels:
app: vibe-launcher-backend
spec:
replicas: 1
strategy:
type: Recreate
selector:
matchLabels:
app: vibe-launcher-backend
template:
metadata:
labels:
app: vibe-launcher-backend
spec:
containers:
- name: server
image: docker.io/library/vibe-launcher-backend:1.1.0-deploy3
imagePullPolicy: IfNotPresent
ports:
- name: http
containerPort: 8080
protocol: TCP
env:
- name: TZ
value: Asia/Shanghai
- name: HOST
value: 0.0.0.0
- name: PORT
value: "8080"
- name: LAYOUT_DB
value: /data/layouts.sqlite
envFrom:
- secretRef:
name: vibe-launcher-auth
volumeMounts:
- name: data
mountPath: /data
resources:
requests:
cpu: 100m
memory: 192Mi
limits:
cpu: 750m
memory: 384Mi
readinessProbe:
httpGet:
path: /healthz
port: http
initialDelaySeconds: 15
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 6
livenessProbe:
httpGet:
path: /healthz
port: http
initialDelaySeconds: 60
periodSeconds: 20
timeoutSeconds: 5
failureThreshold: 5
volumes:
- name: data
hostPath:
path: /opt/vibe-launcher/data
type: DirectoryOrCreate
---
apiVersion: v1
kind: Service
metadata:
name: vibe-launcher-backend
namespace: vibe-launcher
labels:
app: vibe-launcher-backend
spec:
type: NodePort
selector:
app: vibe-launcher-backend
ports:
- name: http
port: 8080
targetPort: http
nodePort: 30830
protocol: TCP
+22
View File
@@ -0,0 +1,22 @@
# Vibe Launcher 后端(k3s vibe-launcher/vibe-launcher-backend, NodePort 30830)
# 挂载点:https://api.ttstd.com/launcher/(灰云直连源站,不走 Cloudflare)
# 用法:放到 /etc/nginx/snippets/launcher-path.conf,在 api.ttstd.com 的 443 server 块内 include
# 以 /launcher/ 前缀反代,proxy_pass 末尾斜杠会剥掉前缀,后端仍收到 /api/... 与 /
location = /launcher {
return 301 /launcher/;
}
location ^~ /launcher/ {
client_max_body_size 2m;
proxy_pass http://127.0.0.1:30830/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 10s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
proxy_buffering off;
add_header Cache-Control "no-store" always;
}
+36
View File
@@ -0,0 +1,36 @@
#!/bin/bash
set -euo pipefail
BASE=${BASE:-https://api.ttstd.com/launcher}
AUTH_FILE=${AUTH_FILE:-/opt/vibe-launcher/auth.env}
. "$AUTH_FILE"
echo "== healthz =="
curl -fsS "$BASE/healthz"; echo
echo "== device layout =="
curl -fsS -H "Authorization: Bearer $DEVICE_TOKEN" -D /tmp/launcher-device.headers \
-o /tmp/launcher-device.json "$BASE/api/layout"
grep -i '^X-Layout-Revision:' /tmp/launcher-device.headers
echo "== admin layout =="
curl -fsS -H "Authorization: Bearer $ADMIN_TOKEN" -D /tmp/launcher-admin.headers \
-o /tmp/launcher-admin.json "$BASE/api/admin/layout"
TAG=$(sed -n 's/^[Ee][Tt][Aa][Gg]: //p' /tmp/launcher-admin.headers | tr -d '\r')
echo "ETag=$TAG"
echo "== missing If-Match =="
curl -sS -o /tmp/launcher-428.json -w '%{http_code}\n' -X PUT \
-H "Authorization: Bearer $ADMIN_TOKEN" -H 'Content-Type: application/json' \
--data @/tmp/launcher-admin.json "$BASE/api/admin/layout"
cat /tmp/launcher-428.json; echo
echo "== invalid layout =="
curl -sS -o /tmp/launcher-422.json -w '%{http_code}\n' -X PUT \
-H "Authorization: Bearer $ADMIN_TOKEN" -H "If-Match: $TAG" \
-H 'Content-Type: application/json' \
--data '{"schemaVersion":2,"pages":[]}' "$BASE/api/admin/layout"
head -c 200 /tmp/launcher-422.json; echo
echo "== history =="
curl -fsS -H "Authorization: Bearer $ADMIN_TOKEN" "$BASE/api/admin/history"; echo
+56
View File
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.2</version>
<relativePath/>
</parent>
<groupId>com.ttstd</groupId>
<artifactId>vibe-launcher-backend</artifactId>
<version>1.1.0</version>
<properties>
<java.version>17</java.version>
<sqlite-jdbc.version>3.41.2.2</sqlite-jdbc.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>${sqlite-jdbc.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>vibe-launcher-backend</finalName>
<resources>
<resource><directory>src/main/resources</directory></resource>
<resource>
<directory>../frontend/dist</directory>
<targetPath>launcher/web</targetPath>
</resource>
<resource>
<directory>../android/app/src/main/assets</directory>
<includes><include>default_layout.json</include></includes>
<targetPath>launcher</targetPath>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,24 @@
package com.ttstd.launcher;
import java.util.List;
import java.util.Map;
class ApiError extends RuntimeException {
final int status;
private final List<LayoutValidator.Issue> issues;
ApiError(int status, String message) {
this(status, message, List.of());
}
ApiError(int status, String message, List<LayoutValidator.Issue> issues) {
super(message);
this.status = status;
this.issues = issues;
}
Map<String, Object> body() {
return issues.isEmpty() ? Map.of("message", getMessage())
: Map.of("message", getMessage(), "issues", issues);
}
}
@@ -0,0 +1,53 @@
package com.ttstd.launcher;
import jakarta.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.resource.NoResourceFoundException;
@RestControllerAdvice
class ApiExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);
private static final MediaType JSON = new MediaType("application", "json", StandardCharsets.UTF_8);
@ExceptionHandler(ApiError.class)
ResponseEntity<Map<String, Object>> apiError(ApiError error) {
return ResponseEntity.status(error.status).contentType(JSON).body(error.body());
}
@ExceptionHandler({NoHandlerFoundException.class, NoResourceFoundException.class})
ResponseEntity<Map<String, Object>> notFound() {
return ResponseEntity.status(404).contentType(JSON).body(Map.of("message", "接口不存在"));
}
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
ResponseEntity<Map<String, Object>> methodNotAllowed(HttpRequestMethodNotSupportedException error) {
var response = ResponseEntity.status(405).contentType(JSON);
if (error.getSupportedHttpMethods() != null) {
response = response.header("Allow", String.join(", ",
error.getSupportedHttpMethods().stream().map(method -> method.name()).toList()));
}
return response.body(Map.of("message", "不支持的请求方法"));
}
@ExceptionHandler({MissingServletRequestParameterException.class, MethodArgumentTypeMismatchException.class})
ResponseEntity<Map<String, Object>> badRequest() {
return ResponseEntity.status(400).contentType(JSON).body(Map.of("message", "请求参数错误"));
}
@ExceptionHandler(Exception.class)
ResponseEntity<Map<String, Object>> internal(Exception error, HttpServletRequest request) {
log.error("处理 {} {} 失败", request.getMethod(), request.getRequestURI(), error);
return ResponseEntity.status(500).contentType(JSON).body(Map.of("message", "服务内部错误"));
}
}
@@ -0,0 +1,11 @@
package com.ttstd.launcher;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LauncherApplication {
public static void main(String[] args) {
SpringApplication.run(LauncherApplication.class, args);
}
}
@@ -0,0 +1,165 @@
package com.ttstd.launcher;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.Map;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tools.jackson.core.JacksonException;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.node.ObjectNode;
@RestController
class LayoutController {
private static final long MAX_SAFE_INTEGER = 9_007_199_254_740_991L;
private static final MediaType JSON = new MediaType("application", "json", StandardCharsets.UTF_8);
private static final String EDITOR_CSP = "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; "
+ "img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'";
private final LayoutStore store;
private final RequestPolicy policy;
private final LayoutValidator validator;
private final ObjectMapper mapper;
private final Resource editor = new ClassPathResource("launcher/web/index.html");
LayoutController(LayoutStore store, RequestPolicy policy, LayoutValidator validator, ObjectMapper mapper) {
this.store = store;
this.policy = policy;
this.validator = validator;
this.mapper = mapper;
}
@GetMapping({"/", "/index.html", "/canvas.html"})
ResponseEntity<Resource> editor() {
return ResponseEntity.ok()
.contentType(new MediaType("text", "html", StandardCharsets.UTF_8))
.cacheControl(CacheControl.noCache())
.header("Content-Security-Policy", EDITOR_CSP)
.body(editor);
}
@GetMapping("/assets/{name:[a-zA-Z0-9_-]+\\.(?:js|css)}")
ResponseEntity<Resource> editorAsset(@PathVariable String name) {
var asset = new ClassPathResource("launcher/web/assets/" + name);
if (!asset.exists()) throw new ApiError(404, "编辑器资源不存在");
var type = new MediaType("text", name.endsWith(".js") ? "javascript" : "css", StandardCharsets.UTF_8);
return ResponseEntity.ok().contentType(type).body(asset);
}
@GetMapping("/healthz")
Map<String, String> health() {
return Map.of("status", "ok");
}
@GetMapping("/api/layout")
ResponseEntity<byte[]> deviceLayout(HttpServletRequest request, HttpServletResponse response) throws SQLException {
policy.requireDevice(request, response);
var release = store.latest();
if (release.etag().equals(request.getHeader("If-None-Match"))) {
return releaseHeaders(304, release).build();
}
return serve(release);
}
@GetMapping("/api/admin/layout")
ResponseEntity<byte[]> adminLayout(HttpServletRequest request, HttpServletResponse response) throws SQLException {
policy.requireAdmin(request, response);
return serve(store.latest());
}
@GetMapping("/api/admin/history")
LayoutStore.History history(@RequestParam(defaultValue = "2147483648") String before,
HttpServletRequest request, HttpServletResponse response) throws SQLException {
policy.requireAdmin(request, response);
long revision;
try {
revision = Long.parseLong(before);
} catch (NumberFormatException error) {
throw new ApiError(400, "无效的分页参数");
}
if (revision < 1 || revision > MAX_SAFE_INTEGER) throw new ApiError(400, "无效的分页参数");
return store.history(revision);
}
@GetMapping("/api/admin/history/{revision:[1-9][0-9]{0,9}}")
ResponseEntity<byte[]> historyEntry(@PathVariable long revision, HttpServletRequest request,
HttpServletResponse response) throws SQLException {
policy.requireAdmin(request, response);
return serve(store.byRevision(revision));
}
@PutMapping("/api/admin/layout")
ResponseEntity<byte[]> publish(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
policy.requireAdmin(request, response);
String tag = requireTag(request);
JsonNode json = readJson(request);
var issues = validator.validate(json);
if (issues.stream().anyMatch(issue -> issue.level().equals("error"))) {
throw new ApiError(422, "布局校验失败", issues.stream().limit(100).toList());
}
return serve(store.publish(tag, (ObjectNode) json, null));
}
@PostMapping("/api/admin/rollback")
ResponseEntity<byte[]> rollback(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException {
policy.requireAdmin(request, response);
String tag = requireTag(request);
JsonNode revision = readJson(request).path("revision");
if (!revision.isNumber() || !revision.canConvertToExactIntegral() || !revision.canConvertToLong()
|| revision.longValue() < 1 || revision.longValue() > MAX_SAFE_INTEGER) {
throw new ApiError(400, "无效的回滚版本号");
}
return serve(store.publish(tag, null, revision.longValue()));
}
private static String requireTag(HttpServletRequest request) {
String tag = request.getHeader(HttpHeaders.IF_MATCH);
if (tag == null || tag.isEmpty()) throw new ApiError(428, "发布前请先读取线上版本");
return tag;
}
private JsonNode readJson(HttpServletRequest request) throws IOException {
String type = request.getContentType();
if (type == null || !type.split(";", 2)[0].trim().equalsIgnoreCase("application/json")) {
throw new ApiError(415, "请求必须使用 application/json");
}
if (request.getContentLengthLong() > LayoutStore.MAX_BYTES) throw new ApiError(413, "布局超过 1 MiB");
byte[] bytes = request.getInputStream().readNBytes(LayoutStore.MAX_BYTES + 1);
if (bytes.length > LayoutStore.MAX_BYTES) throw new ApiError(413, "布局超过 1 MiB");
try {
String text = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
if (text.startsWith("\uFEFF")) text = text.substring(1);
JsonNode node = mapper.reader().with(DeserializationFeature.FAIL_ON_TRAILING_TOKENS).readTree(text);
if (node == null || node.isMissingNode()) throw new ApiError(400, "无效的 UTF-8 JSON");
return node;
} catch (CharacterCodingException | JacksonException error) {
throw new ApiError(400, "无效的 UTF-8 JSON");
}
}
private static ResponseEntity.BodyBuilder releaseHeaders(int status, LayoutStore.Release release) {
return ResponseEntity.status(status).eTag(release.etag())
.header("X-Layout-Revision", Integer.toString(release.revision()));
}
private static ResponseEntity<byte[]> serve(LayoutStore.Release release) {
return releaseHeaders(200, release).contentType(JSON).body(release.layout().getBytes(StandardCharsets.UTF_8));
}
}
@@ -0,0 +1,181 @@
package com.ttstd.launcher;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Repository;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.node.ObjectNode;
@Repository
class LayoutStore {
static final int MAX_BYTES = 1024 * 1024;
private static final int PAGE_SIZE = 50;
private static final String LATEST = "SELECT revision, layout FROM releases ORDER BY revision DESC LIMIT 1";
private static final String BY_REVISION = "SELECT revision, layout FROM releases WHERE revision = ?";
record Release(int revision, String layout) {
String etag() {
return "\"" + java.util.HexFormat.of().formatHex(RequestPolicy.sha256(layout)) + "\"";
}
}
record HistoryEntry(int revision, String publishedAt, Integer restoredFrom) {}
record History(List<HistoryEntry> revisions, Integer nextBefore) {}
private final String address;
private final ObjectMapper mapper;
private final LayoutValidator validator;
LayoutStore(@Value("${launcher.database}") String database, ObjectMapper mapper, LayoutValidator validator)
throws IOException, SQLException {
this.mapper = mapper;
this.validator = validator;
Path path = Path.of(database).toAbsolutePath().normalize();
Files.createDirectories(path.getParent());
address = "jdbc:sqlite:" + path;
ObjectNode initial;
try (var stream = new ClassPathResource("launcher/default_layout.json").getInputStream()) {
var node = mapper.readTree(stream);
if (!node.isObject() || validator.validate(node).stream().anyMatch(i -> i.level().equals("error"))) {
throw new IllegalStateException("内置布局未通过校验");
}
initial = (ObjectNode) node;
}
try (var connection = connect(); var statement = connection.createStatement()) {
statement.execute("PRAGMA journal_mode = WAL");
statement.execute("""
CREATE TABLE IF NOT EXISTS releases (
revision INTEGER PRIMARY KEY CHECK (revision BETWEEN 1 AND 2147483647),
layout TEXT NOT NULL,
publishedAt TEXT NOT NULL,
restoredFrom INTEGER REFERENCES releases(revision)
) STRICT
""");
try (var seed = connection.prepareStatement("""
INSERT OR IGNORE INTO releases (revision, layout, publishedAt, restoredFrom)
VALUES (1, ?, ?, NULL)
""")) {
seed.setString(1, mapper.writeValueAsString(initial.put("revision", 1)));
seed.setString(2, Instant.now().toString());
seed.executeUpdate();
}
}
}
private Connection connect() throws SQLException {
var connection = DriverManager.getConnection(address);
try (var statement = connection.createStatement()) {
statement.execute("PRAGMA busy_timeout = 5000");
statement.execute("PRAGMA synchronous = FULL");
statement.execute("PRAGMA foreign_keys = ON");
return connection;
} catch (SQLException e) {
connection.close();
throw e;
}
}
Release latest() throws SQLException {
try (var connection = connect(); var statement = connection.createStatement();
var rows = statement.executeQuery(LATEST)) {
if (!rows.next()) throw new IllegalStateException("布局版本库为空");
return release(rows);
}
}
Release byRevision(long revision) throws SQLException {
try (var connection = connect()) {
return byRevision(connection, revision);
}
}
private Release byRevision(Connection connection, long revision) throws SQLException {
try (var statement = connection.prepareStatement(BY_REVISION)) {
statement.setLong(1, revision);
try (var rows = statement.executeQuery()) {
if (!rows.next()) throw new ApiError(404, "该版本不存在");
return release(rows);
}
}
}
History history(long before) throws SQLException {
List<HistoryEntry> result = new ArrayList<>();
try (var connection = connect(); var statement = connection.prepareStatement("""
SELECT revision, publishedAt, restoredFrom FROM releases
WHERE revision < ? ORDER BY revision DESC LIMIT 51
""")) {
statement.setLong(1, before);
try (var rows = statement.executeQuery()) {
while (rows.next()) {
if (result.size() == PAGE_SIZE) return new History(result, result.get(PAGE_SIZE - 1).revision());
int restoredFrom = rows.getInt("restoredFrom");
Integer previous = rows.wasNull() ? null : restoredFrom;
result.add(new HistoryEntry(rows.getInt("revision"), rows.getString("publishedAt"), previous));
}
}
}
return new History(result, null);
}
Release publish(String expected, ObjectNode layout, Long restoredFrom) throws SQLException {
try (var connection = connect(); var tx = connection.createStatement()) {
tx.execute("BEGIN IMMEDIATE");
try {
Release current;
try (var rows = tx.executeQuery(LATEST)) {
if (!rows.next()) throw new IllegalStateException("布局版本库为空");
current = release(rows);
}
if (!current.etag().equals(expected)) throw new ApiError(412, "线上版本已变化,请重新读取后再发布");
if (current.revision() == Integer.MAX_VALUE) throw new ApiError(409, "布局版本号已达上限");
if (restoredFrom != null) {
layout = (ObjectNode) mapper.readTree(byRevision(connection, restoredFrom).layout());
var issues = validator.validate(layout);
if (issues.stream().anyMatch(issue -> issue.level().equals("error"))) {
throw new ApiError(422, "历史版本布局校验失败,无法回滚", issues.stream().limit(100).toList());
}
}
int revision = current.revision() + 1;
String json = mapper.writeValueAsString(layout.put("schemaVersion", 3).put("revision", revision));
if (json.getBytes(StandardCharsets.UTF_8).length > MAX_BYTES) throw new ApiError(413, "布局超过 1 MiB");
try (var insert = connection.prepareStatement("""
INSERT INTO releases (revision, layout, publishedAt, restoredFrom) VALUES (?, ?, ?, ?)
""")) {
insert.setInt(1, revision);
insert.setString(2, json);
insert.setString(3, Instant.now().toString());
if (restoredFrom == null) insert.setNull(4, Types.INTEGER);
else insert.setLong(4, restoredFrom);
insert.executeUpdate();
}
tx.execute("COMMIT");
return new Release(revision, json);
} catch (SQLException | RuntimeException error) {
try {
tx.execute("ROLLBACK");
} catch (SQLException rollbackError) {
error.addSuppressed(rollbackError);
}
throw error;
}
}
}
private static Release release(ResultSet rows) throws SQLException {
return new Release(rows.getInt("revision"), rows.getString("layout"));
}
}
@@ -0,0 +1,236 @@
package com.ttstd.launcher;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import org.springframework.stereotype.Component;
import tools.jackson.databind.JsonNode;
@Component
class LayoutValidator {
record Issue(String level, String path, String message) {}
private record Rect(String path, float x, float y, float right, float bottom) {}
private static final Set<String> TYPES = Set.of("app_icon", "widget", "shortcut", "dock_bg");
private static final Set<String> FIT_MODES = Set.of("contain", "elastic", "stretch");
private static final Set<String> BACKGROUNDS = Set.of("wallpaper", "solid", "gradient");
private static final Pattern HEX_COLOR = Pattern.compile("#[0-9A-Fa-f]{6}");
private static final Pattern SCHEME = Pattern.compile("[A-Za-z][A-Za-z0-9+.-]*://.*");
private static final int MAX_CANVAS = 8192;
private static final int MAX_ID_LENGTH = 64;
private static final int MAX_LABEL_LENGTH = 100;
List<Issue> validate(JsonNode layout) {
List<Issue> issues = new ArrayList<>();
if (!layout.isObject()) {
error(issues, "$", "布局必须是 JSON 对象");
return issues;
}
if (!optional(layout, "schemaVersion", n -> integer(n) && n.intValue() == 3)) {
error(issues, "schemaVersion", "仅支持协议 v3");
}
if (!optional(layout, "revision", LayoutValidator::integer)) {
error(issues, "revision", "版本号必须是整数");
}
JsonNode canvas = layout.path("canvas");
JsonNode fit = layout.path("fit");
if (!optional(layout, "canvas", n -> n.isObject() &&
optionalFields(n, LayoutValidator::integer, "designWidth", "designHeight", "safeTop", "safeBottom"))) {
error(issues, "canvas", "画布字段必须是整数");
return issues;
}
if (!optional(layout, "fit", n -> n.isObject() && optional(n, "mode", JsonNode::isTextual)
&& optional(n, "anchorY", LayoutValidator::finiteFloat))) {
error(issues, "fit", "映射模式或留白位置格式错误");
}
int width = canvas.path("designWidth").asInt(1080);
int height = canvas.path("designHeight").asInt(1920);
int safeTop = canvas.path("safeTop").asInt(132);
int safeBottom = canvas.path("safeBottom").asInt(72);
if (width < 320 || height < 480) error(issues, "canvas", "画布最小尺寸为 320 × 480");
if (width > MAX_CANVAS || height > MAX_CANVAS) error(issues, "canvas", "画布尺寸不能超过 " + MAX_CANVAS);
if (safeTop < 0 || safeBottom < 0) error(issues, "canvas", "安全区不能为负数");
if (safeTop + safeBottom >= height) warn(issues, "canvas", "安全区总和高过画布,内容可能没有可用区域");
if (safeTop < 118) warn(issues, "canvas.safeTop", "safeTop 偏小,1440 屏状态栏约 176px");
if (safeBottom < 40) warn(issues, "canvas.safeBottom", "safeBottom 偏小,可能被手势条压住");
String mode = fit.path("mode").stringValue("");
if (!mode.isEmpty() && !FIT_MODES.contains(mode)) warn(issues, "fit.mode", "未知映射模式,端上按 contain 处理");
JsonNode anchor = fit.get("anchorY");
if (anchor != null && finiteFloat(anchor) && (anchor.doubleValue() < 0 || anchor.doubleValue() > 1)) {
warn(issues, "fit.anchorY", "留白位置需在 0–1 之间,端上会截断");
}
JsonNode pages = layout.path("pages");
if (!pages.isArray() || pages.isEmpty() || pages.size() > 20) {
error(issues, "pages", "布局必须包含 1–20 页");
return issues;
}
Set<Integer> indexes = new HashSet<>();
for (int i = 0; i < pages.size(); i++) {
JsonNode page = pages.get(i);
if (page.isObject()) {
JsonNode index = page.get("index");
if (index != null && integer(index)) {
if (!indexes.add(index.intValue())) {
warn(issues, "pages[" + i + "].index", "页序重复,端上按数组顺序显示");
} else if (index.intValue() != i) {
warn(issues, "pages[" + i + "].index", "页序与数组顺序不一致,端上按数组顺序显示");
}
}
}
validatePage(issues, page, "pages[" + i + "]", width, height, safeTop, safeBottom);
}
return issues;
}
private void validatePage(List<Issue> issues, JsonNode page, String path, int width, int height, int safeTop, int safeBottom) {
if (!page.isObject()) {
error(issues, path, "页面必须是对象");
return;
}
if (!optional(page, "index", LayoutValidator::integer)) error(issues, path + ".index", "页序必须是整数");
if (!optional(page, "background", n -> n.isObject() && optional(n, "type", JsonNode::isTextual)
&& optionalFields(n, LayoutValidator::nullableText, "color", "from", "to"))) {
error(issues, path + ".background", "页面背景字段格式错误");
}
JsonNode background = page.get("background");
if (background != null && background.isObject()) {
String backgroundType = background.path("type").stringValue("wallpaper");
if (!BACKGROUNDS.contains(backgroundType)) {
warn(issues, path + ".background.type", "未知背景类型,端上按壁纸处理");
}
if (backgroundType.equals("solid") && background.path("color").stringValue("").isBlank()) {
warn(issues, path + ".background.color", "纯色背景缺少 color");
}
if (backgroundType.equals("gradient") && (background.path("from").stringValue("").isBlank()
|| background.path("to").stringValue("").isBlank())) {
warn(issues, path + ".background", "渐变背景需要 from 和 to");
}
for (String name : List.of("color", "from", "to")) {
String color = background.path(name).stringValue("");
if (!color.isEmpty() && !HEX_COLOR.matcher(color).matches()) {
warn(issues, path + ".background." + name, "颜色需为 #RRGGBB 格式");
}
}
}
JsonNode items = page.path("items");
if (items.isMissingNode()) return;
if (!items.isArray() || items.size() > 80) {
error(issues, path + ".items", "每页最多 80 个元素");
return;
}
Set<String> ids = new HashSet<>();
List<Rect> rectangles = new ArrayList<>();
for (int i = 0; i < items.size(); i++) {
JsonNode item = items.get(i);
String at = path + ".items[" + i + "]";
if (!item.isObject()) {
error(issues, at, "元素必须是对象");
continue;
}
String id = item.path("id").stringValue("");
if (id.isBlank() || !ids.add(id)) error(issues, at + ".id", "ID 为空或重复");
if (id.length() > MAX_ID_LENGTH) warn(issues, at + ".id", "ID 过长,建议不超过 " + MAX_ID_LENGTH + " 字符");
JsonNode typeNode = item.path("type");
String type = typeNode.stringValue("");
if (!typeNode.isTextual()) error(issues, at + ".type", "元素类型必须是字符串");
else if (!TYPES.contains(type)) warn(issues, at + ".type", "未知类型,手机会跳过此元素");
if (!optional(item, "z", LayoutValidator::integer)) error(issues, at + ".z", "层级必须是整数");
if (validCoordinates(item)) {
float x = item.get("x").floatValue();
float y = item.get("y").floatValue();
float right = x + item.get("w").floatValue();
float bottom = y + item.get("h").floatValue();
if (right > width + 0.5f || bottom > height + 0.5f) error(issues, at, "元素超出画布");
if (y < safeTop || bottom > (long) height - safeBottom) warn(issues, at, "元素进入安全区");
if (!type.equals("dock_bg")) rectangles.add(new Rect(at, x, y, right, bottom));
} else {
error(issues, at, "坐标必须非负且尺寸必须为正数");
}
validatePayload(issues, item, at, type);
}
for (int i = 0; i < rectangles.size(); i++) {
Rect a = rectangles.get(i);
for (int j = i + 1; j < rectangles.size(); j++) {
Rect b = rectangles.get(j);
if (a.x < b.right && a.right > b.x && a.y < b.bottom && a.bottom > b.y) {
warn(issues, a.path, "元素与同页其他元素重叠");
break;
}
}
}
}
private void validatePayload(List<Issue> issues, JsonNode item, String path, String type) {
JsonNode payload = item.path("payload");
if (!optional(item, "payload", n -> n.isObject()
&& optionalFields(n, LayoutValidator::nullableText, "label", "package", "provider", "intent")
&& optional(n, "radius", value -> value.isNull() || integer(value)))) {
error(issues, path + ".payload", "内容字段格式错误");
return;
}
if (type.equals("app_icon") && payload.path("package").stringValue("").isBlank()) {
error(issues, path + ".payload.package", "应用图标需要包名");
}
if (type.equals("widget") && !payload.path("provider").stringValue("").contains("/")) {
error(issues, path + ".payload.provider", "组件需填写包名/类名");
}
if (payload.path("label").stringValue("").length() > MAX_LABEL_LENGTH) {
warn(issues, path + ".payload.label", "显示名过长,可能被截断");
}
JsonNode radius = payload.get("radius");
if (radius != null && integer(radius) && radius.intValue() < 0) {
warn(issues, path + ".payload.radius", "圆角不能为负数");
}
String intent = payload.path("intent").stringValue("");
if (!intent.isEmpty() && !SCHEME.matcher(intent).matches()) {
warn(issues, path + ".payload.intent", "快捷方式 intent 应使用 scheme:// 形式");
}
}
private static boolean validCoordinates(JsonNode item) {
JsonNode x = item.path("x"), y = item.path("y"), w = item.path("w"), h = item.path("h");
return finiteFloat(x) && finiteFloat(y) && finiteFloat(w) && finiteFloat(h)
&& x.doubleValue() >= 0 && y.doubleValue() >= 0 && w.floatValue() > 0 && h.floatValue() > 0;
}
private static boolean optionalFields(JsonNode node, Predicate<JsonNode> check, String... names) {
for (String name : names) {
if (!optional(node, name, check)) return false;
}
return true;
}
private static boolean optional(JsonNode node, String name, Predicate<JsonNode> check) {
JsonNode value = node.get(name);
return value == null || check.test(value);
}
private static boolean integer(JsonNode n) {
return n.isNumber() && n.canConvertToExactIntegral() && n.canConvertToInt();
}
private static boolean finiteFloat(JsonNode n) {
return n.isNumber() && Float.isFinite(n.floatValue());
}
private static boolean nullableText(JsonNode n) {
return n.isNull() || n.isTextual();
}
private static void error(List<Issue> issues, String path, String message) {
issues.add(new Issue("error", path, message));
}
private static void warn(List<Issue> issues, String path, String message) {
issues.add(new Issue("warning", path, message));
}
}
@@ -0,0 +1,64 @@
package com.ttstd.launcher;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
class RequestPolicy extends OncePerRequestFilter {
private final byte[] admin;
private final byte[] device;
RequestPolicy(@Value("${launcher.admin-token}") String adminToken,
@Value("${launcher.device-token}") String deviceToken) {
if (!adminToken.matches("[!-~]{24,256}") || !deviceToken.matches("[!-~]{24,256}")
|| adminToken.equals(deviceToken)) {
throw new IllegalArgumentException("请配置两组不同的 ADMIN_TOKEN 和 DEVICE_TOKEN,各使用 24–256 位可打印 ASCII 字符");
}
this.admin = sha256("Bearer " + adminToken);
this.device = sha256("Bearer " + deviceToken);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
response.setHeader("Cache-Control", "no-store");
response.setHeader("X-Content-Type-Options", "nosniff");
response.setHeader("Referrer-Policy", "no-referrer");
// Match the decoded paths using Spring MVC itself, then authorize each mapped API handler.
chain.doFilter(request, response);
}
void requireAdmin(HttpServletRequest request, HttpServletResponse response) {
require(request, response, admin);
}
void requireDevice(HttpServletRequest request, HttpServletResponse response) {
require(request, response, device);
}
private void require(HttpServletRequest request, HttpServletResponse response, byte[] expected) {
String header = request.getHeader("Authorization");
if (header == null || !MessageDigest.isEqual(sha256(header), expected)) {
response.setHeader("WWW-Authenticate", "Bearer");
throw new ApiError(401, "访问令牌无效");
}
}
static byte[] sha256(String text) {
try {
return MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8));
} catch (NoSuchAlgorithmException error) {
throw new IllegalStateException(error);
}
}
}
@@ -0,0 +1,9 @@
spring.application.name=vibe-launcher
server.address=${HOST:127.0.0.1}
server.port=${PORT:8080}
server.tomcat.connection-timeout=10s
spring.web.resources.add-mappings=false
spring.mvc.throw-exception-if-no-handler-found=true
launcher.admin-token=${ADMIN_TOKEN:}
launcher.device-token=${DEVICE_TOKEN:}
launcher.database=${LAYOUT_DB:backend/data/layouts.sqlite}
@@ -0,0 +1,24 @@
package com.ttstd.launcher;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.nio.file.Path;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
class LauncherApplicationTest {
@TempDir Path temp;
@Test
void startsAndSeedsNewDatabase() throws Exception {
try (var context = new SpringApplicationBuilder(LauncherApplication.class)
.web(WebApplicationType.NONE)
.run("--launcher.admin-token=test-launcher-admin-token-24",
"--launcher.device-token=test-launcher-device-token-24",
"--launcher.database=" + temp.resolve("new.sqlite"))) {
assertEquals(1, context.getBean(LayoutStore.class).latest().revision());
}
}
}
@@ -0,0 +1,239 @@
package com.ttstd.launcher;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.sql.DriverManager;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.databind.node.ObjectNode;
class LayoutApiTest {
private static final String ADMIN = "Bearer test-launcher-admin-token-24";
private static final String DEVICE = "Bearer test-launcher-device-token-24";
private static final String ADMIN_LAYOUT = "/api/admin/layout";
private final JsonMapper mapper = JsonMapper.builder().build();
@TempDir Path dir;
@Test
void migratedDatabaseRetainsLayoutsAndSupportsPublishRollbackAndRestart() throws Exception {
Path database = dir.resolve("layouts.sqlite");
String legacyLayout;
try (var input = new ClassPathResource("launcher/default_layout.json").getInputStream()) {
legacyLayout = new String(input.readAllBytes(), StandardCharsets.UTF_8);
}
try (var connection = DriverManager.getConnection("jdbc:sqlite:" + database);
var statement = connection.createStatement()) {
statement.execute("""
CREATE TABLE releases (
revision INTEGER PRIMARY KEY CHECK (revision BETWEEN 1 AND 2147483647),
layout TEXT NOT NULL,
publishedAt TEXT NOT NULL,
restoredFrom INTEGER REFERENCES releases(revision)
) STRICT
""");
try (var insert = connection.prepareStatement("INSERT INTO releases VALUES (1, ?, '2026-01-01T00:00:00.000Z', NULL)")) {
insert.setString(1, legacyLayout);
insert.executeUpdate();
}
}
MockMvc mvc = mvc(database);
var editor = mvc.perform(get("/")).andExpect(status().isOk()).andReturn().getResponse();
assertTrue(editor.getHeader("Content-Security-Policy").contains("script-src 'self'"));
String html = editor.getContentAsString(StandardCharsets.UTF_8);
assertEquals(html, mvc.perform(get("/canvas.html")).andExpect(status().isOk())
.andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8));
var js = Pattern.compile("src=\"\\./(assets/[^\"]+\\.js)\"").matcher(html);
assertTrue(js.find());
mvc.perform(get("/" + js.group(1))).andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith("text/javascript"));
var css = Pattern.compile("href=\"\\./(assets/[^\"]+\\.css)\"").matcher(html);
assertTrue(css.find());
mvc.perform(get("/" + css.group(1))).andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith("text/css"));
mvc.perform(get("/assets/invalid.js")).andExpect(status().isNotFound());
mvc.perform(get("/healthz")).andExpect(status().isOk());
mvc.perform(get("/api/layout")).andExpect(status().isUnauthorized())
.andExpect(header().string("WWW-Authenticate", "Bearer"));
mvc.perform(get("/api/admin/history").header("Authorization", DEVICE)).andExpect(status().isUnauthorized());
var original = mvc.perform(get("/api/layout").header("Authorization", DEVICE))
.andExpect(status().isOk()).andExpect(header().string("X-Layout-Revision", "1"))
.andReturn().getResponse();
assertEquals(legacyLayout, original.getContentAsString(StandardCharsets.UTF_8));
String tag = original.getHeader("ETag");
assertEquals(new LayoutStore.Release(1, legacyLayout).etag(), tag);
mvc.perform(get("/api/layout").header("Authorization", DEVICE).header("If-None-Match", tag))
.andExpect(status().isNotModified()).andExpect(header().string("ETag", tag));
mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).contentType(MediaType.APPLICATION_JSON)
.content(legacyLayout)).andExpect(status().isPreconditionRequired());
mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag)
.contentType(MediaType.APPLICATION_JSON).content("{} {}")).andExpect(status().isBadRequest());
mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag)
.contentType(MediaType.APPLICATION_JSON).content(new byte[LayoutStore.MAX_BYTES + 1]))
.andExpect(status().is(413));
var invalid = mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag)
.contentType(MediaType.APPLICATION_JSON).content("{\"schemaVersion\":2,\"pages\":[]}"))
.andExpect(status().is(422)).andReturn().getResponse();
assertTrue(mapper.readTree(invalid.getContentAsByteArray()).path("issues").size() >= 2);
var changed = (ObjectNode) mapper.readTree(legacyLayout);
changed.put("futureField", "同步验证");
String body = mapper.writeValueAsString(changed);
Callable<Integer> publish = () -> mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN)
.header("If-Match", tag).contentType(MediaType.APPLICATION_JSON).content(body))
.andReturn().getResponse().getStatus();
var executor = Executors.newFixedThreadPool(2);
try {
var outcomes = executor.invokeAll(List.of(publish, publish));
assertEquals(List.of(200, 412), List.of(outcomes.get(0).get(), outcomes.get(1).get()).stream().sorted().toList());
} finally {
executor.shutdownNow();
}
var posted = mvc.perform(get("/api/admin/history/2").header("Authorization", ADMIN))
.andExpect(status().isOk()).andReturn().getResponse();
assertEquals("同步验证", mapper.readTree(posted.getContentAsByteArray()).path("futureField").stringValue());
assertNotNull(posted.getHeader("ETag"));
mvc.perform(post("/api/admin/rollback").header("Authorization", ADMIN)
.header("If-Match", posted.getHeader("ETag")).contentType(MediaType.APPLICATION_JSON)
.content("{\"revision\":1}"))
.andExpect(status().isOk()).andExpect(header().string("X-Layout-Revision", "3"));
MockMvc restarted = mvc(database);
var history = restarted.perform(get("/api/admin/history").header("Authorization", ADMIN))
.andExpect(status().isOk()).andReturn().getResponse();
var revisions = mapper.readTree(history.getContentAsByteArray()).path("revisions");
assertEquals(3, revisions.size());
assertEquals(1, revisions.get(0).path("restoredFrom").intValue());
var latest = restarted.perform(get("/api/layout").header("Authorization", DEVICE))
.andExpect(status().isOk()).andReturn().getResponse();
assertEquals(((ObjectNode) mapper.readTree(legacyLayout)).put("revision", 3),
mapper.readTree(latest.getContentAsByteArray()));
}
@Test
void errorsAreReturnedAsJson() throws Exception {
MockMvc mvc = mvc(dir.resolve("errors.sqlite"));
var unauthorized = mvc.perform(get(ADMIN_LAYOUT)).andExpect(status().isUnauthorized())
.andReturn().getResponse();
assertEquals("访问令牌无效", message(unauthorized.getContentAsByteArray()));
var wrongMethod = mvc.perform(post("/healthz")).andExpect(status().isMethodNotAllowed())
.andReturn().getResponse();
assertEquals("不支持的请求方法", message(wrongMethod.getContentAsByteArray()));
var badPage = mvc.perform(get("/api/admin/history").header("Authorization", ADMIN).param("before", "abc"))
.andExpect(status().isBadRequest()).andReturn().getResponse();
assertEquals("无效的分页参数", message(badPage.getContentAsByteArray()));
var tag = mvc.perform(get(ADMIN_LAYOUT).header("Authorization", ADMIN))
.andExpect(status().isOk()).andReturn().getResponse().getHeader("ETag");
var badRevision = mvc.perform(post("/api/admin/rollback").header("Authorization", ADMIN)
.header("If-Match", tag).contentType(MediaType.APPLICATION_JSON).content("{\"revision\":0}"))
.andExpect(status().isBadRequest()).andReturn().getResponse();
assertEquals("无效的回滚版本号", message(badRevision.getContentAsByteArray()));
var missing = mvc.perform(get("/api/admin/history/999").header("Authorization", ADMIN))
.andExpect(status().isNotFound()).andReturn().getResponse();
assertEquals("该版本不存在", message(missing.getContentAsByteArray()));
}
@Test
void historyIsPagedWithNextBefore() throws Exception {
Path database = dir.resolve("paged.sqlite");
var store = new LayoutStore(database.toString(), mapper, new LayoutValidator());
String layout = store.latest().layout();
try (var connection = DriverManager.getConnection("jdbc:sqlite:" + database);
var insert = connection.prepareStatement("""
INSERT INTO releases (revision, layout, publishedAt, restoredFrom) VALUES (?, ?, ?, NULL)
""")) {
for (int revision = 2; revision <= 101; revision++) {
insert.setInt(1, revision);
insert.setString(2, layout);
insert.setString(3, "2026-01-01T00:00:00Z");
insert.executeUpdate();
}
}
MockMvc mvc = mvc(database);
var first = mapper.readTree(mvc.perform(get("/api/admin/history").header("Authorization", ADMIN))
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
assertEquals(50, first.path("revisions").size());
assertEquals(101, first.path("revisions").get(0).path("revision").intValue());
assertEquals(52, first.path("nextBefore").intValue());
var second = mapper.readTree(mvc.perform(get("/api/admin/history").header("Authorization", ADMIN)
.param("before", "52")).andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
assertEquals(50, second.path("revisions").size());
assertEquals(2, second.path("nextBefore").intValue());
var last = mapper.readTree(mvc.perform(get("/api/admin/history").header("Authorization", ADMIN)
.param("before", "2")).andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
assertEquals(1, last.path("revisions").size());
assertTrue(last.path("nextBefore").isNull());
}
@Test
void rejectsOversizedCanvasAndInvalidRollbackSource() throws Exception {
Path database = dir.resolve("guarded.sqlite");
MockMvc mvc = mvc(database);
var tag = mvc.perform(get(ADMIN_LAYOUT).header("Authorization", ADMIN))
.andExpect(status().isOk()).andReturn().getResponse().getHeader("ETag");
var layout = (ObjectNode) mapper.readTree(new ClassPathResource("launcher/default_layout.json").getInputStream());
((ObjectNode) layout.get("canvas")).put("designWidth", 9000);
var invalid = mvc.perform(put(ADMIN_LAYOUT).header("Authorization", ADMIN).header("If-Match", tag)
.contentType(MediaType.APPLICATION_JSON).content(mapper.writeValueAsString(layout)))
.andExpect(status().is(422)).andReturn().getResponse();
assertTrue(mapper.readTree(invalid.getContentAsByteArray()).path("issues").toString().contains("canvas"));
try (var connection = DriverManager.getConnection("jdbc:sqlite:" + database);
var statement = connection.createStatement()) {
statement.executeUpdate("""
INSERT INTO releases (revision, layout, publishedAt, restoredFrom)
VALUES (2, '{"schemaVersion":2,"pages":[]}', '2026-01-01T00:00:00Z', NULL)
""");
}
var latestTag = mvc.perform(get(ADMIN_LAYOUT).header("Authorization", ADMIN))
.andExpect(status().isOk()).andReturn().getResponse().getHeader("ETag");
var rollback = mvc.perform(post("/api/admin/rollback").header("Authorization", ADMIN)
.header("If-Match", latestTag).contentType(MediaType.APPLICATION_JSON)
.content("{\"revision\":2}"))
.andExpect(status().is(422)).andReturn().getResponse();
assertEquals("历史版本布局校验失败,无法回滚", message(rollback.getContentAsByteArray()));
}
private String message(byte[] body) throws Exception {
return mapper.readTree(body).path("message").stringValue();
}
private MockMvc mvc(Path database) throws Exception {
var validator = new LayoutValidator();
var store = new LayoutStore(database.toString(), mapper, validator);
var policy = new RequestPolicy(ADMIN.substring(7), DEVICE.substring(7));
return MockMvcBuilders.standaloneSetup(new LayoutController(store, policy, validator, mapper))
.setControllerAdvice(new ApiExceptionHandler())
.addFilters(policy).build();
}
}
@@ -0,0 +1,115 @@
package com.ttstd.launcher;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import tools.jackson.databind.json.JsonMapper;
class LayoutValidatorTest {
private final LayoutValidator validator = new LayoutValidator();
private final JsonMapper mapper = JsonMapper.builder().build();
@Test
void builtInLayoutHasNoErrors() throws Exception {
try (var input = new ClassPathResource("launcher/default_layout.json").getInputStream()) {
var layout = mapper.readTree(new String(input.readAllBytes(), StandardCharsets.UTF_8));
assertTrue(validator.validate(layout).stream().noneMatch(issue -> issue.level().equals("error")));
}
}
@Test
void rejectsBrokenProtocolFields() throws Exception {
var issues = issues("""
{
"schemaVersion": 2,
"canvas": {"designWidth": 100, "designHeight": 100, "safeTop": -1, "safeBottom": 0},
"fit": {"mode": "contain", "anchorY": 0.5},
"pages": [{
"index": 0,
"background": {"type": "wallpaper"},
"items": [
{"id": "", "type": "app_icon", "x": -1, "y": 0, "w": 0, "h": 10, "z": 1,
"payload": {"package": ""}},
{"id": "", "type": "widget", "x": 10, "y": 10, "w": 10, "h": 10, "z": 1,
"payload": {"provider": "nocomponent"}}
]
}]
}
""");
assertTrue(hasError(issues, "schemaVersion"));
assertTrue(hasError(issues, "canvas"));
assertTrue(hasError(issues, "pages[0].items[0].id"));
assertTrue(hasError(issues, "pages[0].items[0].payload.package"));
assertTrue(hasError(issues, "pages[0].items[1].payload.provider"));
}
@Test
void rejectsOversizedCanvasAndEmptyPages() throws Exception {
var issues = issues("""
{"schemaVersion":3,"canvas":{"designWidth":9000,"designHeight":9000},"pages":[]}
""");
assertTrue(hasError(issues, "canvas"));
assertTrue(hasError(issues, "pages"));
}
@Test
void warnsOnProtocolEdgeCases() throws Exception {
var issues = issues("""
{
"schemaVersion": 3,
"canvas": {"designWidth": 1080, "designHeight": 1920, "safeTop": 132, "safeBottom": 72},
"fit": {"mode": "unknown", "anchorY": 1.4},
"pages": [
{"index": 1, "background": {"type": "image", "color": "white"},
"items": [{"id": "%s", "type": "mystery", "x": 0, "y": 0, "w": 10, "h": 10, "z": 1,
"payload": {"label": "%s", "radius": -1, "intent": "bad"}}]},
{"index": 1, "background": {"type": "gradient", "from": "#ffffff"}, "items": []}
]
}
""".formatted("x".repeat(65), "标题".repeat(60)));
assertTrue(issues.stream().noneMatch(issue -> issue.level().equals("error")));
for (String path : List.of("fit.mode", "fit.anchorY", "pages[0].index", "pages[1].index",
"pages[0].background.type", "pages[0].background.color", "pages[1].background",
"pages[0].items[0].id", "pages[0].items[0].type", "pages[0].items[0].payload.label",
"pages[0].items[0].payload.radius", "pages[0].items[0].payload.intent")) {
assertTrue(issues.stream().anyMatch(issue -> issue.level().equals("warning") && issue.path().equals(path)),
"缺少告警:" + path);
}
}
@Test
void warnsOnSmallSafeAreasLikeTheEditor() throws Exception {
var issues = issues("""
{"schemaVersion":3,
"canvas":{"designWidth":1080,"designHeight":1920,"safeTop":100,"safeBottom":20},
"pages":[{"index":0,"background":{"type":"wallpaper"},"items":[]}]}
""");
assertTrue(issues.stream().anyMatch(issue -> issue.level().equals("warning")
&& issue.path().equals("canvas.safeTop")));
assertTrue(issues.stream().anyMatch(issue -> issue.level().equals("warning")
&& issue.path().equals("canvas.safeBottom")));
assertTrue(issues.stream().noneMatch(issue -> issue.level().equals("error")));
}
@Test
void acceptsUnknownTopLevelFields() throws Exception {
var issues = issues("""
{"schemaVersion":3,"futureField":{"a":1},
"canvas":{"designWidth":1080,"designHeight":1920},
"pages":[{"index":0,"background":{"type":"wallpaper"},"items":[]}]}
""");
assertEquals(List.of(), issues.stream().filter(issue -> issue.level().equals("error")).toList());
}
private List<LayoutValidator.Issue> issues(String json) throws Exception {
return validator.validate(mapper.readTree(json));
}
private static boolean hasError(List<LayoutValidator.Issue> issues, String path) {
return issues.stream().anyMatch(issue -> issue.level().equals("error") && issue.path().equals(path));
}
}
@@ -0,0 +1,79 @@
package com.ttstd.launcher;
import static java.util.stream.Collectors.joining;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import tools.jackson.databind.json.JsonMapper;
class UniformityTest {
private final LayoutValidator validator = new LayoutValidator();
private final JsonMapper mapper = JsonMapper.builder().build();
@Test
void sharedLayoutCases() throws Exception {
var fixtures = Path.of("..", "docs", "layout-cases.json");
for (var fixture : mapper.readTree(fixtures.toFile())) {
assertEquals(fixture.path("accepted").booleanValue(),
errors(validator.validate(fixture.path("layout"))).isEmpty(),
fixture.path("name").stringValue());
}
}
@Test
void builtInLayoutMatchesProtocolBaseline() throws Exception {
var layout = mapper.readTree(read("launcher/default_layout.json"));
assertTrue(errors(validator.validate(layout)).isEmpty());
assertEquals(3, layout.path("schemaVersion").intValue());
assertEquals(1080, layout.path("canvas").path("designWidth").intValue());
assertEquals(1920, layout.path("canvas").path("designHeight").intValue());
assertEquals(132, layout.path("canvas").path("safeTop").intValue());
assertEquals(72, layout.path("canvas").path("safeBottom").intValue());
}
@Test
void protocolLimitsMatchEditorAndAndroid() throws Exception {
String page = "{\"index\":%d,\"background\":{\"type\":\"wallpaper\"},\"items\":[]}";
String pages20 = IntStream.range(0, 20).mapToObj(i -> page.formatted(i)).collect(joining(","));
String pages21 = IntStream.range(0, 21).mapToObj(i -> page.formatted(i)).collect(joining(","));
assertTrue(errors(validator.validate(mapper.readTree(layout(320, 480, "[" + pages20 + "]")))).isEmpty());
assertTrue(errors(validator.validate(mapper.readTree(layout(320, 480, "[" + pages21 + "]"))))
.stream().anyMatch(issue -> issue.path().equals("pages")));
assertTrue(errors(validator.validate(mapper.readTree(layout(319, 480, "["
+ page.formatted(0) + "]")))).stream().anyMatch(issue -> issue.path().equals("canvas")));
assertTrue(errors(validator.validate(mapper.readTree(layout(8193, 1920, "["
+ page.formatted(0) + "]")))).stream().anyMatch(issue -> issue.path().equals("canvas")));
String item = "{\"id\":\"i%d\",\"type\":\"app_icon\",\"x\":0,\"y\":0,\"w\":10,\"h\":10,\"z\":1,"
+ "\"payload\":{\"package\":\"com.demo.app\"}}";
String items80 = IntStream.range(0, 80).mapToObj(i -> item.formatted(i)).collect(joining(","));
String page80 = "{\"index\":0,\"background\":{\"type\":\"wallpaper\"},\"items\":[" + items80 + "]}";
assertTrue(errors(validator.validate(mapper.readTree(layout(1080, 1920, "[" + page80 + "]")))).isEmpty());
String items81 = items80 + "," + item.formatted(80);
String page81 = "{\"index\":0,\"background\":{\"type\":\"wallpaper\"},\"items\":[" + items81 + "]}";
assertTrue(errors(validator.validate(mapper.readTree(layout(1080, 1920, "[" + page81 + "]"))))
.stream().anyMatch(issue -> issue.path().equals("pages[0].items")));
}
private static String layout(int width, int height, String pages) {
return "{\"schemaVersion\":3,\"canvas\":{\"designWidth\":" + width
+ ",\"designHeight\":" + height + "},\"pages\":" + pages + "}";
}
private static List<LayoutValidator.Issue> errors(List<LayoutValidator.Issue> issues) {
return issues.stream().filter(issue -> issue.level().equals("error")).toList();
}
private static String read(String resource) throws Exception {
try (var input = new ClassPathResource(resource).getInputStream()) {
return new String(input.readAllBytes(), StandardCharsets.UTF_8);
}
}
}