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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

InviteCode is a Kotlin invitation and referral rewards plugin for Spigot and Paper. `InviteCodeKt` is the repository name; the plugin and its data directory are named `InviteCode`.

The project is currently `0.1.0-SNAPSHOT`. It builds one Java 8 compatible plugin JAR and keeps newer Minecraft APIs behind isolated adapters. SQLite and MySQL 8.4 are implemented storage backends. The final player experience and cross-version server matrix still require release-stage acceptance.
The project is currently `0.1.0-SNAPSHOT`. It builds one Java 8 compatible plugin JAR and keeps newer Minecraft APIs behind isolated adapters. SQLite and MySQL 8.4 are production storage backends; JSON is available for small single-instance installations. The final player experience and cross-version server matrix still require release-stage acceptance.

The complete maintainer guide is in [繁體中文](docs/README.zh-TW.md) and is the primary maintained documentation. See also the [product specification](docs/spec/invitecode-1.0.md), [Bukkit operations](docs/operations/bukkit-workflow.md), and [MySQL setup](docs/operations/mysql-storage.md). These documents are maintained in Traditional Chinese.
The complete maintainer guide is in [繁體中文](docs/README.zh-TW.md) and is the primary maintained documentation. See also the [product specification](docs/spec/invitecode-1.0.md), [Bukkit operations](docs/operations/bukkit-workflow.md), [JSON setup](docs/operations/json-storage.md), and [MySQL setup](docs/operations/mysql-storage.md). These documents are maintained in Traditional Chinese.

## Build

