Skip to content

Commit a1bcc9e

Browse files
committed
Split rule code and CraftEngine resource artifacts
1 parent da24360 commit a1bcc9e

84 files changed

Lines changed: 1665 additions & 457 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/rule-registry.yml‎

Lines changed: 166 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -67,41 +67,188 @@ jobs:
6767
rmdir "$temporary"
6868
done
6969
done
70-
- name: Verify entries and their downloadable JAR bytes
70+
- name: Verify entries and both downloadable artifact types
7171
shell: bash
7272
run: |
7373
set -euo pipefail
7474
python3 - <<'PY'
7575
import datetime
7676
import hashlib
77+
import io
7778
import json
7879
import pathlib
7980
import re
8081
import urllib.parse
8182
import urllib.request
83+
import zipfile
8284
8385
expected_repositories = {
8486
"riichi": "riichi-mahjong-java",
8587
"mcr": "mahjong-mcr-java",
8688
"sichuan": "sichuan-mahjong-java",
8789
}
88-
exact_keys = {
90+
code_keys = {
8991
"id", "version", "url", "sha256", "spiVersion",
9092
"requiredCoreVersion", "sizeBytes",
9193
}
94+
resource_keys = code_keys | {
95+
"resourceUrl", "resourceSha256", "resourceSizeBytes",
96+
}
97+
98+
def verify_download(url, expected_size, expected_sha256):
99+
request = urllib.request.Request(url, headers={"User-Agent": "MahjongEngine-registry-builder"})
100+
digest = hashlib.sha256()
101+
total = 0
102+
content = bytearray()
103+
with urllib.request.urlopen(request, timeout=120) as response:
104+
while chunk := response.read(65536):
105+
total += len(chunk)
106+
if total > 64 * 1024 * 1024:
107+
raise SystemExit(f"artifact too large: {url}")
108+
digest.update(chunk)
109+
content.extend(chunk)
110+
if total != expected_size or digest.hexdigest() != expected_sha256:
111+
raise SystemExit(f"artifact bytes differ: {url}")
112+
return bytes(content)
113+
114+
def properties(data, label):
115+
result = {}
116+
for raw in data.decode("utf-8").splitlines():
117+
line = raw.strip()
118+
if not line or line.startswith(("#", "!")):
119+
continue
120+
separator = line.find("=")
121+
if separator < 1:
122+
raise SystemExit(f"malformed {label}")
123+
key, value = line[:separator].strip(), line[separator + 1:].strip()
124+
if not key or key in result:
125+
raise SystemExit(f"duplicate {label} key: {key}")
126+
result[key] = value
127+
return result
128+
129+
def verify_resource_archive(content, rule_id, version):
130+
required = {
131+
"META-INF/mahjong-rule-resources.properties",
132+
"META-INF/mahjong-rule-sounds.properties",
133+
"META-INF/RESOURCEPACK_ATTRIBUTION.md",
134+
"craftengine/_bundle_index.txt",
135+
"craftengine/_bundle_manifest.sha256",
136+
"craftengine/pack.yml",
137+
}
138+
with zipfile.ZipFile(io.BytesIO(content)) as archive:
139+
files = {}
140+
total_uncompressed = 0
141+
if len(archive.infolist()) > 20_000:
142+
raise SystemExit("rule resource ZIP has too many entries")
143+
for item in archive.infolist():
144+
name = item.filename
145+
parts = pathlib.PurePosixPath(name.rstrip("/")).parts
146+
if ("\\" in name or name.startswith("/") or ".." in parts
147+
or not parts or item.file_size < 0
148+
or item.file_size > 64 * 1024 * 1024):
149+
raise SystemExit(f"unsafe rule resource path: {name}")
150+
if item.is_dir():
151+
continue
152+
total_uncompressed += item.file_size
153+
if total_uncompressed > 256 * 1024 * 1024:
154+
raise SystemExit("rule resource ZIP exceeds expansion limit")
155+
lower = name.lower()
156+
allowed_meta = (name in required
157+
or name.startswith("META-INF/licenses/"))
158+
if (lower.endswith((".class", ".jar", ".java"))
159+
or name.startswith("META-INF/services/")
160+
or (not name.startswith("craftengine/") and not allowed_meta)):
161+
raise SystemExit(f"non-CE rule resource payload: {name}")
162+
if name in files:
163+
raise SystemExit(f"duplicate rule resource path: {name}")
164+
files[name] = archive.read(item)
165+
if not required.issubset(files):
166+
raise SystemExit("rule resource ZIP is missing required CE metadata")
167+
168+
descriptor = properties(
169+
files["META-INF/mahjong-rule-resources.properties"],
170+
"rule resource descriptor",
171+
)
172+
if descriptor != {"format": "1", "id": rule_id, "version": version}:
173+
raise SystemExit("rule resource descriptor differs from release coordinate")
174+
175+
namespace = "mahjong_" + rule_id + "_v" + re.sub(
176+
r"[^0-9A-Za-z]", "_", version,
177+
).lower()
178+
sounds = properties(
179+
files["META-INF/mahjong-rule-sounds.properties"],
180+
"rule sound descriptor",
181+
)
182+
if (not sounds or any(
183+
not value.split(",", 1)[0].strip().startswith(namespace + ":")
184+
for value in sounds.values())):
185+
raise SystemExit("rule sounds must use a version-isolated CE namespace")
186+
registry_path = (
187+
f"craftengine/resourcepack/assets/{namespace}/sounds.json"
188+
)
189+
if registry_path not in files:
190+
raise SystemExit("versioned CraftEngine sounds.json is missing")
191+
namespace_lines = [
192+
line.strip()
193+
for line in files["craftengine/pack.yml"]
194+
.decode("utf-8").splitlines()
195+
if line.strip().startswith("namespace:")
196+
]
197+
if namespace_lines != [f"namespace: {namespace}"]:
198+
raise SystemExit("CraftEngine pack namespace differs from rule version")
199+
registry = json.loads(files[registry_path])
200+
for value in sounds.values():
201+
event = value.split(",", 1)[0].split(":", 1)[1]
202+
if event not in registry:
203+
raise SystemExit(f"sounds.json has no event: {event}")
204+
205+
index = {
206+
line.strip()
207+
for line in files["craftengine/_bundle_index.txt"]
208+
.decode("utf-8").splitlines()
209+
if line.strip()
210+
}
211+
actual = {
212+
name.removeprefix("craftengine/")
213+
for name in files
214+
if name.startswith("craftengine/")
215+
and name != "craftengine/_bundle_index.txt"
216+
}
217+
if index != actual or "_bundle_manifest.sha256" not in index:
218+
raise SystemExit("CraftEngine bundle index differs from ZIP contents")
219+
manifest = {}
220+
for line in (
221+
files["craftengine/_bundle_manifest.sha256"]
222+
.decode("utf-8").splitlines()
223+
):
224+
digest, separator, name = line.partition(" ")
225+
if (separator != " " or not re.fullmatch(r"[0-9a-f]{64}", digest)
226+
or not name or name in manifest):
227+
raise SystemExit("invalid CraftEngine bundle manifest")
228+
manifest[name] = digest
229+
content_names = index - {"_bundle_manifest.sha256"}
230+
if set(manifest) != content_names:
231+
raise SystemExit("CraftEngine index and manifest differ")
232+
for name, digest in manifest.items():
233+
if hashlib.sha256(files["craftengine/" + name]).hexdigest() != digest:
234+
raise SystemExit(f"CraftEngine content hash mismatch: {name}")
235+
92236
entries = []
93237
coordinates = set()
94238
seen_ids = set()
95239
for path in sorted(pathlib.Path("registry-entries").glob("*.json")):
96240
entry = json.loads(path.read_text(encoding="utf-8"))
97-
if set(entry) != exact_keys:
241+
if set(entry) not in (code_keys, resource_keys):
98242
raise SystemExit(f"unexpected fields in {path}: {set(entry)}")
99243
rule_id = entry["id"]
100244
if rule_id not in expected_repositories:
101245
raise SystemExit(f"unofficial rule id in {path}: {rule_id}")
102246
version = entry["version"]
103247
if not re.fullmatch(r"[0-9A-Za-z][0-9A-Za-z._+-]{0,63}", version):
104248
raise SystemExit(f"invalid version in {path}")
249+
semantic = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)(?:[-+].*)?", version)
250+
if semantic and tuple(map(int, semantic.groups())) >= (2, 0, 2) and set(entry) != resource_keys:
251+
raise SystemExit(f"rule versions 2.0.2+ require a resource artifact: {path}")
105252
coordinate = (rule_id, version)
106253
if coordinate in coordinates:
107254
raise SystemExit(f"duplicate coordinate: {coordinate}")
@@ -117,23 +264,27 @@ jobs:
117264
expected_prefix = f"/EllanServer/{expected_repositories[rule_id]}/releases/download/v{version}/"
118265
if parsed.scheme != "https" or parsed.netloc != "github.com" or not parsed.path.startswith(expected_prefix):
119266
raise SystemExit(f"unexpected artifact URL in {path}: {entry['url']}")
120-
request = urllib.request.Request(entry["url"], headers={"User-Agent": "MahjongEngine-registry-builder"})
121-
digest = hashlib.sha256()
122-
total = 0
123-
with urllib.request.urlopen(request, timeout=120) as response:
124-
while chunk := response.read(65536):
125-
total += len(chunk)
126-
if total > 64 * 1024 * 1024:
127-
raise SystemExit(f"artifact too large: {entry['url']}")
128-
digest.update(chunk)
129-
if total != entry["sizeBytes"] or digest.hexdigest() != entry["sha256"]:
130-
raise SystemExit(f"artifact bytes differ from {path}")
267+
verify_download(entry["url"], entry["sizeBytes"], entry["sha256"])
268+
if set(entry) == resource_keys:
269+
if not isinstance(entry["resourceSizeBytes"], int) or not 1 <= entry["resourceSizeBytes"] <= 64 * 1024 * 1024:
270+
raise SystemExit(f"invalid resource size in {path}")
271+
if not re.fullmatch(r"[0-9a-f]{64}", entry["resourceSha256"]):
272+
raise SystemExit(f"invalid resource SHA-256 in {path}")
273+
resource_parsed = urllib.parse.urlparse(entry["resourceUrl"])
274+
if resource_parsed.scheme != "https" or resource_parsed.netloc != "github.com" or not resource_parsed.path.startswith(expected_prefix):
275+
raise SystemExit(f"unexpected resource URL in {path}: {entry['resourceUrl']}")
276+
resource_content = verify_download(
277+
entry["resourceUrl"],
278+
entry["resourceSizeBytes"],
279+
entry["resourceSha256"],
280+
)
281+
verify_resource_archive(resource_content, rule_id, version)
131282
entries.append(entry)
132283
133284
if seen_ids != set(expected_repositories):
134285
raise SystemExit(f"registry must include all official ids; got {seen_ids}")
135286
generated = datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
136-
payload = {"format": 1, "generatedAt": generated, "packs": sorted(entries, key=lambda item: (item["id"], item["version"]))}
287+
payload = {"format": 2, "generatedAt": generated, "packs": sorted(entries, key=lambda item: (item["id"], item["version"]))}
137288
pathlib.Path("registry-payload.json").write_text(
138289
json.dumps(payload, ensure_ascii=True, separators=(",", ":")),
139290
encoding="utf-8",

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
dependency.
1010
- Added the signed rule-pack SPI/runtime, per-table bounded actor, fair bounded rule execution,
1111
memory-first SQL outbox and replayable snapshots.
12+
- Split every official rule version into a pure rule JAR and a separately signed resource ZIP;
13+
the plugin retains common table/chair/tile visuals while rule-owned sounds no longer live in
14+
either the plugin bundle or the rule classloader.
1215
- Moved public scene assets, furniture geometry, hitboxes, seats, interactions, and entity culling
1316
into the CraftEngine bundle. Secret faces remain per-player packet projections.
1417
- Added CE-owned opening-dice slots and face variants; rule packs publish only deterministic dice

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ Create a reusable table with `/mahjong create <riichi|mcr|sichuan> [profile]`. P
1818

1919
All modes share one physical table compiler. A rule pack supplies only its actual tile instances, wall stacks and draw origin, zone ordering, rotations/stacks, and typed action placement; the core contains no 108/136/144-tile mode branches.
2020

21+
The plugin owns the reusable table, chairs, dice and Mahjong tile visuals. Each official rule version is published as two signed artifacts in one release: a pure rule JAR and a resource-only ZIP whose entire payload is a version-isolated CraftEngine pack for that rule's sounds and similar presentation data. The core only authenticates and hands that pack to CraftEngine; the signed registry binds both artifacts to the same rule ID and version.
22+
2123
The former session/controllers, mixed Java/Kotlin rule code, `mahjong-utils`, GB JNI/CMake tree, Display Entity renderer, legacy/shadow modes, and runtime fallback have been removed.
2224

2325
Requirements: Java 25, Paper/Folia 26.2, and CraftEngine 26.7+. The portable core and external rule-pack SDK remain Java 21 contracts; only the server-facing adapters and final plugin target Java 25.

‎README.zh-CN.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ MahjongPaper 2.0 是一个面向 Paper/Folia 的麻将核心插件。核心不
1515
- 签名规则包的下载、校验、独立 classloader、版本固定、隔离失败和重启激活。
1616
- 平台无关 `SceneGraph`、只保留最新帧的异步预计算,以及按 Folia region 公平应用的 CraftEngine 差分。
1717
- CraftEngine 配置负责桌体、座椅、麻将牌姿态、碰撞、交互 hitbox、entity culling 和骰子槽位/face variant;Java 不重复实现这些资产行为,同一骰子只原地切 variant。
18-
- 规则包声明骰点与开门位置,CE 播放固定槽位动画;开门、摸打、吃碰杠和终局音效由 Paper 适配层按玩家调度,音源别名仍由资源包配置。
18+
- 规则包声明骰点与开门位置,CE 播放固定槽位动画;插件主体拥有通用牌桌、凳子和牌,每个规则版本另发布独立的 CraftEngine 资源 ZIP 来提供本玩法的开门、摸打、吃碰杠和终局音效。插件只校验并交付给 CE,纯规则 JAR 不混装任何资源包内容。
1919
- 暗手牌面只通过 Sparrow 客户端假实体发送给授权玩家,不创建含秘密信息的世界实体。
2020
- 大厅可加入可恢复的通用机器人;掉线和 `/mahjong auto` 复用每桌唯一单次任务,日麻、MCR、四川的出牌策略分别由对应规则包实现。
2121
- 房主可通过桌面动作或 `/mahjong owner <seat>` 原子转让给在线真人;命令、动作和反馈由客户端按简体中文、繁体中文、英文或日文渲染。

‎THIRD_PARTY_NOTICES.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,14 @@ MahjongPaper-authored source is offered under the root MIT license. Third-party
1010
- MySQL Connector/J (GPL-2.0 with the Universal FOSS Exception).
1111
- Sparrow Heart 0.72 (MIT) and its required Sparrow Reflection/YAML components. Sparrow Reflection and Sparrow YAML are GPL-3.0; their license text is packaged under `META-INF/licenses`.
1212
- ASM (BSD-3-Clause) and Mapping-IO (Apache-2.0), where pulled by the Sparrow stack; available notices are packaged under `META-INF/licenses`.
13-
- Mahjong tile/resource models derived from MahjongCraft and the additional art/audio sources listed in `resourcepack/ATTRIBUTION.md`; that attribution is packaged in the JAR.
13+
- Shared Mahjong table/tile resource models derived from MahjongCraft and the visual sources listed in `resourcepack/ATTRIBUTION.md`; that attribution is packaged in the plugin JAR.
1414

1515
Because GPL-covered Sparrow components are included in the executable distribution, redistributors must satisfy the applicable GPL source and notice obligations. This notice is not legal advice.
1616

1717
## Supplied separately by the server operator
1818

1919
- Paper/Folia.
2020
- CraftEngine 26.7 or newer.
21-
- The signed Riichi, MCR and Sichuan rule-pack JARs. Each rule repository carries its own notices and dependency boundary.
21+
- The signed Riichi, MCR and Sichuan pure rule JARs and their separately signed resource ZIPs. Each rule resource ZIP carries its own sound attribution and terms.
2222

2323
No GB-Mahjong native source/library, `mahjong-utils`, Kotlin runtime, InvSync or AntiGriefLib is distributed by MahjongPaper 2.0.

‎buildSrc/src/main/kotlin/top/ellan/mahjong/build/CraftEngineBundleGenerator.kt‎

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ object CraftEngineBundleGenerator {
2828
require(configurationFiles.isNotEmpty()) { "No CraftEngine configuration files found" }
2929
verifyTileFactory(configurationFiles, resourcepackDir)
3030
verifyOpeningDice(configurationFiles, resourcepackDir)
31-
verifyFeedbackAssets(resourcepackDir)
3231
verifyLocales(resourcepackDir)
3332

3433
val outputRoot = outputDir.resolve("craftengine").resolve("mahjongpaper")
@@ -132,19 +131,6 @@ object CraftEngineBundleGenerator {
132131
}
133132
}
134133

135-
private fun verifyFeedbackAssets(resourcepackDir: File) {
136-
val sounds =
137-
resourcepackDir
138-
.resolve("assets/mahjongcraft/sounds.json")
139-
.also { require(it.isFile) { "Mahjong sound registry is missing" } }
140-
.readText(Charsets.UTF_8)
141-
listOf("opening_dice", "opening_wall_break").forEach { cue ->
142-
require(Regex("\"${Regex.escape(cue)}\"\\s*:").containsMatchIn(sounds)) {
143-
"Opening sound event is missing: $cue"
144-
}
145-
}
146-
}
147-
148134
private fun verifyLocales(resourcepackDir: File) {
149135
val localeDir = resourcepackDir.resolve("assets/mahjongcraft/lang")
150136
val expected = setOf("en_us", "zh_cn", "zh_tw", "ja_jp")

0 commit comments

Comments
 (0)