Expand Down
4 changes: 3 additions & 1 deletion docs/README.zh-TW.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ InviteCode 是從零重寫的 Kotlin Minecraft 邀請與推薦獎勵插件;`In
- 透過 Invite Code 建立一筆永久的 Inviter 與 Invitee 關係。
- 將建立 Invitation 與達成獎勵資格分成不同階段。
- 支援可設定的 Qualification Policy 與可復原的 Reward Delivery。
- 已實作 SQLite 與 MySQL 8.4;JSON 仍是後續規劃。
- 已實作 SQLite 與 MySQL 8.4;JSON 可供小型單實例伺服器、測試與資料交換使用。
- 在不使用 NMS 的前提下維持 Java 8 執行環境相容性。
- 在有能力的新版伺服器使用原生 Dialog 輸入,其餘版本安全退回聊天或指令輸入。

Expand Down Expand Up @@ -68,6 +68,8 @@ SQLite persistence 具備暫存資料庫 contract tests,插件只在專用 exe

MySQL 8.4 使用共用外部 HMAC 密鑰、連線池及具 checksum 與中斷復原檢查的 migration ledger。資料庫須先存在,全新的空白 database 會在插件啟動時自動建表;多個插件實例必須使用同一個密鑰。設定與復原方式請見 [`mysql-storage.md`](./operations/mysql-storage.md)。

JSON 以版本化、可閱讀的資料快照作為持久化來源,沿用 SQLite 的交易約束處理操作;每次寫入都要更新整份檔案,因此僅適合小型單實例環境。設定、備份與錯誤復原方式見 [`json-storage.md`](./operations/json-storage.md)。

Claim 防濫用只保存具期限的 HMAC-SHA-256 網路雜湊,不保存原始 IP;預設保留 30 天,並可設定相符時 `ALLOW`、`WARN` 或 `DENY`。SQLite 的 `anti-abuse.key` 由首次初始化建立,需隨 SQLite 備份且不得提交版本控制;MySQL 則使用所有實例共用的外部密鑰。

## Qualification Policy
Expand Down
2 changes: 1 addition & 1 deletion docs/operations/bukkit-workflow.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Bukkit 操作與維護

本文件說明 InviteCode 在 Spigot/Paper 上的玩家流程、管理指令、儲存初始化、維護模式與人工驗收方式。可選擇 `SQLITE` 或 `MYSQL`;`JSON` 尚未實作。MySQL 的設定與復原細節見 [`mysql-storage.md`](./mysql-storage.md)。
本文件說明 InviteCode 在 Spigot/Paper 上的玩家流程、管理指令、儲存初始化、維護模式與人工驗收方式。可選擇 `SQLITE`、`MYSQL` 或小型單實例環境使用的 `JSON`。JSON 與 MySQL 的設定及復原細節分別見 [`json-storage.md`](./json-storage.md) 與 [`mysql-storage.md`](./mysql-storage.md)。

## 首次啟動

Expand Down
9 changes: 9 additions & 0 deletions docs/operations/json-storage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# JSON 儲存設定與復原

JSON backend 適合小型單一伺服器、測試與資料交換。將 `plugins/InviteCode/storage.yml` 的 `backend` 設為 `JSON`,可選擇在 `json.file` 指定 `plugins/InviteCode/` 下的相對 `.json` 路徑;未設定時預設為 `invitecode.json`。第一次啟動會自動建立 JSON 檔與二進位 `anti-abuse.key`,不需管理員執行初始化指令。

JSON 檔是唯一的持久化資料來源,內含 `format-version`、`schema-version` 與按資料表分組的記錄;執行時使用暫存 SQLite 工作檔沿用現有交易、唯一性及稽核約束。每次成功寫入都會重新輸出整份 JSON,以同資料夾暫存檔原子替換正式檔,並將替換前的快照保留為 `invitecode.json.previous`(實際名稱跟隨 `json.file`)。`.lock` sidecar 以作業系統檔案鎖阻止兩個程序同時開啟;程序異常結束後檔案可能留存,鎖會由作業系統釋放,不應僅因檔案存在而刪除它。

每次寫入的成本隨整體資料量成長,不能像 MySQL 一樣讓多個插件實例共用同一份資料,也不應用於高併發或大型伺服器。JSON 格式供檢視與交換,但手動更改記錄可能破壞領域約束。切換 backend 不會自動搬移資料。JSON 格式與內部 schema 版本不相符時會拒絕開啟;目前沒有既有 JSON 檔的線上升級指令。

若 JSON 損毀或版本不支援,插件會進入維護模式,保留原檔,**不會**把它當成空白資料重新初始化。先停止伺服器並備份正式 JSON、`.previous` 及 `anti-abuse.key`。檢查錯誤訊息與版本;若上一份快照有效,可在伺服器停機時由管理員將 `.previous` 複製回正式檔,再啟動驗證。這會失去上一份快照之後的變更。不要重新產生 `anti-abuse.key`:它是 HMAC 密鑰,應與 JSON 同時備份。若寫入或原子替換失敗,當次程序會停止後續寫入;修正磁碟問題後重啟並檢查最後一份有效快照。
19 changes: 19 additions & 0 deletions docs/testing/evidence/2026-09-23-issue-7-json-smoke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Issue #7 JSON 儲存自動化 Smoke

- 日期:2026-09-23
- 受測 JAR SHA-256:`99CE69BE0A38679EDD914AC608C0B0ACC85FE5BCD6A88D80B44FCEF3238BDADA`
- 設定:`backend: JSON`,全新隔離 TestLab 實例;未安排真人玩家驗收

| Profile | 核心/Java | 首次啟動 | 停機後重啟 |
| --- | --- | --- | --- |
| `spigot-1.8.8` | Spigot 1.8.8/`local-8` | 自動建立 JSON 與 32-byte 密鑰,InviteCode `ACTIVE` | 直接讀回 JSON,Doctor 顯示 `JSON 儲存版本=1` |
| `spigot-latest` | Spigot 26.2/`local-25` | 自動建立 JSON 與 32-byte 密鑰,InviteCode `ACTIVE`;Doctor 顯示 Dialog=`SPIGOT` | 未執行,已由最低 Spigot 與最新 Paper 覆蓋重啟 |
| `paper-latest` | Paper 26.2 build 128/`local-25` | 自動建立 JSON 與 32-byte 密鑰,InviteCode `ACTIVE` | 直接讀回 JSON,Doctor 顯示 `JSON 儲存版本=1`、Dialog=`PAPER` |

最低 Spigot 與最新 Paper 的 JSON 與 `anti-abuse.key` SHA-256 在重啟前後各自保持不變;三個實例的 `logs/latest.log` 可用嚴格 UTF-8 解碼,沒有 InviteCode 維護模式、`NoSuchMethodError` 或找不到 JDBC driver。伺服器均以 `stop` 正常關閉,51888/52620/62620 port 已釋放。Java 8 JAR 檢查與相關 Gradle 測試通過。共用儲存契約由 SQLite、MySQL、JSON 三種 backend 使用;本機未提供 MySQL 測試服務,相關 integration tests 依既有設定略過。

測試過程先後查出兩個只有在實際伺服器 ClassLoader 才會出現的問題:JSON 快照直接經 `DriverManager` 無法取得封裝的 SQLite driver,以及舊版 Spigot 的 Gson 蓋過插件需要的版本。最終 JAR 已改用 SQL 模組既有的 driver 載入方式,並將插件用 Gson 搬至私有 package;上表與雜湊結果均為修正後同一份 JAR 的結果。

`spigot-latest` 的最後一輪 smoke 有一個從 `127.0.0.1` 進入的 `Command1` 玩家連線約四秒,並非本次安排的測試步驟。此連線使該實例產生玩家資料;沒有以其行為判定玩家流程通過,也不把該實例的 JSON 雜湊用於重啟一致性比較。

最新 Paper 與 Spigot 啟動時另有 OSHI 在 Windows Perflib 讀取英文 counter 名稱失敗的錯誤,堆疊位於伺服器的 OSHI/JNA,未涉及 InviteCode;伺服器與插件仍正常啟動。真人操作、其他 Minecraft 版本與高負載效能不在本次 smoke 範圍,仍待後續驗收。
2 changes: 1 addition & 1 deletion docs/testing/test-servers.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pwsh -NoProfile -File .\scripts\test-servers\start.ps1 -Profile paper-latest
## 每個 profile 的最低 smoke

1. 確認 InviteCode 啟用且沒有 linkage error、legacy material warning 或未處理 exception。
2. 確認第一次啟動自動建立 SQLite 與 anti-abuse key,重新啟動後沿用既有資料。
2. 確認所選 backend 首次啟動自動建立必要資料與 anti-abuse key(MySQL 使用外部密鑰),重新啟動後沿用既有資料。
3. 玩家與 Console 驗證 `/ic help`、`/ic reload`、Tab completion 與權限拒絕。
4. 玩家驗證 Invite Code 顯示、Claim、Confirmation、Status 與 Stats。
5. 驗證 `zh_TW`/`en_US`、UTF-8 與 client locale fallback。
Expand Down
6 changes: 6 additions & 0 deletions invitecode-core/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
description = "Platform-independent InviteCode domain model."

plugins {
`java-test-fixtures`
}

dependencies {
api(project(":invitecode-api"))
testFixturesImplementation(platform("org.junit:junit-bom:5.13.4"))
testFixturesImplementation("org.junit.jupiter:junit-jupiter")
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ data class SqliteConfiguration(val file: String) {
}
}

data class JsonConfiguration(val file: String) {
init {
require(file.isNotBlank() && file.endsWith(".json", ignoreCase = true)) {
"JSON file must be a non-blank .json path."
}
require(!file.startsWith('/') && !Regex("^[A-Za-z]:.*").matches(file)) {
"JSON file must be relative to the plugin data directory."
}
require(file.replace('\\', '/').split('/').none { it.isBlank() || it == "." || it == ".." }) {
"JSON file must not contain empty, current-directory, or parent-directory segments."
}
}
}

data class MysqlConfiguration(
val host: String,
val port: Int,
Expand Down Expand Up @@ -76,25 +90,15 @@ data class StorageConfiguration(
val backend: StorageBackendType,
val sqlite: SqliteConfiguration,
val mysql: MysqlConfiguration,
) {
fun requireSupportedBackend(): StorageConfiguration {
if (backend == StorageBackendType.JSON) {
throw UnsupportedStorageBackendException(backend)
}
return this
}
}

class UnsupportedStorageBackendException(backend: StorageBackendType) : IllegalStateException(
"Storage backend $backend is not implemented in this version; select SQLITE or install a version that supports it.",
val json: JsonConfiguration = JsonConfiguration("invitecode.json"),
)

object StorageConfigurationParser {
const val CURRENT_VERSION = 1

fun parse(value: Map<String, Any?>): StorageConfiguration {
require(value.keys == ROOT_KEYS) {
"Storage configuration must contain only ${ROOT_KEYS.sorted().joinToString()}."
require(value.keys == ROOT_KEYS || value.keys == ROOT_KEYS + "json") {
"Storage configuration must contain ${ROOT_KEYS.sorted().joinToString()} and optional json."
}
val version = value.requiredInteger("config-version", "Storage configuration")
require(version == CURRENT_VERSION) {
Expand All @@ -106,6 +110,11 @@ object StorageConfigurationParser {
require(mysql.keys == MYSQL_KEYS) {
"mysql must contain only ${MYSQL_KEYS.sorted().joinToString()}."
}
val json = if ("json" in value) {
val map = value.requiredMap("json", "Storage configuration")
require(map.keys == setOf("file")) { "json must contain only file." }
JsonConfiguration(map.requiredString("file", "json"))
} else JsonConfiguration("invitecode.json")
return StorageConfiguration(
version = version,
backend = value.requiredEnum("backend", "Storage configuration"),
Expand All @@ -123,6 +132,7 @@ object StorageConfigurationParser {
),
tlsMode = mysql.requiredEnum("tls-mode", "mysql"),
),
json = json,
)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,25 @@ class StorageConfigurationTest {
}

@Test
fun `supports MySQL and rejects unfinished JSON`() {
fun `supports MySQL and JSON with a safe default path`() {
assertEquals(
StorageBackendType.MYSQL,
StorageConfigurationParser.parse(validConfiguration().toMutableMap().apply { put("backend", "MYSQL") })
.requireSupportedBackend().backend,
.backend,
)
assertThrows<UnsupportedStorageBackendException> {
StorageConfigurationParser.parse(validConfiguration().toMutableMap().apply { put("backend", "JSON") })
.requireSupportedBackend()
val json = StorageConfigurationParser.parse(
validConfiguration().toMutableMap().apply { put("backend", "JSON") },
)
assertEquals(StorageBackendType.JSON, json.backend)
assertEquals("invitecode.json", json.json.file)
}

@Test
fun `JSON file rejects escaping paths`() {
val value = validConfiguration().toMutableMap().apply {
put("json", mapOf("file" to "../outside.json"))
}
assertThrows<IllegalArgumentException> { StorageConfigurationParser.parse(value) }
}

@Test
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package io.github.command1264.invitecode.core

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.time.Instant
import java.time.LocalDate
import java.util.UUID

abstract class StorageContractTest {
protected abstract fun withStorage(test: (InviteCodeStorage) -> Unit)

@Test
fun `player identity and unique login days survive storage operations`() = withStorage { storage ->
val id = UUID.randomUUID()
val firstSeen = Instant.parse("2026-09-22T00:00:00Z")
storage.savePlayer(StoredPlayer(id, firstSeen, "Original"))
storage.savePlayer(StoredPlayer(id, firstSeen.plusSeconds(5), "Latest"))
storage.recordLoginDay(id, LocalDate.parse("2026-09-22"))
storage.recordLoginDay(id, LocalDate.parse("2026-09-22"))
assertEquals(StoredPlayer(id, firstSeen, "Latest"), storage.player(id))
assertEquals(1, storage.loginDays(id))
}

@Test
fun `reward state and transition history are durable`() = withStorage { storage ->
val recipient = UUID.randomUUID()
val now = Instant.parse("2026-09-22T00:00:00Z")
val deliveryId = UUID.randomUUID()
val actionId = UUID.randomUUID()
storage.savePlayer(StoredPlayer(recipient, now))
val delivery = StoredRewardDelivery(
deliveryId, null, "first-milestone", RewardDeliveryStatus.PENDING,
"milestone:$recipient:1:first-milestone", now, now,
)
val action = StoredRewardAction(
actionId, deliveryId, null, recipient, 0, "MESSAGE", "hello",
RewardActionStatus.PENDING, "${delivery.idempotencyKey}:0", now, now,
)
storage.saveRewardDelivery(delivery, listOf(action))
assertEquals(delivery, storage.rewardDelivery(deliveryId))
assertEquals(listOf(action), storage.rewardActions(deliveryId))
storage.saveRewardAction(action.copy(status = RewardActionStatus.PROCESSING, updatedAt = now.plusSeconds(1)))
assertEquals(1, storage.recoverInterruptedRewardActions(now.plusSeconds(2)))
assertEquals(RewardActionStatus.UNCERTAIN, storage.rewardAction(actionId)?.status)
assertEquals(3, storage.rewardActionTransitions(actionId).size)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ object RuntimeConfigurationAssembler {
onMissingMessage: (String) -> Unit = {},
): InviteCodeRuntimeConfiguration {
val parsedGeneral = BukkitPluginConfigurationParser.parse(general)
val parsedStorage = StorageConfigurationParser.parse(storage).requireSupportedBackend()
val parsedStorage = StorageConfigurationParser.parse(storage)
val parsedQualifications = QualificationConfigurationParser.parse(qualifications)
val parsedRewards = RewardConfigurationParser.parse(rewards)
require(messageCatalogs.isNotEmpty()) { "At least one message catalog is required." }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,13 @@ class RuntimeConfigurationAssemblerTest {
}

@Test
fun `unsupported configured backend fails before snapshot installation`() {
fun `JSON backend is accepted in the configuration snapshot`() {
val json = storage().toMutableMap().apply { this["backend"] = "JSON" }

assertThrows(IllegalStateException::class.java) {
RuntimeConfigurationAssembler.parse(
general(), json, qualifications(), rewards(), mapOf("zh_TW" to catalog("訊息")),
)
}
val configured = RuntimeConfigurationAssembler.parse(
general(), json, qualifications(), rewards(), mapOf("zh_TW" to catalog("訊息")),
)
assertEquals(StorageBackendType.JSON, configured.storage.backend)
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -347,8 +347,11 @@ private class SpigotDialogBackend private constructor(
val button = load("net.md_5.bungee.api.dialog.action.ActionButton")
val dialog = load("net.md_5.bungee.api.dialog.Dialog")
val confirmation = load("net.md_5.bungee.api.dialog.ConfirmationDialog")
val jsonElement = load("com.google.gson.JsonElement")
val jsonObject = load("com.google.gson.JsonObject")
// Shadow 8.3 relocates matching string constants. Construct the server API name at
// runtime so this reflective adapter still uses the server's Gson classes.
val serverJsonPackage = listOf("com", "google", "gson").joinToString(".")
val jsonElement = load("$serverJsonPackage.JsonElement")
val jsonObject = load("$serverJsonPackage.JsonObject")
SpigotDialogBackend(
plugin = plugin,
eventClass = event,
Expand Down
4 changes: 4 additions & 0 deletions invitecode-plugin/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ val shadowJar = tasks.named<ShadowJar>("shadowJar") {
archiveClassifier.set("")
exclude("module-info.class", "META-INF/versions/**")
mergeServiceFiles()
relocate("com.google.gson", "io.github.command1264.invitecode.libs.gson")
}

tasks.withType<Test>().configureEach {
Expand Down Expand Up @@ -150,6 +151,8 @@ val verifyPluginJar by tasks.registering(VerifyPluginJar::class) {
"org/sqlite/JDBC.class",
"com/mysql/cj/jdbc/Driver.class",
"com/zaxxer/hikari/HikariDataSource.class",
"io/github/command1264/invitecode/libs/gson/Gson.class",
"io/github/command1264/invitecode/storage/json/JsonInviteCodeStorage.class",
"org/slf4j/impl/JDK14LoggerFactory.class",
"mysql/V1__initial_schema.sql",
"org/sqlite/native/Linux/x86_64/libsqlitejdbc.so",
Expand All @@ -165,6 +168,7 @@ val verifyPluginJar by tasks.registering(VerifyPluginJar::class) {
"rewards.yml",
"messages/zh_TW.yml",
"messages/en_US.yml",
"com/google/gson/Gson.class",
),
)
}
Expand Down
Loading
Loading