feat(all): complete gameplay systems and add signed updates

Complete equipment, item storage, roster, battle recovery, PvP, recommendations, statues and fishing flows.

Add localized launcher and console interfaces, signed releases and announcements, verified resource updates and required-update prompts.

Publish gameplay notes for client and server 0.2.0.
This commit is contained in:
Flechazo committed 2026-10-15 23:12:59 +08:00
1 parent c5584cc19b
commit e96232b779
205 files changed
+22206 -1247

No files matched your search

+3
View File
@@ -5,6 +5,9 @@
*.cabal text eol=lf
*.proto text eol=lf
*.py text eol=lf
*.sh text eol=lf
*.service text eol=lf
*.path text eol=lf
*.yaml text eol=lf
*.yml text eol=lf
*.json text eol=lf
+5 -1
View File
@@ -37,7 +37,7 @@ OAuth 联机服使用与游戏相同的 Discord 或 Google 登录。在管理台
## 服务器配置
“服务器配置”页直接编辑服务端正在使用的 `game.json`、`authentication.json` 和 `resources.json`,字段含义与 [游戏规则配置](GAME_CONFIGURATION.md)、[认证配置](AUTHENTICATION.md)、[资源配置](RESOURCES.md) 一致。
“服务器配置”页直接编辑服务端正在使用的 `game.json`、`authentication.json`、`resources.json` 和 `updates.json`,字段含义与 [游戏规则配置](GAME_CONFIGURATION.md)、[认证配置](AUTHENTICATION.md)、[资源配置](RESOURCES.md) 一致;`updates.json` 的各项含义在页面中有说明。
- 编辑时实时校验,使用的规则与服务端启动时完全相同;有错误的配置无法保存。
- 保存是整文件原子替换。如果文件在你编辑期间被其他人或其他程序修改,保存会被拒绝,可以选择载入最新版本。
@@ -46,3 +46,7 @@ OAuth 联机服使用与游戏相同的 Discord 或 Google 登录。在管理台
- 引用的环境变量(OAuth 密钥、审核接口密钥)在当前服务端进程中未设置,或者引用的文件(词库、TLS 证书)读取不到时,页面会给出提醒。密钥本身只能通过环境变量提供,不会写入配置文件,也不会在页面中显示。
- 服务端对配置文件没有写权限时(例如部署方以只读方式挂载),页面只能查看,不能修改。需要锁定某份配置时,以只读方式提供即可。
- 如果文件在管理台之外被改成了服务端无法加载的内容,页面会指出问题。修正后保存,就能避免下次重启失败。
## 版本更新
仅服主可见。“版本更新”页显示当前版本、可用版本、更新说明、迁移标记和预下载状态,可立即检查新版、设定倒计时应用更新或取消尚未开始排空的维护。没有浏览器时可用 `bd2server update status|check|apply|cancel --data-dir <数据目录>` 完成同样的操作。
+85
View File
@@ -0,0 +1,85 @@
# 更新日志
## server 2.36.7+server.0.2.0 · 2026-10-15
> type: update
> migration: none
### zh_cn: 玩法补全
- 装备支持制作后强化、制作后分解和强化后分解,补全装备仓库存取与升阶购买。
- 补全道具锁定、解锁、丢弃及仓库存取,保留数量和属性并检查使用限制。
- 补全角色升阶、临时伙伴到期清理、服装强化、万能强化及已解锁技能潜能的锁定与解锁。
- 伙伴关系随共同参战结果结算,支持羁绊阶段奖励及满关系伙伴剧情奖励,进度持久保存。
- 补全未完成战斗恢复、上一蓝方回合回退和放弃战斗;魔兽追踪、公会突袭支持作战记录与最高伤害统计。
- 镜中之战支持实际回合重放、进攻和防守阵容战绩分别重置;补全胜利阵容推荐、战力排序、已拥有角色筛选及分享设置。
- 补全广场每日奖励、个人及全服雕像击打统计、已结算赛季排名雕像展示和每日奖励。
- 捕鱼笼支持离线累计、奖励预览、领取鱼类或自动出售及钓鱼经验结算,修正出售价格取整。
### en_us: Gameplay additions
- Added craft-to-upgrade, craft-to-dismantle and upgrade-to-dismantle equipment actions, equipment storage and eligible rank-up purchases.
- Added item locking, unlocking, discarding and storage transfers, preserving quantities and properties and enforcing item restrictions.
- Added character promotion, expired temporary companion cleanup, costume and universal upgrades, and locking or unlocking acquired skill potentials.
- Partner relationships now settle with shared battle results. Solidarity milestone and maximum-relationship partner story rewards retain their progress.
- Added unfinished battle recovery, rollback to the previous allied turn and abandonment. Fiend Hunt and Guild Raid now support action records and best-damage statistics.
- Mirror Wars replays now use actual battle turns, with separate attack and defense record resets. Added winning-team recommendations, power sorting, an owned-character filter and sharing preferences.
- Added daily square rewards, personal and server-wide statue hit counts, settled-season ranking statue displays and daily rewards.
- Fishing traps now accumulate catches offline, preview rewards, deliver fish or sell them automatically, and award fishing experience. Corrected sale-price rounding.
### zh_tw: 玩法補全
- 裝備支援製作後強化、製作後分解和強化後分解,補全裝備倉庫存取與升階購買。
- 補全道具鎖定、解鎖、丟棄及倉庫存取,保留數量和屬性並檢查使用限制。
- 補全角色升階、臨時夥伴到期清理、服裝強化、萬能強化及已解鎖技能潛能的鎖定與解鎖。
- 夥伴關係隨共同參戰結果結算,支援羈絆階段獎勵及滿關係夥伴劇情獎勵,進度持久保存。
- 補全未完成戰鬥恢復、上一藍方回合回退和放棄戰鬥;魔獸追蹤、公會突襲支援作戰記錄與最高傷害統計。
- 鏡中之戰支援實際回合重播、進攻和防守陣容戰績分別重置;補全勝利陣容推薦、戰力排序、已擁有角色篩選及分享設定。
- 補全廣場每日獎勵、個人及全服雕像擊打統計、已結算賽季排名雕像展示和每日獎勵。
- 捕魚籠支援離線累積、獎勵預覽、領取魚類或自動出售及釣魚經驗結算,修正出售價格取整。
### ja_jp: ゲームプレイ機能の追加
- 装備の製作後強化、製作後分解、強化後分解に対応し、装備倉庫への出し入れと対象装備のランクアップ購入を追加しました。
- アイテムのロック、解除、廃棄、倉庫への移動を追加しました。数量と属性を保持し、使用制限を確認します。
- キャラクターの昇級、期限切れの一時的な仲間の整理、コスチューム強化、万能強化、解放済みスキル潜在能力のロックと解除を追加しました。
- 共に参加した戦闘結果に応じてパートナー関係を更新し、絆段階報酬と最大関係のパートナーストーリー報酬の進捗を保存します。
- 未完了の戦闘の復元、前の味方ターンへの巻き戻し、戦闘の放棄を追加しました。魔獣追跡とギルドレイドでは行動記録と最高ダメージを保存します。
- 鏡戦争のリプレイを実際のターンに対応させ、攻撃・防御編成の戦績を個別にリセットできます。勝利編成のおすすめ、戦闘力順、所持キャラクターのみの絞り込み、共有設定を追加しました。
- 広場のデイリー報酬、個人・サーバー全体の彫像攻撃回数、確定済みシーズンのランキング彫像とデイリー報酬を追加しました。
- 漁獲かごのオフライン蓄積、報酬確認、魚の受け取り・自動売却、釣り経験値の精算に対応し、売却価格の丸めを修正しました。
### ko_kr: 게임 플레이 기능 추가
- 장비 제작 후 강화, 제작 후 분해, 강화 후 분해를 지원하고 장비 창고 입출고와 대상 장비의 등급 상승 구매를 추가했습니다.
- 아이템 잠금, 잠금 해제, 버리기와 창고 이동을 추가했습니다. 수량과 속성을 유지하고 사용 제한을 확인합니다.
- 캐릭터 승급, 만료된 임시 동료 정리, 코스튬 강화와 만능 강화, 해금한 스킬 잠재력의 잠금 및 해제를 추가했습니다.
- 함께 참여한 전투 결과에 따라 파트너 관계를 정산하고, 유대 단계 보상과 최대 관계 파트너 스토리 보상 진행도를 저장합니다.
- 미완료 전투 복구, 이전 아군 턴으로 되돌리기와 전투 포기를 추가했습니다. 마물 추적과 길드 레이드는 행동 기록과 최고 피해량을 저장합니다.
- 거울전쟁 다시보기가 실제 전투 턴을 사용하며 공격·방어 편성 전적을 각각 초기화할 수 있습니다. 승리 편성 추천, 전투력 정렬, 보유 캐릭터 필터와 공유 설정을 추가했습니다.
- 광장 일일 보상, 개인 및 서버 전체 조각상 타격 횟수, 정산된 시즌의 순위 조각상 표시와 일일 보상을 추가했습니다.
- 통발의 오프라인 어획 누적, 보상 미리보기, 물고기 수령 또는 자동 판매와 낚시 경험치 정산을 추가하고 판매 가격 반올림을 수정했습니다.
## client 2.36.7+client.0.2.0 · 2026-10-15
> type: update
### en_us: Battle recovery
- Added battle checkpoints to support unfinished battle recovery and turn rollback.
### zh_cn: 战斗恢复
- 补全战斗检查点上报,支持未完成战斗恢复与回合回退。
### zh_tw: 戰鬥恢復
- 補全戰鬥檢查點回報,支援未完成戰鬥恢復與回合回退。
### ja_jp: 戦闘の復元
- 戦闘チェックポイントの送信を追加し、未完了の戦闘の復元とターンの巻き戻しに対応しました。
### ko_kr: 전투 복구
- 전투 체크포인트 전송을 추가하여 미완료 전투 복구와 턴 되돌리기를 지원합니다.
+4
View File
@@ -0,0 +1,4 @@
{
"key_id": "6ba6c06138973875",
"signature": "CvlPMkd8base336vDpyaNCv8ZuQX7Y69kNBrwHRBDv3PfLmNKQCYdinxH0GA77BKGqSoOwuzx37PIpT85e1uBw=="
}
+2 -1
View File
@@ -16,8 +16,9 @@ RUN apt-get update \
&& useradd --uid 10001 --gid 10001 --no-create-home --shell /usr/sbin/nologin bd2
WORKDIR /app
ENV BD2_UPDATE_METHOD=docker
COPY --from=build /out/bd2server /app/bd2server
COPY versions.json /app/
COPY versions.json CHANGELOG.md* UPDATE_FINGERPRINT.json* /app/
COPY go/seed /app/go/seed
COPY schedules /app/schedules
RUN mkdir -p /app/data && chown 10001:10001 /app/data
+2
View File
@@ -2,5 +2,7 @@
!go/
!go/**
!versions.json
!CHANGELOG.md*
!UPDATE_FINGERPRINT.json
!schedules/
!schedules/**
+2
View File
@@ -80,6 +80,8 @@ BD2 Launcher 是使用 Wails 的独立桌面游戏启动器。Windows 使用系
服务端自带网页管理台,地址为 `<服务器地址>/admin/`,可以可视化修改上述配置、给玩家寄送物品和调整背包容量,详细见 [网页管理台](ADMIN_CONSOLE.md)。
启动器和服务端会自动检查新版本;服务端更新可在网页管理台“版本更新”页或用 `bd2server update status|check|apply|cancel` 应用,应用前会通知在线玩家并保存存档。游戏内“新闻”公告来自签名的 [更新日志](CHANGELOG.md),按玩家的游戏语言显示。
服务端日志默认输出 INFO 及以上级别,仅终端启用颜色:TRACE 灰、DEBUG 青、INFO 绿、WARN 黄、ERROR 红。可用 `serve --log-level debug --log-color auto` 调整,或设置 `BD2_LOG_LEVEL` 和 `BD2_LOG_COLOR` 环境变量,显式命令行参数优先。级别支持 `trace/debug/info/warn/error`,颜色支持 `auto/always/never`。`auto` 下文件和重定向保持纯文本,`NO_COLOR` 或 `TERM=dumb` 也会关闭颜色;如需在 Docker 日志流中显示颜色,可显式选择 `always`。
### 启动客户端
+1
View File
@@ -0,0 +1 @@
{"fingerprint":{"client_version":"2.36.7+client.0.2.0","game":{"build_origins":["https://cdn.dev.bd2.pmang.cloud","https://dl.dev.bd2.pmang.cloud"],"bundle_version":"20261007175947","catalog_bytes":67338179,"catalog_hash":"0f90a94601be05737f86a4ec7a1c889f","catalog_sha256":"c9ed216c66903bfa1e556f38cc02e2923a48164e8469767d7987f7989d86d385","data_bytes":191754787,"data_sha256":"44cc20963abf800f4b3af449ff901534a1b99089571a820eb7bbb841fd0f0cd1","game_bytes":413552979,"game_data_version":"20261008155037","game_path":"/Build/Windows/20261002/StandaloneWindows64.2.36.7.zip","game_sha256":"3ca28b7c94d65b2cb4e33784d843902758415a3a83870c5f6198f5cd90e3bff3","game_version":"2.36.7","platform":"StandaloneWindows64","resource_files":[{"path":"GameData/20261008155037/design.version","sha256":"df58255444317d71fe52a2029ad61dc7984a08648e182d5e160c1f5ed2ad8f8b","size":67},{"path":"GameData/20261008155037/release/common-dbdata.bin","sha256":"44cc20963abf800f4b3af449ff901534a1b99089571a820eb7bbb841fd0f0cd1","size":191754787},{"path":"GameData/20261008155037/release/common-dbdata.info","sha256":"d1f63cedd4aa4c30c6ba58bca2d833d50b669abdeb60b338f7fc974ac4c1a3bd","size":10},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/catalog_alpha.hash","sha256":"6fe5835dcb927cfe1cb2a2fc4ba3b440873d06104f8d5cc92dc2993e5cb345c6","size":33},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/catalog_alpha.json","sha256":"c9ed216c66903bfa1e556f38cc02e2923a48164e8469767d7987f7989d86d385","size":67338179},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatar-char-group0_assets_charavatar.bundle","sha256":"c723a309b7b61bc2189f539f6911c852b21783b5fcb0a7a167e2f1d073fc2b5f","size":101738625},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatar-char-group0_scenes_charavatar.bundle","sha256":"56676c7f48d3d7c90f8956b02bc3f15f3074af7e8ff0ef64e1f9b8289eb08d52","size":31379},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarfishingicon_1_assets_all.bundle","sha256":"3407127468d588ff84e5158d31f2b791fb144582fc914340d307e7b79b96be22","size":44897},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarfishingicon_l_1_assets_all.bundle","sha256":"78ebf960a6b4f3b83fe28de1597e36f9ba7db1142bc1c0acdc9c65cd974cbbb4","size":2932480},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avataricon_1_assets_all.bundle","sha256":"b11d1072756c56a879f8b18ffc0dcb2ab16405d94418fcd9bc1e3ffb4404e321","size":2839270},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifehousing_1_assets_all.bundle","sha256":"1c844bc153dabe18b153157e466d7f7f0fa12e40c3b3ef6fc00af31abcf354e0","size":42443},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifehousing_l_1_assets_all.bundle","sha256":"c12e4bae20aedf8889d7f916cca0b3d55167a4b787bd649e07f10d21db0c49bc","size":2334709},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifeicon_1_assets_all.bundle","sha256":"bf6b432dc821a6e864993f649fedc1d03244d1ee2c93310bd0ce55d99ab8b743","size":16286},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-avatarlifeicon_l_1_assets_all.bundle","sha256":"528dec1ed0c867bb6dcd59b985dc3911280f5f560c0d4b000a1e979f46f6e335","size":824161},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bgmalbum_1_assets_all.bundle","sha256":"16d606338d9b9e53a8d99d063613a8830dc943cb4225047f23b060f11614a7fc","size":614361},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-animation_assets_all.bundle","sha256":"8fb500400acf16f22516a298afbef6435c42c30969c762d7eee92c1d936cf06c","size":26191},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-animator_assets_all.bundle","sha256":"098045676a9b7d2c58703745bd608b2f9856027dd461012d3bde66d2f8266a16","size":6987},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-mesh_assets_all.bundle","sha256":"32a77141ffce92a510deb79f6af3309624b274c6e66493832946169a20612075","size":1617979},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-meterial_assets_all.bundle","sha256":"5d252406b5f875ca3add9da3bbbde4f7161f0fdd61f9592b3df780ce8c0ed1e1","size":384695},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group10_assets_all_49ba98afca0c02be2fc3424f638f5847.bundle","sha256":"71724987a41def2769d3bbdf79f1fb02933a0eb557d7f34a87c1e612e355c605","size":524718},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group11_assets_all_43fe4fab9a2c7d550e8bd6cc4f3b05e4.bundle","sha256":"31689c4ca268c96fd04e35d45f0bde1261b2810f32e339761889d1bebaaecfb6","size":665927},{"path":"ServerData/StandaloneWindows64/HD/20261007175947/common-bundlecommon-effect-prefab-group12_assets_all_622cf72083a2211233519e4d3074b754.bundle","sha256":"e86c377fd87f65a6092545e559a6bdd483e932741c03fe42538e9b9bc7b5dcc0","size":526015},{"path"Line truncated
+5 -2
View File
@@ -27,6 +27,7 @@ func main() {
func usage() {
fmt.Println(`Usage:
bd2w build [-GameDir directory] [-SkipTests] [-SchedulesOnly]
bd2w release changelog --component server|client [--bump patch] | publish [--no-announcement]
bd2w runClient [client options]
bd2w runClient2 [--instance player2] [--game-dir directory]
bd2w plugins [--game-dir directory]
@@ -72,10 +73,10 @@ func run(args []string) error {
case "diff":
return t.execute("diff", taskgraph.Task{Name: "diff", Run: func(context.Context) error { return sourcetools.RunDiff(args[1:], os.Stdout) }})
}
if args[0] != "build" && args[0] != "runClient" && args[0] != "runClient2" && args[0] != "runServer" && args[0] != "sdk" && args[0] != "version-source" && args[0] != "plugins" && args[0] != "check-csharp" && args[0] != "download-client" && args[0] != "download-resources" {
if args[0] != "build" && args[0] != "runClient" && args[0] != "runClient2" && args[0] != "runServer" && args[0] != "sdk" && args[0] != "version-source" && args[0] != "plugins" && args[0] != "check-csharp" && args[0] != "download-client" && args[0] != "download-resources" && args[0] != "release" {
return fmt.Errorf("unknown task %q; use --help for available commands", args[0])
}
if len(args) == 2 && isHelp(args[1]) {
if len(args) == 2 && isHelp(args[1]) && args[0] != "release" {
usage()
return nil
}
@@ -111,6 +112,8 @@ func run(args []string) error {
return t.execute("version-source", taskgraph.Task{Name: "version-source", Run: func(context.Context) error { return t.generateVersionSource(args[1:]) }})
case "check-csharp":
return t.checkCSharp(args[1:])
case "release":
return t.release(args[1:])
case "download-client", "download-resources":
return t.runDownload(args[0], args[1:])
case "sdk":
+66 -1
View File
@@ -3,13 +3,18 @@ package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
clientplugin "bd2server/internal/client/plugin"
clientupdate "bd2server/internal/client/update"
releasepkg "bd2server/internal/common/release"
"bd2server/internal/common/taskgraph"
"bd2server/internal/common/versionconfig"
)
type release struct {
@@ -171,21 +176,81 @@ func (r *release) stageAssets() error {
return err
}
}
for _, name := range []string{"versions.json", "README.md", "LICENSE"} {
if err := r.writePluginStore(); err != nil {
return err
}
for _, name := range []string{"versions.json", "README.md", "LICENSE", "CHANGELOG.md", releasepkg.ChangelogSignatureName} {
// Unsigned development changelogs ship without a signature and show no notices.
if name == releasepkg.ChangelogSignatureName && !regular(filepath.Join(root, name)) {
continue
}
for _, out := range []string{r.server, r.client} {
if err := copyFile(filepath.Join(root, name), filepath.Join(out, name)); err != nil {
return err
}
}
}
if regular(filepath.Join(root, releasepkg.FingerprintFileName)) {
f, err := releasepkg.LoadFingerprint(filepath.Join(root, releasepkg.FingerprintFileName), releasepkg.BuiltinChannel().TrustedKeys)
if err != nil {
return err
}
v, err := versionconfig.Load(filepath.Join(root, "versions.json"))
if err != nil {
return err
}
if err := f.MatchesVersions(v); err != nil {
return err
}
for _, out := range []string{r.server, r.client} {
if err := copyFile(filepath.Join(root, releasepkg.FingerprintFileName), filepath.Join(out, releasepkg.FingerprintFileName)); err != nil {
return err
}
}
}
for _, name := range []string{"AUTHENTICATION.md", "RESOURCES.md", "GAME_CONFIGURATION.md"} {
if err := copyFile(filepath.Join(root, name), filepath.Join(r.server, name)); err != nil {
return err
}
}
for _, name := range []string{"bd2server.service", "bd2-docker-update.sh", "bd2-docker-update.service", "bd2-docker-update.path"} {
source := filepath.Join(root, "tools", "server", name)
if err := copyFile(source, filepath.Join(r.server, name)); err != nil {
return fmt.Errorf("stage server installation file %s: %w", name, err)
}
if strings.HasSuffix(name, ".sh") {
if err := os.Chmod(filepath.Join(r.server, name), 0o755); err != nil {
return err
}
}
}
return nil
}
// writePluginStore describes the packaged plugin set so the launcher's
// updater knows which versions it holds.
func (r *release) writePluginStore() error {
versions, err := versionconfig.Load(filepath.Join(r.task.root, "versions.json"))
if err != nil {
return err
}
byID := versions.Plugins.ByID()
store := clientupdate.Store{Version: versions.ClientVersion}
for _, spec := range clientplugin.Shipped {
sum, err := releasepkg.HashFile(filepath.Join(r.client, "plugins", spec.FileName()))
if err != nil {
return err
}
id := pluginIDs[spec.FileName()]
store.Files = append(store.Files, clientupdate.StoredFile{ID: id, Name: spec.FileName(), Version: byID[id], SHA256: sum})
}
raw, err := json.MarshalIndent(store, "", " ")
if err != nil {
return err
}
return os.WriteFile(filepath.Join(r.client, "plugins", clientupdate.StoreFile), append(raw, '\n'), 0o644)
}
func (r *release) archive() error {
if err := archiveDirectory(r.server, r.serverZip); err != nil {
return err
+436
View File
@@ -0,0 +1,436 @@
package main
import (
"archive/zip"
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strings"
"time"
clientplugin "bd2server/internal/client/plugin"
"bd2server/internal/common/i18n"
releasepkg "bd2server/internal/common/release"
"bd2server/internal/common/versionconfig"
)
// serverPlatforms are the packages published for self-updating servers.
var serverPlatforms = [][2]string{{"linux", "amd64"}, {"linux", "arm64"}}
// pluginIDs maps shipped plugin files to their versions.json keys.
var pluginIDs = map[string]string{
"BD2LocalIdentity.dll": "local_identity", "BD2LoginUI.dll": "login_ui", "BD2CashShop.dll": "cash_shop", "BD2FChat.dll": "fchat", "BD2.GameNames.dll": "game_names",
}
func (t task) release(args []string) error {
if len(args) == 0 || isHelp(args[0]) {
fmt.Println(`Usage:
bd2w release changelog --component server|client [--bump patch|minor|major|none]
bd2w release publish [-GameDir dir] [-SkipTests] [--output dir] [--image ref] [--allow-dirty] [--no-announcement]
publish builds unsigned release materials described by versions.json and
CHANGELOG.md. Signing and uploading are independent publisher operations.`)
return nil
}
switch args[0] {
case "changelog":
return t.releaseChangelog(args[1:])
case "publish":
return t.releasePublish(args[1:])
}
return fmt.Errorf("unknown release task %q", args[0])
}
var componentVersionLine = regexp.MustCompile(`("(server|client)_version"\s*:\s*")([0-9]+\.[0-9]+\.[0-9]+)\+(server|client)\.([0-9]+)\.([0-9]+)\.([0-9]+)(")`)
func (t task) releaseChangelog(args []string) error {
fs := flag.NewFlagSet("release changelog", flag.ContinueOnError)
component := fs.String("component", "", "server or client")
bump := fs.String("bump", "patch", "patch, minor, major or none")
if err := fs.Parse(args); err != nil {
return err
}
if *component != releasepkg.ComponentServer && *component != releasepkg.ComponentClient {
return errors.New("--component must be server or client")
}
versionsPath := filepath.Join(t.root, "versions.json")
raw, err := os.ReadFile(versionsPath)
if err != nil {
return err
}
var version string
updated := componentVersionLine.ReplaceAllStringFunc(string(raw), func(line string) string {
m := componentVersionLine.FindStringSubmatch(line)
if m[2] != *component {
return line
}
var major, minor, patch int
_, _ = fmt.Sscan(m[5], &major)
_, _ = fmt.Sscan(m[6], &minor)
_, _ = fmt.Sscan(m[7], &patch)
switch *bump {
case "major":
major, minor, patch = major+1, 0, 0
case "minor":
minor, patch = minor+1, 0
case "patch":
patch++
case "none":
default:
version = "!"
return line
}
version = fmt.Sprintf("%s+%s.%d.%d.%d", m[3], m[4], major, minor, patch)
return m[1] + version + m[8]
})
if version == "!" || version == "" {
return fmt.Errorf("cannot bump %s_version with --bump %s", *component, *bump)
}
changelogPath := filepath.Join(t.root, "CHANGELOG.md")
changelog, err := os.ReadFile(changelogPath)
if err != nil {
return err
}
entries, err := releasepkg.ParseChangelog(changelog)
if err != nil {
return fmt.Errorf("CHANGELOG.md: %w", err)
}
if _, exists := releasepkg.Find(entries, *component, version); exists {
return fmt.Errorf("CHANGELOG.md already has %s %s", *component, version)
}
text := string(changelog)
at := len(text)
fence := ""
offset := 0
for line := range strings.SplitAfterSeq(text, "\n") {
trimmed := strings.TrimSpace(line)
if fence != "" {
if strings.HasPrefix(trimmed, fence) {
fence = ""
}
} else if strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~") {
fence = trimmed[:3]
} else if strings.HasPrefix(line, "## server ") || strings.HasPrefix(line, "## client ") {
at = offset
break
}
offset += len(line)
}
section := releasepkg.ChangelogTemplate(*component, version, time.Now())
text = text[:at] + section + "\n" + text[at:]
if err := os.WriteFile(versionsPath, []byte(updated), 0o644); err != nil {
return err
}
if err := os.WriteFile(changelogPath, []byte(text), 0o644); err != nil {
return err
}
fmt.Printf("%s_version is now %s; fill in its CHANGELOG.md section, then commit, push and prepare the release materials.\n", *component, version)
return nil
}
type publishOptions struct {
build buildOptions
output string
image string
allowDirty bool
silent bool
}
func parsePublish(args []string) (publishOptions, error) {
var opts publishOptions
var rest []string
for i := 0; i < len(args); i++ {
name, value, assigned := strings.Cut(args[i], "=")
take := func() (string, error) {
if assigned {
return value, nil
}
i++
if i >= len(args) {
return "", fmt.Errorf("%s requires a value", name)
}
return args[i], nil
}
var err error
switch name {
case "--output":
opts.output, err = take()
case "--image":
opts.image, err = take()
case "--no-announcement":
opts.silent = true
case "--allow-dirty":
opts.allowDirty = true
default:
rest = append(rest, args[i])
}
if err != nil {
return opts, err
}
}
build, err := parseOptions(rest)
opts.build = build
return opts, err
}
func (t task) git(args ...string) (string, error) {
command := exec.CommandContext(t.ctx, "git", args...)
command.Dir = t.root
var stderr bytes.Buffer
command.Stderr = &stderr
out, err := command.Output()
if err != nil {
return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))
}
return strings.TrimSpace(string(out)), nil
}
// releaseCommit returns HEAD after checking that it is committed and pushed
// to both remotes, so every published release names a reachable commit.
func (t task) releaseCommit(allowDirty bool) (string, error) {
commit, err := t.git("rev-parse", "HEAD")
if err != nil {
return "", err
}
if allowDirty {
return commit, nil
}
if status, err := t.git("status", "--porcelain", "--untracked-files=normal"); err != nil {
return "", err
} else if status != "" {
return "", errors.New("the working tree has uncommitted changes; commit and push before publishing")
}
for _, remote := range []string{"origin", "sighs"} {
if _, err := t.git("fetch", "--quiet", remote, "main"); err != nil {
return "", err
}
if _, err := t.git("merge-base", "--is-ancestor", "HEAD", remote+"/main"); err != nil {
return "", fmt.Errorf("HEAD %s is not pushed to %s/main; push to both remotes first", commit[:12], remote)
}
}
return commit, nil
}
func (t task) releasePublish(args []string) error {
opts, err := parsePublish(args)
if err != nil {
return err
}
commit, err := t.releaseCommit(opts.allowDirty)
if err != nil {
return err
}
versions, err := versionconfig.Load(filepath.Join(t.root, "versions.json"))
if err != nil {
return err
}
fingerprint, err := releasepkg.LoadFingerprint(filepath.Join(t.root, releasepkg.FingerprintFileName), releasepkg.BuiltinChannel().TrustedKeys)
if err != nil {
return fmt.Errorf("release fingerprint must be generated independently before publication: %w", err)
}
if err := fingerprint.MatchesVersions(versions); err != nil {
return err
}
changelog, err := os.ReadFile(filepath.Join(t.root, "CHANGELOG.md"))
if err != nil {
return err
}
entries, err := releasepkg.ParseChangelog(changelog)
if err != nil {
return fmt.Errorf("CHANGELOG.md: %w", err)
}
serverEntry, ok := releasepkg.Find(entries, releasepkg.ComponentServer, versions.ServerVersion)
if !ok && !opts.silent {
return fmt.Errorf("CHANGELOG.md has no section for server %s; run bd2w release changelog --component server", versions.ServerVersion)
}
clientEntry, ok := releasepkg.Find(entries, releasepkg.ComponentClient, versions.ClientVersion)
if !ok && !opts.silent {
return fmt.Errorf("CHANGELOG.md has no section for client %s; run bd2w release changelog --component client", versions.ClientVersion)
}
if opts.silent {
serverEntry = releasepkg.Entry{Migration: releasepkg.MigrationNone}
clientEntry = releasepkg.Entry{}
}
if err := t.build(opts.build); err != nil {
return err
}
site := opts.output
if site == "" {
site = filepath.Join(t.root, ".build", "release-site")
}
if err := removeBuildOutput(filepath.Join(t.root, ".build"), site); err != nil {
return err
}
publish := func(source, name, platform, id, version string) (releasepkg.File, error) {
sum, err := releasepkg.HashFile(source)
if err != nil {
return releasepkg.File{}, err
}
info, err := os.Stat(source)
if err != nil {
return releasepkg.File{}, err
}
relative := path.Join("files", sum[:16], name)
if err := copyFile(source, filepath.Join(site, filepath.FromSlash(relative))); err != nil {
return releasepkg.File{}, err
}
return releasepkg.File{Name: name, ID: id, Platform: platform, Version: version, Size: info.Size(), SHA256: sum, URL: "../" + relative}, nil
}
packageRoot := filepath.Join(t.root, ".build", "package")
native := t.target.goos + "-" + t.target.goarch
date := func(e releasepkg.Entry) string {
if e.Date.IsZero() {
return ""
}
return e.Date.Format("2006-01-02")
}
server := &releasepkg.Component{Version: versions.ServerVersion, Date: date(serverEntry), Notes: serverEntry.Notes(), Image: opts.image,
Migration: &releasepkg.Migration{Kind: serverEntry.Migration, Backup: serverEntry.Backup}, MinimumPlugins: versions.MinimumPlugins.ByID()}
delete(server.MinimumPlugins, "capture_environment")
if serverEntry.Migration != releasepkg.MigrationNone {
server.Migration.Note = i18n.Text{}
for locale, notes := range serverEntry.Notes() {
server.Migration.Note[locale] = firstLine(notes)
}
}
for _, platform := range serverPlatforms {
archive, err := t.serverPackage(versions, platform[0], platform[1], filepath.Join(packageRoot, "bd2server"))
if err != nil {
return err
}
f, err := publish(archive, filepath.Base(archive), platform[0]+"-"+platform[1], "", "")
if err != nil {
return err
}
server.Files = append(server.Files, f)
}
launcher := &releasepkg.Component{Version: versions.ClientVersion, Date: date(clientEntry), Notes: clientEntry.Notes()}
clientPackage := filepath.Join(packageRoot, "bd2client")
executable := "bd2client"
if t.target.goos == "windows" {
executable += ".exe"
}
for _, name := range []string{executable, "versions.json", "client-download.json", releasepkg.FingerprintFileName} {
platform := ""
if name == executable {
platform = native
}
f, err := publish(filepath.Join(clientPackage, name), name, platform, "", "")
if err != nil {
return err
}
launcher.Files = append(launcher.Files, f)
}
plugins := &releasepkg.Component{Version: versions.ClientVersion, Date: date(clientEntry), Notes: clientEntry.Notes()}
pluginVersions := versions.Plugins.ByID()
for _, spec := range clientplugin.Shipped {
id := pluginIDs[spec.FileName()]
f, err := publish(filepath.Join(clientPackage, "plugins", spec.FileName()), spec.FileName(), "", id, pluginVersions[id])
if err != nil {
return err
}
plugins.Files = append(plugins.Files, f)
}
manifest := releasepkg.Manifest{Schema: releasepkg.SchemaVersion, Channel: releasepkg.BuiltinChannel().Name, PublishedAt: time.Now().UTC().Truncate(time.Second), Commit: commit,
Launcher: launcher, Plugins: plugins, Server: server, Fingerprint: fingerprint}
if err := manifest.Validate(); err != nil {
return err
}
raw, err := json.MarshalIndent(manifest, "", " ")
if err != nil {
return err
}
if err := os.WriteFile(filepath.Join(site, "manifest.json"), append(raw, '\n'), 0o644); err != nil {
return err
}
if err := copyFile(filepath.Join(t.root, "CHANGELOG.md"), filepath.Join(site, "CHANGELOG.md")); err != nil {
return err
}
fmt.Println("Unsigned release materials:", site)
fmt.Println("Signing and publication must be performed independently by the publisher.")
return nil
}
func firstLine(text string) string {
line, _, _ := strings.Cut(strings.TrimSpace(text), "\n")
return line
}
// serverPackage cross-compiles the server for goos/goarch and zips it with
// the native package's data files. The executable keeps its 0755 mode.
func (t task) serverPackage(versions versionconfig.Config, goos, goarch, nativePackage string) (string, error) {
work := filepath.Join(t.root, ".build", "release-server", goos+"-"+goarch)
if err := removeBuildOutput(filepath.Join(t.root, ".build"), work); err != nil {
return "", err
}
binary := filepath.Join(work, "bd2server")
if goos == "windows" {
binary += ".exe"
}
cross := t
var err error
if cross.target, err = platformTarget(goos, goarch); err != nil {
return "", err
}
if err := cross.command("go", "build", "-tags", "release", "-trimpath", "-ldflags", "-s -w", "-o", binary, "./cmd/bd2server"); err != nil {
return "", err
}
archive := filepath.Join(t.root, ".build", fmt.Sprintf("bd2server-%s-%s-%s.zip", versions.ServerVersion, goos, goarch))
out, err := os.Create(archive)
if err != nil {
return "", err
}
writer := zip.NewWriter(out)
add := func(source, name string, mode os.FileMode) error {
in, err := os.Open(source)
if err != nil {
return err
}
defer func() { _ = in.Close() }()
header := &zip.FileHeader{Name: "bd2server/" + name, Method: zip.Deflate}
header.SetMode(mode)
w, err := writer.CreateHeader(header)
if err != nil {
return err
}
_, err = io.Copy(w, in)
return err
}
err = add(binary, filepath.Base(binary), 0o755)
if err == nil {
err = filepath.WalkDir(nativePackage, func(file string, entry os.DirEntry, walkErr error) error {
if walkErr != nil || entry.IsDir() {
return walkErr
}
name, err := filepath.Rel(nativePackage, file)
if err != nil {
return err
}
name = filepath.ToSlash(name)
if strings.HasPrefix(name, "data/") || strings.TrimSuffix(name, ".exe") == "bd2server" {
return nil
}
mode := os.FileMode(0o644)
if strings.HasSuffix(name, ".sh") {
mode = 0o755
}
return add(file, name, mode)
})
}
if err = errors.Join(err, writer.Close(), out.Close()); err != nil {
return "", err
}
return archive, os.RemoveAll(work)
}
+8
View File
@@ -10,6 +10,7 @@ import (
clientapp "bd2server/internal/client/app"
clientconfig "bd2server/internal/client/config"
"bd2server/internal/client/download"
clientupdate "bd2server/internal/client/update"
"bd2server/internal/common/versionconfig"
)
@@ -23,6 +24,13 @@ type clientRunOptions struct {
}
func main() {
if len(os.Args) > 1 && os.Args[1] == clientupdate.HelperFlag {
if err := clientupdate.RunHelper(os.Args[2:]); err != nil {
clientapp.ShowFatalError(err)
os.Exit(1)
}
return
}
if len(os.Args) > 1 && os.Args[1] == "download-resources" {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
+18
View File
@@ -2,9 +2,12 @@ package main
import (
"bd2server/internal/server/app"
"bd2server/internal/server/platform/updates"
"errors"
"fmt"
"log/slog"
"os"
"time"
)
func main() {
@@ -33,14 +36,28 @@ func main() {
err = app.Resources(os.Args[2:])
case "preflight":
err = app.Preflight(os.Args[2:])
case "update":
err = runUpdate(os.Args[2:])
case "help", "-h", "--help":
usage()
return
default:
err = fmt.Errorf("unknown command %q", os.Args[1])
}
var restart *updates.RestartError
if errors.As(err, &restart) {
if err := restart.Plan.Execute(time.Now()); err != nil {
slog.Error("update switch failed; the current version stays installed", "error", err)
os.Exit(1)
}
os.Exit(updates.ExitRestart)
}
if err != nil {
slog.Error("command failed", "command", os.Args[1], "error", err)
var exit *updates.ExitError
if errors.As(err, &exit) {
os.Exit(exit.Code)
}
os.Exit(1)
}
}
@@ -53,6 +70,7 @@ Usage:
bd2server serve [--data-dir DIR] [--version-config FILE] [options]
bd2server resources fetch --output DIR [--version-config FILE]
bd2server state check [options]
bd2server update status|check|apply|cancel [--data-dir DIR] [--in 10m | --now] [--confirm-irreversible] [--json]
The server binds to loopback by default.
Logging: --log-level trace|debug|info|warn|error; --log-color auto|always|never.
+124
View File
@@ -0,0 +1,124 @@
package main
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"time"
"bd2server/internal/common/i18n"
"bd2server/internal/server/platform/updates"
)
func runUpdate(args []string) error {
if len(args) == 0 {
return errors.New("usage: bd2server update status|check|apply|cancel [--data-dir DIR]")
}
fs := flag.NewFlagSet("update "+args[0], flag.ContinueOnError)
dataDir := fs.String("data-dir", "", "server data directory (defaults beside the executable)")
asJSON := fs.Bool("json", false, "print the status as JSON")
delay := fs.Duration("in", -1, "apply: start maintenance after this countdown, e.g. 10m (default from updates.json)")
now := fs.Bool("now", false, "apply: start maintenance as soon as the release is ready")
confirm := fs.Bool("confirm-irreversible", false, "apply: accept a release whose save migration cannot be rolled back")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if *dataDir == "" {
executable, err := os.Executable()
if err != nil {
return err
}
*dataDir = filepath.Join(filepath.Dir(executable), "data")
}
directory, err := filepath.Abs(*dataDir)
if err != nil {
return err
}
switch args[0] {
case "status":
status, err := updates.ReadStatus(directory)
if err != nil {
return err
}
if *asJSON {
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", " ")
return encoder.Encode(status)
}
printStatus(status)
return nil
case "check", "apply", "cancel":
control := updates.Control{ID: requestID(), Action: args[0], ConfirmIrreversible: *confirm, RequestedAt: time.Now().UTC()}
if args[0] == updates.ActionApply {
config, err := updates.Document.Load(updates.Document.Path(filepath.Join(directory, "config")))
if err != nil {
return err
}
control.DelayMinutes = config.CountdownMinutes
if *delay >= 0 {
control.DelayMinutes = int(delay.Round(time.Minute) / time.Minute)
}
if *now {
control.DelayMinutes = 0
}
}
ack, err := updates.SubmitControl(directory, control, 90*time.Second)
if err != nil {
return err
}
fmt.Println(ack.Message)
if !ack.OK {
return errors.New("the server refused the request")
}
return nil
}
return fmt.Errorf("unknown update command %q", args[0])
}
func requestID() string {
raw := make([]byte, 8)
_, _ = rand.Read(raw)
return hex.EncodeToString(raw)
}
func printStatus(s updates.Status) {
fmt.Printf("Current %s (install method %s)\n", s.CurrentVersion, s.Method)
if !s.LastCheck.IsZero() {
fmt.Printf("Checked %s\n", s.LastCheck.Local().Format(time.DateTime))
}
if s.LastError != "" {
fmt.Printf("Check error %s\n", s.LastError)
}
if a := s.Available; a != nil {
state := "not downloaded"
if a.Downloaded {
state = "downloaded and verified"
} else if a.DownloadError != "" {
state = "download failed: " + a.DownloadError
}
fmt.Printf("Available %s (%s, migration %s)\n", a.Version, state, a.Migration.Kind)
if note := a.Migration.Note.In(i18n.Fallback); note != "" {
fmt.Printf("Migration %s\n", note)
}
if notes := a.Notes.In(i18n.Fallback); notes != "" {
fmt.Printf("\n%s\n\n", notes)
}
} else if s.LastError == "" {
fmt.Println("Available none; up to date")
}
if m := s.Maintenance; m != nil {
at := "countdown starts once the release is prepared"
if !m.At.IsZero() {
at = m.At.Local().Format(time.DateTime)
}
fmt.Printf("Maintenance %s -> %s (%s, %s)\n", m.Phase, m.Version, at, m.RequestedBy)
}
if r := s.LastResult; r != nil {
fmt.Printf("Last switch %s -> %s: %s %s\n", r.From, r.To, r.Outcome, r.Message)
}
}
+16 -13
View File
@@ -13,19 +13,22 @@ import (
)
type Config struct {
GameVersion string `json:"game_version"`
ClientVersion string `json:"client_version"`
ServerVersion string `json:"server_version"`
GameDataVersion string `json:"game_data_version"`
BundleVersion string `json:"bundle_version"`
SeedDirectory string `json:"seed_directory"`
Plugins struct {
LocalIdentity string `json:"local_identity"`
CaptureEnvironment string `json:"capture_environment"`
LoginUI string `json:"login_ui"`
CashShop string `json:"cash_shop"`
FChat string `json:"fchat"`
} `json:"plugins"`
GameVersion string `json:"game_version"`
ClientVersion string `json:"client_version"`
ServerVersion string `json:"server_version"`
GameDataVersion string `json:"game_data_version"`
BundleVersion string `json:"bundle_version"`
SeedDirectory string `json:"seed_directory"`
Plugins pluginVersions `json:"plugins"`
MinimumPlugins pluginVersions `json:"minimum_plugins"`
}
type pluginVersions struct {
LocalIdentity string `json:"local_identity"`
CaptureEnvironment string `json:"capture_environment"`
LoginUI string `json:"login_ui"`
CashShop string `json:"cash_shop"`
FChat string `json:"fchat"`
}
func readConfig(path string, config *Config) error {
+140 -49
View File
@@ -16,10 +16,11 @@ import (
clientconfig "bd2server/internal/client/config"
clientlayout "bd2server/internal/client/layout"
clientsetup "bd2server/internal/client/setup"
clientupdate "bd2server/internal/client/update"
"bd2server/internal/common/versionconfig"
)
//go:embed web/index.html web/icon.svg web/icon.png web/icon.ico
//go:embed web/index.html web/icon.svg web/icon.png web/icon.ico web/lang/*.json
var webFS embed.FS
var errGameAlreadyRunning = errors.New("Brown Dust II is already running") //nolint:staticcheck // ST1005
@@ -41,7 +42,8 @@ type Request struct {
ServerOrigin string `json:"server_origin"`
CDNMode clientconfig.CDNMode `json:"cdn_mode"`
LocalResourceDirectory string `json:"local_resource_directory"`
UILanguage string `json:"ui_language"`
// DialogTitle is the folder picker's title in the UI language.
DialogTitle string `json:"dialog_title"`
}
func (r Request) settings() clientconfig.Settings {
@@ -82,10 +84,24 @@ type Studio struct {
quitOnce sync.Once
launch func(string, string) error
savePreferences func(string) error
updates *clientupdate.Manager
}
func NewStudio(options Options, host NativeHost) *Studio {
return &Studio{options: options, host: host, ctx: context.Background(), launch: launchGame, savePreferences: clientconfig.SavePreferences}
s := &Studio{options: options, host: host, ctx: context.Background(), launch: launchGame, savePreferences: clientconfig.SavePreferences}
if executable, err := os.Executable(); err == nil {
s.updates = clientupdate.New(clientupdate.Options{
Versions: options.Versions, Directory: filepath.Dir(executable), Logger: options.Logger,
Games: func() string {
preferences, err := clientconfig.LoadPreferences()
if err != nil {
return ""
}
return preferences.GameDirectory
},
})
}
return s
}
func (s *Studio) Startup(ctx context.Context) {
@@ -96,6 +112,9 @@ func (s *Studio) Startup(ctx context.Context) {
}
s.ctx, s.cancel = owned, cancel
s.ctxMu.Unlock()
if s.updates != nil {
go s.updates.Run(owned)
}
}
func (s *Studio) Shutdown() {
@@ -129,7 +148,7 @@ func (s *Studio) Initialize() InitialState {
if state.GameDirectory == "" {
return state
}
if _, err := clientsetup.Inspect(state.GameDirectory, s.options.Versions); err != nil {
if _, err := clientsetup.Inspect(state.GameDirectory, s.versions(state.GameDirectory)); err != nil {
s.log().Warn("saved game directory is no longer valid", "error", err)
return state
}
@@ -165,18 +184,15 @@ func success(message string, data any) Response {
return Response{OK: true, Message: message, Data: data}
}
func (s *Studio) chooseDirectory(language, kind string) (string, error) {
func (s *Studio) chooseDirectory(title, kind string) (string, error) {
if s.host.BrowseDirectory == nil {
return "", errors.New("native directory picker is unavailable")
}
prompt := "Select the Brown Dust II installation directory"
if kind == "resources" {
prompt = "Select the CDN directory containing ServerData and GameData"
}
if language == "zh-CN" {
prompt = "选择 Brown Dust II 安装目录"
prompt := title
if prompt == "" {
prompt = "Select the Brown Dust II installation directory"
if kind == "resources" {
prompt = "选择包含 ServerData 和 GameData 的 CDN 目录"
prompt = "Select the CDN directory containing ServerData and GameData"
}
}
s.log().Info("directory selection opened", "kind", kind)
@@ -189,35 +205,35 @@ func (s *Studio) chooseDirectory(language, kind string) (string, error) {
func (s *Studio) Browse(input Request) (Response, error) {
return s.perform("browse game directory", func() (Response, error) {
dir, err := s.chooseDirectory(input.UILanguage, "game")
dir, err := s.chooseDirectory(input.DialogTitle, "game")
if err != nil {
return Response{}, err
}
if dir == "" {
return success("Selection cancelled", nil), nil
}
status, err := clientsetup.Inspect(dir, s.options.Versions)
status, err := clientsetup.Inspect(dir, s.versions(dir))
return success("Game client found", status), err
})
}
func (s *Studio) BrowseResources(input Request) (Response, error) {
return s.perform("browse resource directory", func() (Response, error) {
dir, err := s.chooseDirectory(input.UILanguage, "resources")
dir, err := s.chooseDirectory(input.DialogTitle, "resources")
if err != nil {
return Response{}, err
}
if dir == "" {
return success("Selection cancelled", nil), nil
}
policy, err := clientsetup.FetchResourcePolicy(s.context(), nil, clientconfig.Settings{ServerOrigin: "http://127.0.0.1", CDNMode: clientconfig.CDNLocal, LocalResourceDirectory: dir}, s.options.Versions)
policy, err := clientsetup.FetchResourcePolicy(s.context(), nil, clientconfig.Settings{ServerOrigin: "http://127.0.0.1", CDNMode: clientconfig.CDNLocal, LocalResourceDirectory: dir}, s.versions(input.GameDirectory))
return success("Local resource directory found", policy), err
})
}
func (s *Studio) Inspect(input Request) (Response, error) {
return s.perform("inspect game directory", func() (Response, error) {
status, err := clientsetup.Inspect(input.GameDirectory, s.options.Versions)
status, err := clientsetup.Inspect(input.GameDirectory, s.versions(input.GameDirectory))
return success("Game directory is valid", status), err
})
}
@@ -226,7 +242,7 @@ func (s *Studio) Resources(input Request) (Response, error) {
return s.perform("check resource policy", func() (Response, error) {
ctx, cancel := context.WithTimeout(s.context(), 12*time.Second)
defer cancel()
policy, err := clientsetup.FetchResourcePolicy(ctx, nil, input.settings(), s.options.Versions)
policy, err := clientsetup.FetchResourcePolicy(ctx, nil, input.settings(), s.versions(input.GameDirectory))
message := "The client will use the release-locked official CDN"
if policy.Mode == clientconfig.CDNLocal { //nolint:staticcheck // QF1003
message = "Local resources verified"
@@ -239,7 +255,7 @@ func (s *Studio) Resources(input Request) (Response, error) {
func (s *Studio) Save(input Request) (Response, error) {
return s.perform("save settings", func() (Response, error) {
settings, err := clientsetup.SaveSettings(input.GameDirectory, input.settings(), s.options.Versions)
settings, err := clientsetup.SaveSettings(input.GameDirectory, input.settings(), s.versions(input.GameDirectory))
if err != nil {
return Response{}, err
}
@@ -252,7 +268,7 @@ func (s *Studio) Save(input Request) (Response, error) {
func (s *Studio) Patch(input Request) (Response, error) {
return s.perform("patch client", func() (Response, error) {
result, err := clientsetup.Patch(input.GameDirectory, input.settings(), s.options.Versions)
result, err := clientsetup.Patch(input.GameDirectory, input.settings(), s.versions(input.GameDirectory))
if err != nil {
return Response{}, err
}
@@ -269,7 +285,7 @@ func (s *Studio) Patch(input Request) (Response, error) {
func (s *Studio) Install(input Request) (Response, error) {
return s.perform("install plugins", func() (Response, error) {
result, err := clientsetup.InstallPlugins(input.GameDirectory, input.settings(), s.options.Versions, s.options.LocalIdentityPlugin, s.options.LoginUIPlugin, s.options.CashShopPlugin, s.options.FChatPlugin)
result, err := clientsetup.InstallPlugins(input.GameDirectory, input.settings(), s.versions(input.GameDirectory), s.options.LocalIdentityPlugin, s.options.LoginUIPlugin, s.options.CashShopPlugin, s.options.FChatPlugin)
if err != nil {
return Response{}, err
}
@@ -277,7 +293,7 @@ func (s *Studio) Install(input Request) (Response, error) {
return Response{}, err
}
message := "BD2 client plugins installed or updated"
if !result.LocalIdentity.Changed && !result.LoginUI.Changed && !result.CashShop.Changed && !result.FChat.Changed {
if !result.Changed {
message = "BD2 client plugins are already up to date; no DLL was rewritten"
}
return success(message, result), nil
@@ -286,7 +302,13 @@ func (s *Studio) Install(input Request) (Response, error) {
func (s *Studio) Launch(input Request) (Response, error) {
return s.perform("launch game", func() (Response, error) {
status, err := clientsetup.Inspect(input.GameDirectory, s.options.Versions)
if s.updates != nil {
if err := s.updates.PrepareGame(s.context(), input.GameDirectory, input.ServerOrigin); err != nil {
return Response{}, err
}
}
versions := s.versions(input.GameDirectory)
status, err := clientsetup.Inspect(input.GameDirectory, versions)
if err != nil {
return Response{}, err
}
@@ -298,40 +320,109 @@ func (s *Studio) Launch(input Request) (Response, error) {
}
ctx, cancel := context.WithTimeout(s.context(), 12*time.Second)
defer cancel()
if _, err := clientsetup.FetchResourcePolicy(ctx, nil, input.settings(), s.options.Versions); err != nil {
if _, err := clientsetup.FetchResourcePolicy(ctx, nil, input.settings(), versions); err != nil {
return Response{}, err
}
settings, err := clientsetup.SaveSettings(input.GameDirectory, input.settings(), s.options.Versions)
if err != nil {
return Response{}, err
}
if err := s.savePreferences(input.GameDirectory); err != nil {
return Response{}, err
}
installation, err := clientlayout.Resolve(status.GameDirectory)
if err != nil {
return Response{}, err
}
if !installation.SupportedOnHost() {
return Response{}, fmt.Errorf("cannot launch a %s game client from this operating system", installation.Kind)
}
for _, name := range []string{"BD2LocalIdentity.dll", "BD2LoginUI.dll", "BD2CashShop.dll", "BD2FChat.dll"} {
info, err := os.Stat(filepath.Join(installation.Plugins, name))
if err != nil || !info.Mode().IsRegular() {
return Response{}, fmt.Errorf("install or update the client plugins before launching; %s is missing", name)
launch := func() (Response, error) {
settings, err := clientsetup.SaveSettings(input.GameDirectory, input.settings(), versions)
if err != nil {
return Response{}, err
}
}
if err := s.launch(installation.LaunchTarget(), settings.ProxyURL); err != nil {
if errors.Is(err, errGameAlreadyRunning) {
return success("Brown Dust II is already running", nil), nil
if err := s.savePreferences(input.GameDirectory); err != nil {
return Response{}, err
}
return Response{}, fmt.Errorf("launch Brown Dust II: %w", err)
installation, err := clientlayout.Resolve(status.GameDirectory)
if err != nil {
return Response{}, err
}
if !installation.SupportedOnHost() {
return Response{}, fmt.Errorf("cannot launch a %s game client from this operating system", installation.Kind)
}
for _, name := range []string{"BD2LocalIdentity.dll", "BD2LoginUI.dll", "BD2CashShop.dll", "BD2FChat.dll"} {
info, err := os.Stat(filepath.Join(installation.Plugins, name))
if err != nil || !info.Mode().IsRegular() {
return Response{}, fmt.Errorf("install or update the client plugins before launching; %s is missing", name)
}
}
if err := s.launch(installation.LaunchTarget(), settings.ProxyURL); err != nil {
if errors.Is(err, errGameAlreadyRunning) {
return success("Brown Dust II is already running", nil), nil
}
return Response{}, fmt.Errorf("launch Brown Dust II: %w", err)
}
s.log().Info("game launch requested", "platform", installation.Kind, "client_version", s.options.Versions.ClientVersion, "game_version", status.ClientVersion)
return success("Brown Dust II started", nil), nil
}
s.log().Info("game launch requested", "platform", installation.Kind, "client_version", s.options.Versions.ClientVersion, "game_version", status.ClientVersion)
return success("Brown Dust II started", nil), nil
if s.updates == nil {
return launch()
}
var response Response
err = s.updates.WithLaunch(ctx, nil, status.GameDirectory, input.ServerOrigin, func() error {
var err error
response, err = launch()
return err
})
return response, err
})
}
// UpdateStatus reports launcher and plugin updates for the status panel.
func (s *Studio) UpdateStatus() clientupdate.Status {
if s.updates == nil {
return clientupdate.Status{}
}
return s.updates.Status()
}
// CheckUpdates checks now, downloads what is newer and installs a ready
// plugin set into closed game instances.
func (s *Studio) CheckUpdates() (Response, error) {
if s.updates == nil {
return Response{}, errors.New("update service is unavailable")
}
ctx := s.context()
if err := s.updates.Check(ctx); err != nil {
return Response{}, err
}
if err := s.updates.Download(ctx); err != nil {
return Response{}, err
}
if err := s.updates.CommitGame(ctx); err != nil {
return Response{}, err
}
if err := s.updates.CommitPlugins(); err != nil {
return Response{}, err
}
return success("Update check completed", s.updates.Status()), nil
}
func (s *Studio) versions(game string) versionconfig.Config {
if s.updates != nil {
return s.updates.Versions(game)
}
return s.options.Versions
}
// ApplyLauncherUpdate restarts into the downloaded launcher. A running game
// is not closed; launching is paused until the new launcher is up.
func (s *Studio) ApplyLauncherUpdate() (Response, error) {
if s.updates == nil {
return Response{}, errors.New("update service is unavailable")
}
s.mu.Lock()
defer s.mu.Unlock()
err := s.updates.ApplyLauncher(func() {
if s.host.Quit != nil {
go s.host.Quit(s.context())
}
})
if err != nil {
return Response{}, err
}
return success("Launcher is restarting to finish the update", nil), nil
}
func (s *Studio) Quit() {
s.quitOnce.Do(func() {
s.log().Info("client exit requested")
+11
View File
@@ -1,6 +1,7 @@
package app
import (
"bd2server/internal/common/i18n"
"context"
"fmt"
"io/fs"
@@ -75,6 +76,8 @@ func Run(runOptions Options) error {
return nil
}
var launcherText = i18n.TextHandler(webFS, "web/lang")
func desktopSecurityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
@@ -82,6 +85,14 @@ func desktopSecurityHeaders(next http.Handler) http.Handler {
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'")
if r.URL.Path == "/text.js" {
i18n.ServeBrowserScript(w, r)
return
}
if r.URL.Path == "/text/format" {
launcherText(w, r)
return
}
next.ServeHTTP(w, r)
})
}
+5 -2
View File
@@ -8,6 +8,9 @@ import (
"os/exec"
"path/filepath"
"strings"
clientupdate "bd2server/internal/client/update"
"bd2server/internal/common/versionconfig"
)
func ShowFatalError(err error) {
@@ -26,7 +29,7 @@ func launchGame(target, proxyURL string) error {
}
// LaunchServices does not inherit open's environment; --env explicitly
// supplies the Unity variables to the newly launched application.
args := gameOpenArguments(target, os.Environ(), proxyURL)
args := gameOpenArguments(target, clientupdate.LaunchEnvironment(os.Environ(), target, versionconfig.Current().ClientVersion), proxyURL)
return exec.Command("open", args...).Start()
}
@@ -35,7 +38,7 @@ func gameOpenArguments(target string, environment []string, proxyURL string) []s
args := []string{target}
for _, entry := range gameProxyEnvironment(environment, proxyURL) {
key, _, found := strings.Cut(entry, "=")
if found && isGameProxyEnvironmentKey(key) {
if found && (isGameProxyEnvironmentKey(key) || strings.HasPrefix(key, "BD2_")) {
args = append(args, "--env", entry)
}
}
+4 -1
View File
@@ -13,6 +13,9 @@ import (
"time"
"unsafe"
clientupdate "bd2server/internal/client/update"
"bd2server/internal/common/versionconfig"
"golang.org/x/sys/windows"
)
@@ -73,7 +76,7 @@ func launchGame(target, proxyURL string) error {
}
command := visibleCommand(target, gameLaunchArguments()...)
command.Dir = filepath.Dir(target)
command.Env = gameProxyEnvironment(os.Environ(), proxyURL)
command.Env = clientupdate.LaunchEnvironment(gameProxyEnvironment(os.Environ(), proxyURL), filepath.Dir(target), versionconfig.Current().ClientVersion)
if err := command.Start(); err != nil {
return err
}
+140 -79
View File
@@ -1,5 +1,5 @@
<!doctype html>
<html lang="zh-CN">
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
@@ -17,7 +17,7 @@ main{max-width:1324px;margin:auto;padding:0 58px}.scene{position:relative}.intro
.scene.is-entering .reveal{animation:reveal 1.3s var(--ease) both;animation-delay:calc(var(--i,0)*110ms)}.scene.is-leaving{animation:leave .55s cubic-bezier(.4,0,.6,1) both;pointer-events:none}.transition-veil{position:fixed;inset:0;background:linear-gradient(115deg,#eee4d4ed,#dfc7a8e8);z-index:30;pointer-events:none;opacity:0;backdrop-filter:blur(8px)}.transition-veil.play{animation:veil 1.25s ease-in-out both}.opening-curtain{position:fixed;inset:0;background:#e8decc;pointer-events:none;z-index:40;animation:opening 1.65s ease forwards}
.desk-scene{padding:46px 0 34px}.desk-header{display:flex;justify-content:space-between;align-items:end;gap:24px;margin-bottom:30px}.desk-header .eyebrow{margin-bottom:13px}.desk-header h1{font-size:42px}.desk-header p{margin-top:12px;font-size:12px;color:var(--muted)}.connection-chip{display:flex;align-items:center;gap:9px;font-size:11px;color:#74634f;border:1px solid var(--line);padding:8px 13px;border-radius:30px}.dot{width:6px;height:6px;border-radius:50%;background:#a99b85;display:inline-block;flex-shrink:0}.dot.good{background:var(--olive);box-shadow:0 0 0 4px #68744912}.dot.bad{background:var(--bad)}.desk-grid{display:grid;grid-template-columns:minmax(0,1fr) 298px;gap:24px}.main-panel{background:#f9f5ec94;border:1px solid #fff9;border-radius:4px;box-shadow:0 12px 50px -40px #5c412c55}.panel-section{padding:25px 28px;border-bottom:1px solid var(--line)}.panel-section:last-child{border-bottom:0}.section-title{display:flex;align-items:center;gap:11px;margin-bottom:22px}.section-title .index{font:italic 14px var(--serif);color:#a08569}.section-title h2{font-size:15px;font-weight:500}.section-title .end{margin-left:auto;font-size:10px;color:var(--muted)}.setting-row{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-top:18px}.setting-name{font-size:10px;color:var(--muted);margin-bottom:4px}.setting-value{font-size:12px;overflow-wrap:anywhere}.setting-row>div{min-width:0}.setting-row .text-btn{font-size:11px;flex-shrink:0;color:var(--rust)}.route-options{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}.route{position:relative;cursor:pointer}.route input{position:absolute;opacity:0;inset:0;width:100%;height:100%;margin:0}.route-content{display:block;position:relative;pointer-events:none;min-height:139px;padding:15px 14px;border:1px solid var(--line);border-radius:3px;transition:.25s;background:#f8f3e83d}.route-content .route-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}.route-code{font:10px var(--serif);letter-spacing:.08em;color:#98826b}.radio-dot{width:11px;height:11px;border-radius:50%;border:1px solid #aa9680;display:block}.route-content strong{font-size:12px;font-weight:500;display:block;margin-bottom:5px}.route-content small{font-size:10px;line-height:1.75;display:block;color:var(--muted)}.route input:checked+.route-content{border-color:#9e7551;background:#b9986920;box-shadow:inset 0 0 0 1px #9e755118}.route input:checked+.route-content .radio-dot{background:#916c4a;border:3px solid #e8d9c3;box-shadow:0 0 0 1px #916c4a}.route input:focus-visible+.route-content{outline:2px solid var(--rust);outline-offset:4px}.route input:disabled+.route-content{opacity:.55}.route-actions{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:18px}.route-actions .text-btn{font-size:11px}.route-hint{font-size:10px;color:#927d64;margin-top:13px}.policy{font:11px/1.9 Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere;background:#dfd2bc50;border-left:2px solid #a3835e;padding:13px;margin-top:16px}.prepare-note{font-size:11px;color:var(--muted);margin:-8px 0 19px;line-height:1.8}.prepare-actions{display:flex;gap:10px;flex-wrap:wrap}.prepare-actions .btn{flex:1}.status-panel{align-self:start;padding:25px 23px;background:#dfd1ba66;border:1px solid #9875501c;border-radius:4px}.status-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:6px}.status-title h2{font:400 19px var(--serif)}.status-title span{font-size:9px;color:#927d65;letter-spacing:.1em}.check{display:flex;align-items:center;justify-content:space-between;padding:14px 0;border-bottom:1px solid var(--line);font-size:11px;gap:8px}.check span:last-child{color:#948471;font-size:10px}.check span.ok{color:var(--olive)}.check span.warn{color:var(--bad)}.status-foot{font-size:10px;color:#8d7a63;margin-top:14px;line-height:1.8}.log-wrap{border-top:1px solid var(--line);margin-top:24px;padding-top:19px}.log-heading{font-size:10px;color:#8d745b;display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}.log{font-size:11px;color:#7e6c56;line-height:1.8;overflow-wrap:anywhere;min-height:65px}.log strong{display:block;color:var(--ink);font-size:12px;font-weight:500;margin-bottom:5px}.history{margin-top:14px;border-top:1px solid var(--line);padding-top:12px;font-size:10px;color:#806e59}.history summary{cursor:pointer}.history ol{list-style:none;padding:0;margin:10px 0 0;max-height:180px;overflow:auto}.history li{padding:7px 0;border-top:1px solid #a487651a;overflow-wrap:anywhere}.history time{display:block;color:#9a876f;font-size:9px}.history li.error{color:var(--bad)}.unsaved{font-size:10px;color:var(--rust);margin-top:12px}.desk-footer{display:flex;justify-content:space-between;gap:20px;margin-top:24px;color:#8a765e;font-size:10px}
.desk-actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap;justify-content:flex-end}.desk-actions .btn{min-height:38px;padding:8px 16px}.local-resource{margin-top:14px;padding:14px;border:1px solid var(--line);background:#f8f3e83d;border-radius:3px}.local-resource[hidden]{display:none}.local-resource .small-note{margin:8px 0 0}
.toast{position:fixed;bottom:28px;left:50%;transform:translate(-50%,18px);max-width:min(590px,calc(100% - 32px));width:max-content;padding:13px 21px;background:#483a2e;color:#fff4e0;box-shadow:0 10px 40px #483a2e26;border:1px solid #c9ac82;border-radius:3px;font-size:12px;opacity:0;pointer-events:none;transition:.35s var(--ease);z-index:70}.toast.show{opacity:1;transform:translate(-50%,0)}.toast.error{background:#793e30;color:#fff0e3}dialog{width:min(490px,calc(100% - 32px));padding:30px;border:1px solid #fff9;border-radius:5px;background:#f0e7d7;color:var(--ink);box-shadow:0 30px 140px #37271955}dialog::backdrop{background:#40322266;backdrop-filter:blur(9px)}dialog[open]{animation:reveal .55s var(--ease)}.dialog-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:25px}.dialog-head h2{font:24px var(--serif)}.dialog-close{background:none;border:0;font-size:23px;color:var(--muted);padding:0 7px}.dialog-actions{display:flex;justify-content:flex-end;margin-top:20px}.quit-scene{min-height:65svh;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center}.quit-scene h1{font-size:44px}.quit-scene p{color:var(--muted);margin-top:20px;font-size:13px}
.update-box{display:grid;gap:4px;margin-top:12px;padding:10px 12px;border:1px solid #c9ac8288;border-radius:3px;background:#fff8ec80;font-size:12px}.update-box span{white-space:pre-line;max-height:120px;overflow:auto;color:#6d5a47}.update-box .text-btn{justify-self:start}.toast{position:fixed;bottom:28px;left:50%;transform:translate(-50%,18px);max-width:min(590px,calc(100% - 32px));width:max-content;padding:13px 21px;background:#483a2e;color:#fff4e0;box-shadow:0 10px 40px #483a2e26;border:1px solid #c9ac82;border-radius:3px;font-size:12px;opacity:0;pointer-events:none;transition:.35s var(--ease);z-index:70}.toast.show{opacity:1;transform:translate(-50%,0)}.toast.error{background:#793e30;color:#fff0e3}dialog{width:min(490px,calc(100% - 32px));padding:30px;border:1px solid #fff9;border-radius:5px;background:#f0e7d7;color:var(--ink);box-shadow:0 30px 140px #37271955}dialog::backdrop{background:#40322266;backdrop-filter:blur(9px)}dialog[open]{animation:reveal .55s var(--ease)}.dialog-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:25px}.dialog-head h2{font:24px var(--serif)}.dialog-close{background:none;border:0;font-size:23px;color:var(--muted);padding:0 7px}.dialog-actions{display:flex;justify-content:flex-end;margin-top:20px}.quit-scene{min-height:65svh;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center}.quit-scene h1{font-size:44px}.quit-scene p{color:var(--muted);margin-top:20px;font-size:13px}
@keyframes reveal{from{opacity:0;filter:blur(10px);transform:translateY(24px) scale(.986)}to{opacity:1;filter:blur(0);transform:none}}@keyframes leave{to{opacity:0;filter:blur(8px);transform:translateY(-15px) scale(1.014)}}@keyframes veil{0%,100%{opacity:0}45%,58%{opacity:1}}@keyframes opening{0%,15%{opacity:1}100%{opacity:0}}@keyframes drift{to{transform:translate(-4%,3%) scale(1.05)}}
@media(min-width:1500px){.intro-scene{gap:13%}.form-card{padding:40px}.intro-scene h1{font-size:72px}}@media(max-width:1050px){.topbar{padding:0 30px}main,.bottom-bar{padding-left:30px;padding-right:30px}.intro-scene{gap:5%}.form-card{padding:27px 23px}.desk-grid{grid-template-columns:minmax(0,1fr) 250px;gap:16px}.panel-section{padding:23px 20px}.status-panel{padding:23px 18px}.route-content{padding:12px 10px}.top-note{display:none}}@media(max-width:760px){.topbar{height:77px;padding:0 22px}main,.bottom-bar{padding-left:22px;padding-right:22px}.intro-scene{grid-template-columns:1fr;gap:32px;padding:42px 0;min-height:auto}.intro-scene h1{font-size:43px}.eyebrow{margin-bottom:17px}.lead{margin-top:18px;max-width:100%}.intro-label{display:none}.form-card{padding:25px}.card-number{position:absolute;right:25px;top:25px;font-size:31px}.form-card h2{padding-right:45px}.bottom-bar{align-items:start;flex-direction:column;gap:15px}.steps{gap:21px}.desk-scene{padding-top:31px}.desk-header{align-items:start}.desk-header h1{font-size:34px}.connection-chip{font-size:10px;padding:6px 10px;margin-top:4px}.desk-grid{grid-template-columns:1fr}.status-panel{display:grid;grid-template-columns:1fr 1fr;gap:0 30px}.status-title{grid-column:1/-1}.log-wrap{margin-top:10px;border-top:0}.status-foot{margin-bottom:14px}.desk-footer{flex-direction:column;gap:7px}.bottom-note{font-size:9px}.landscape svg{width:180%;left:-60%}.desk-header p{max-width:240px}.route-content{min-height:145px}}@media(max-width:400px){main,.bottom-bar{padding-left:16px;padding-right:16px}.form-card{padding:23px 18px}.route-options{grid-template-columns:1fr}.route-content{min-height:0;padding:12px 14px}.route-content .route-top{float:right;margin:0 0 10px 20px;gap:12px}.route-content small{max-width:90%}.status-panel{display:block}.desk-header{flex-direction:column;gap:14px}.panel-section{padding:22px 16px}.btn{padding-left:13px;padding-right:13px}.steps{gap:15px}.route-actions{align-items:stretch}.prepare-actions{flex-direction:column}}
@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}.opening-curtain{display:none}}
@@ -29,6 +29,8 @@ html,body{scrollbar-width:none}html::-webkit-scrollbar,body::-webkit-scrollbar{d
.window-control:hover{background:#8064481c}.window-control.window-close:hover{background:#b84b3a;color:white}.window-control:focus-visible{outline:2px solid var(--rust);outline-offset:-3px}
.window-control svg{width:12px;height:12px;pointer-events:none;fill:none;stroke:currentColor;stroke-width:1.3}
@media(max-width:1050px){.topbar{padding-right:164px}}@media(max-width:760px){.topbar{padding-right:152px}.brand-name{font-size:11px;letter-spacing:.12em}.brand-name small{font-size:8px}.window-control{width:40px}}
.lang-select{--wails-draggable:no-drag;flex-shrink:0;border:1px solid var(--line);border-radius:3px;background:#fffcf533;color:var(--muted);font:11px var(--sans);padding:5px 8px;cursor:pointer}.lang-select:hover:not(:disabled){color:var(--rust);border-color:#96543766}.lang-select:focus-visible{outline:2px solid var(--rust);outline-offset:3px}
html:lang(ja){--sans:'Segoe UI','Yu Gothic UI',Meiryo,sans-serif;--serif:Georgia,'Yu Mincho','Noto Serif CJK JP',serif}html:lang(ko){--sans:'Segoe UI','Malgun Gothic','Apple SD Gothic Neo',sans-serif;--serif:Georgia,Batang,'Noto Serif CJK KR',serif}html:lang(zh-TW){--sans:'Segoe UI','Microsoft JhengHei','PingFang TC',sans-serif;--serif:Georgia,'Noto Serif CJK TC',PMingLiU,serif}
</style>
</head>
<body data-scene="directory">
@@ -36,111 +38,170 @@ html,body{scrollbar-width:none}html::-webkit-scrollbar,body::-webkit-scrollbar{d
<svg viewBox="0 0 1600 1000" preserveAspectRatio="xMidYMid slice" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="sky" x2="0" y2="1"><stop stop-color="#f3e6c9"/><stop offset=".7" stop-color="#dab88e"/><stop offset="1" stop-color="#b98560"/></linearGradient><linearGradient id="mesa" x2="0.2" y2="1"><stop stop-color="#b48360"/><stop offset="1" stop-color="#8f624b"/></linearGradient><linearGradient id="sand" x2=".6" y2="1"><stop stop-color="#b8946e"/><stop offset="1" stop-color="#674b39"/></linearGradient><filter id="soft"><feGaussianBlur stdDeviation="18"/></filter></defs><path fill="url(#sky)" d="M0 0h1600v1000H0z"/><circle cx="1150" cy="270" r="91" fill="#fff4ce" opacity=".4" filter="url(#soft)"/><circle cx="1150" cy="270" r="68" fill="#fff0c7" opacity=".8"/><path d="M0 640 240 590 370 610 520 558 670 580 820 510 950 560 1120 492 1280 560 1420 482 1600 530V1000H0Z" fill="#bea17f" opacity=".6"/><path d="m835 710 60-133 43-18 17-104 32-8 17-45 130-2 18 48 32 6 15 112 35 14 36 114 58 38 212 18V1000H790Z" fill="url(#mesa)" opacity=".65"/><path d="m1004 400 15 162 24 39-12 110 75 112 18-203-23-111 33-109z" fill="#d3a079" opacity=".38"/><path d="m1280 760 81-113 24-160 47-12 13-59 122 3 14 67 19 18v496h-320Z" fill="#9a6b4f" opacity=".6"/><path d="M0 746Q260 652 525 746T1030 775 1600 724V1000H0Z" fill="#c8aa80"/><path d="M0 869Q300 687 660 860T1300 814 1600 830V1000H0Z" fill="url(#sand)" opacity=".65"/><path d="M860 1000q185-97 375-124t365-13v137Z" fill="#826045" opacity=".7"/><path d="M870 998q146-128 235-165t69-90" fill="none" stroke="#e1c397" stroke-width="3" opacity=".24"/></svg>
</div>
<div class="sunlight" aria-hidden="true"></div><div class="grain" aria-hidden="true"></div><div class="opening-curtain" aria-hidden="true"></div><div id="veil" class="transition-veil" aria-hidden="true"></div>
<header class="topbar"><div class="brand"><img class="emblem" src="/icon.svg" width="40" height="40" alt=""><div class="brand-name">BD2 LAUNCHER<small>GAME LAUNCHER</small></div></div><div class="top-note">BD2 启动器 · 配置保存在本机</div><div class="window-controls" role="group" aria-label="窗口控制"><button class="window-control" id="windowMinimise" aria-label="最小化" title="最小化"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M1 9h10"/></svg></button><button class="window-control" id="windowMaximise" aria-label="最大化或还原" title="最大化或还原"><svg viewBox="0 0 12 12" aria-hidden="true"><rect x="1.5" y="1.5" width="9" height="9"/></svg></button><button class="window-control window-close" id="windowClose" aria-label="关闭" title="关闭"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="m1.5 1.5 9 9m0-9-9 9"/></svg></button></div></header>
<header class="topbar"><div class="brand"><img class="emblem" src="/icon.svg" width="40" height="40" alt=""><div class="brand-name"><span data-i18n="launcher.brand.title"></span><small data-i18n="launcher.brand.subtitle"></small></div></div><div class="top-note" data-i18n="launcher.top_note"></div><select class="lang-select" id="language" data-i18n-attr="aria-label:launcher.language;title:launcher.language"><option value="en_us" lang="en">English</option><option value="ko_kr" lang="ko">한국어</option><option value="ja_jp" lang="ja">日本語</option><option value="zh_tw" lang="zh-TW">繁體中文</option><option value="zh_cn" lang="zh-CN">简体中文</option></select><div class="window-controls" role="group" data-i18n-attr="aria-label:launcher.window.controls"><button class="window-control" id="windowMinimise" data-i18n-attr="aria-label:launcher.window.minimize;title:launcher.window.minimize"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M1 9h10"/></svg></button><button class="window-control" id="windowMaximise" data-i18n-attr="aria-label:launcher.window.maximize;title:launcher.window.maximize"><svg viewBox="0 0 12 12" aria-hidden="true"><rect x="1.5" y="1.5" width="9" height="9"/></svg></button><button class="window-control window-close" id="windowClose" data-i18n-attr="aria-label:launcher.window.close;title:launcher.window.close"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="m1.5 1.5 9 9m0-9-9 9"/></svg></button></div></header>
<main>
<section class="scene intro-scene is-entering" id="directoryScene" aria-labelledby="directoryTitle">
<div><div class="eyebrow reveal" style="--i:1">01 / GAME DIRECTORY</div><h1 class="reveal" style="--i:2" id="directoryTitle" tabindex="-1">先从游戏目录<br>开始。</h1><p class="lead reveal" style="--i:3">选择已安装的游戏文件夹。<br>我们会检查游戏程序和资源文件,再继续设置连接。</p><div class="intro-label reveal" style="--i:4"><i></i>BrownDust II · 客户端配置</div></div>
<div class="form-card reveal" style="--i:4"><div class="card-number" aria-hidden="true">01</div><h2>选择游戏目录</h2><p class="description">请选择包含 <code>BrownDust II.exe</code> 的文件夹。</p><div id="directoryHome"><div id="directoryFields"><label class="field-label" for="gameDir">游戏安装目录</label><div class="input-row"><input id="gameDir" type="text" value="" placeholder="例如 E:\Games\BrownDust II" autocomplete="off" spellcheck="false"><button class="btn" id="browse">浏览</button></div><div class="form-tools"><span id="directoryHint">可直接填写路径,也可以浏览目录。</span><button class="text-btn" id="inspect">检查目录</button></div><p class="inline-result" id="directoryResult" role="status"></p></div></div><button class="btn primary wide" id="directoryNext"><span>继续设置服务器</span><span class="arrow" aria-hidden="true">→</span></button><p class="small-note">此步骤只检查文件,不会修改游戏资源。</p></div>
<div><div class="eyebrow reveal" style="--i:1" data-i18n="launcher.directory.step"></div><h1 class="reveal" style="--i:2" id="directoryTitle" tabindex="-1" data-i18n="launcher.directory.heading"></h1><p class="lead reveal" style="--i:3" data-i18n="launcher.directory.lead"></p><div class="intro-label reveal" style="--i:4"><i></i><span data-i18n="launcher.directory.label"></span></div></div>
<div class="form-card reveal" style="--i:4"><div class="card-number" aria-hidden="true">01</div><h2 data-i18n="launcher.directory.title"></h2><p class="description" id="directoryDescription" data-i18n="launcher.directory.description" data-i18n-code="BrownDust II.exe"></p><div id="directoryHome"><div id="directoryFields"><label class="field-label" for="gameDir" data-i18n="launcher.directory.field"></label><div class="input-row"><input id="gameDir" type="text" value="" data-i18n-attr="placeholder:launcher.directory.placeholder" autocomplete="off" spellcheck="false"><button class="btn" id="browse" data-i18n="launcher.browse"></button></div><div class="form-tools"><span id="directoryHint" data-i18n="launcher.directory.hint"></span><button class="text-btn" id="inspect" data-i18n="launcher.directory.inspect"></button></div><p class="inline-result" id="directoryResult" role="status"></p></div></div><button class="btn primary wide" id="directoryNext"><span data-i18n="launcher.directory.next"></span><span class="arrow" aria-hidden="true">→</span></button><p class="small-note" data-i18n="launcher.directory.note"></p></div>
</section>
<section class="scene intro-scene" id="serverScene" hidden aria-labelledby="serverTitle">
<div><div class="eyebrow reveal" style="--i:1">02 / SERVER CONNECTION</div><h1 class="reveal" style="--i:2" id="serverTitle" tabindex="-1">接下来,<br>设置服务器。</h1><p class="lead reveal" style="--i:3">填写要连接的服务端地址。<br>进入启动器后,你可以选择资源来源、应用补丁和安装插件。</p><div class="intro-label reveal" style="--i:4"><i></i>目录已选择 · 之后仍可修改</div></div>
<div class="form-card reveal" style="--i:4"><div class="card-number" aria-hidden="true">02</div><h2>服务器地址</h2><p class="description">填写完整地址,可以包含端口。</p><div id="serverHome"><div id="serverFields"><label class="field-label" for="origin">地址与端口</label><input id="origin" type="text" value="" placeholder="https://play.example.com" autocomplete="url" spellcheck="false" aria-describedby="originHint"><p class="small-note" id="originHint">例如 <code>http://192.168.1.8:8080</code><br>不要添加 <code>/game/</code> 或其他路径。真实连接地址由 LI 插件读取。</p><p class="inline-result" id="serverResult" role="status"></p></div></div><button class="btn primary wide" id="serverNext"><span>进入启动器</span><span class="arrow" aria-hidden="true">→</span></button><div class="server-back"><button class="text-btn" id="serverBack">← 返回目录设置</button></div></div>
<div><div class="eyebrow reveal" style="--i:1" data-i18n="launcher.server.step"></div><h1 class="reveal" style="--i:2" id="serverTitle" tabindex="-1" data-i18n="launcher.server.heading"></h1><p class="lead reveal" style="--i:3" data-i18n="launcher.server.lead"></p><div class="intro-label reveal" style="--i:4"><i></i><span data-i18n="launcher.server.label"></span></div></div>
<div class="form-card reveal" style="--i:4"><div class="card-number" aria-hidden="true">02</div><h2 data-i18n="launcher.server.title"></h2><p class="description" data-i18n="launcher.server.description"></p><div id="serverHome"><div id="serverFields"><label class="field-label" for="origin" data-i18n="launcher.server.field"></label><input id="origin" type="text" value="" placeholder="https://play.example.com" autocomplete="url" spellcheck="false" aria-describedby="originHint"><p class="small-note" id="originHint" data-i18n="launcher.server.hint" data-i18n-code="http://192.168.1.8:8080|/game/"></p><p class="inline-result" id="serverResult" role="status"></p></div></div><button class="btn primary wide" id="serverNext"><span data-i18n="launcher.server.next"></span><span class="arrow" aria-hidden="true">→</span></button><div class="server-back"><button class="text-btn" id="serverBack" data-i18n="launcher.server.back"></button></div></div>
</section>
<section class="scene desk-scene" id="deskScene" hidden aria-labelledby="deskTitle">
<header class="desk-header reveal" style="--i:0"><div><div class="eyebrow">03 / LAUNCHER</div><h1 id="deskTitle" tabindex="-1">BD2 启动器</h1><p>管理连接设置,完成游戏启动前的准备。</p></div><div class="desk-actions"><div class="connection-chip"><span class="dot" id="pulse"></span><span id="overallStatus">等待检查</span></div><button class="btn primary" id="launch">启动游戏 <span aria-hidden="true">▶</span></button></div></header>
<header class="desk-header reveal" style="--i:0"><div><div class="eyebrow" data-i18n="launcher.desk.step"></div><h1 id="deskTitle" tabindex="-1" data-i18n="launcher.title"></h1><p data-i18n="launcher.desk.subtitle"></p></div><div class="desk-actions"><div class="connection-chip"><span class="dot" id="pulse"></span><span id="overallStatus"></span></div><button class="btn primary" id="launch"><span data-i18n="launcher.launch"></span> <span aria-hidden="true">▶</span></button></div></header>
<div class="desk-grid"><div class="main-panel reveal" style="--i:1">
<section class="panel-section"><div class="section-title"><span class="index">01</span><h2>连接设置</h2><span class="end">随时可以修改</span></div><div class="setting-row"><div><div class="setting-name">游戏目录</div><div class="setting-value" id="directorySummary">尚未选择</div></div><button class="text-btn" id="editDirectory">修改目录 ↗</button></div><div class="setting-row"><div><div class="setting-name">服务器地址</div><div class="setting-value" id="serverSummary">尚未填写</div></div><button class="text-btn" id="editServer">修改地址 ↗</button></div><div class="setting-row"><div><div class="setting-name">代理</div><div class="setting-value" id="proxySummary">直接连接</div></div><button class="text-btn" id="editProxy">设置代理 ↗</button></div></section>
<section class="panel-section"><div class="section-title"><span class="index">02</span><h2>资源来源</h2><span class="end">CDN</span></div><div class="route-options" role="radiogroup" aria-label="CDN 类型">
<label class="route"><input type="radio" name="cdn" value="official" checked><span class="route-content"><span class="route-top"><span class="route-code">OFFICIAL</span><span class="radio-dot"></span></span><strong>官方 CDN</strong><small>从官方节点下载资源,不占用服主的大文件流量。</small></span></label>
<label class="route"><input type="radio" name="cdn" value="local"><span class="route-content"><span class="route-top"><span class="route-code">LOCAL</span><span class="radio-dot"></span></span><strong>本机已下载资源</strong><small>直接读取电脑上的 ServerData 和 GameData,不再下载相同文件。</small></span></label>
<label class="route"><input type="radio" name="cdn" value="server"><span class="route-content"><span class="route-top"><span class="route-code">SERVER</span><span class="radio-dot"></span></span><strong>服主资源</strong><small>由服务器提供资源地址;服主可自建 CDN,也可以反代官方 CDN。</small></span></label>
</div><div class="local-resource" id="localResource" hidden><label class="field-label" for="localResourceDir">本机 CDN 根目录</label><div class="input-row"><input id="localResourceDir" type="text" value="" placeholder="例如 E:\bd2\dl" autocomplete="off" spellcheck="false"><button class="btn" id="browseResources">浏览</button></div><p class="small-note">所选目录内必须同时包含 <code>ServerData</code> 和 <code>GameData</code>。</p></div><p class="route-hint" id="routeHint">官方模式由客户端直连版本锁定的官方 CDN。</p><div class="route-actions"><button class="text-btn" id="checkResources">验证资源来源 ↗</button><button class="btn" id="save">保存连接设置</button></div><p class="unsaved" id="dirtyNotice">当前设置尚未保存。</p><div class="policy" id="policy" role="status" hidden></div></section>
<section class="panel-section"><div class="section-title"><span class="index">03</span><h2>补丁与插件</h2></div><p class="prepare-note">操作前请先关闭游戏。补丁只修改内置 Intro 地址,并保留 <code>resources.assets.bak</code> 备份。安装插件前,请先手动安装 BepInEx。</p><div class="prepare-actions"><button class="btn rust" id="patch">应用客户端补丁 <span aria-hidden="true">↗</span></button><button class="btn primary" id="install">安装 / 更新插件 <span aria-hidden="true">↗</span></button></div></section>
</div><aside class="status-panel reveal" style="--i:3" aria-label="客户端状态"><div class="status-title"><h2>当前状态</h2><span>LOCAL STATUS</span></div><div><div class="check"><span>游戏程序</span><span id="sExe">等待检查</span></div><div class="check"><span>资源文件</span><span id="sAssets">等待检查</span></div><div class="check"><span>BepInEx</span><span id="sBep">等待检查</span></div><div class="check"><span>连接配置</span><span id="sConfig">尚未写入</span></div><p class="status-foot">状态来自本机文件检查,不代表服务器在线。<br>客户端版本:<code id="clientReleaseVersion"></code><br>游戏版本:<code id="gameReleaseVersion"></code><br>诊断日志:<code id="persistentLogPath"></code></p><button class="text-btn" style="font-size:11px" id="refresh">重新检查 ↻</button></div><div class="log-wrap"><div class="log-heading"><span>最近操作</span><time id="logTime">—</time></div><div class="log" id="log" role="status"><strong>等待操作</strong><span>选择游戏目录后即可开始检查。</span></div><details class="history"><summary>查看操作记录</summary><ol id="historyList"></ol></details></div></aside></div>
<footer class="desk-footer reveal" style="--i:4"><span>BD2 LAUNCHER <span aria-hidden="true">/</span> 配置仅保存在你的电脑上</span><span>不会保存账号凭据或服主密钥</span></footer>
<section class="panel-section"><div class="section-title"><span class="index">01</span><h2 data-i18n="launcher.connection.title"></h2><span class="end" data-i18n="launcher.connection.editable"></span></div><div class="setting-row"><div><div class="setting-name" data-i18n="launcher.connection.directory"></div><div class="setting-value" id="directorySummary"></div></div><button class="text-btn" id="editDirectory" data-i18n="launcher.connection.change_directory"></button></div><div class="setting-row"><div><div class="setting-name" data-i18n="launcher.server.title"></div><div class="setting-value" id="serverSummary"></div></div><button class="text-btn" id="editServer" data-i18n="launcher.connection.change_server"></button></div><div class="setting-row"><div><div class="setting-name" data-i18n="launcher.connection.proxy"></div><div class="setting-value" id="proxySummary"></div></div><button class="text-btn" id="editProxy" data-i18n="launcher.connection.set_proxy"></button></div></section>
<section class="panel-section"><div class="section-title"><span class="index">02</span><h2 data-i18n="launcher.resources.title"></h2><span class="end">CDN</span></div><div class="route-options" role="radiogroup" data-i18n-attr="aria-label:launcher.resources.group">
<label class="route"><input type="radio" name="cdn" value="official" checked><span class="route-content"><span class="route-top"><span class="route-code" data-i18n="launcher.resources.official.code"></span><span class="radio-dot"></span></span><strong data-i18n="launcher.resources.official.name"></strong><small data-i18n="launcher.resources.official.description"></small></span></label>
<label class="route"><input type="radio" name="cdn" value="local"><span class="route-content"><span class="route-top"><span class="route-code" data-i18n="launcher.resources.local.code"></span><span class="radio-dot"></span></span><strong data-i18n="launcher.resources.local.name"></strong><small data-i18n="launcher.resources.local.description"></small></span></label>
<label class="route"><input type="radio" name="cdn" value="server"><span class="route-content"><span class="route-top"><span class="route-code" data-i18n="launcher.resources.server.code"></span><span class="radio-dot"></span></span><strong data-i18n="launcher.resources.server.name"></strong><small data-i18n="launcher.resources.server.description"></small></span></label>
</div><div class="local-resource" id="localResource" hidden><label class="field-label" for="localResourceDir" data-i18n="launcher.resources.local_root"></label><div class="input-row"><input id="localResourceDir" type="text" value="" data-i18n-attr="placeholder:launcher.resources.local_placeholder" autocomplete="off" spellcheck="false"><button class="btn" id="browseResources" data-i18n="launcher.browse"></button></div><p class="small-note" data-i18n="launcher.resources.local_note" data-i18n-code="ServerData|GameData"></p></div><p class="route-hint" id="routeHint"></p><div class="route-actions"><button class="text-btn" id="checkResources" data-i18n="launcher.resources.verify"></button><button class="btn" id="save" data-i18n="launcher.save"></button></div><p class="unsaved" id="dirtyNotice" data-i18n="launcher.unsaved"></p><div class="policy" id="policy" role="status" hidden></div></section>
<section class="panel-section"><div class="section-title"><span class="index">03</span><h2 data-i18n="launcher.prepare.title"></h2></div><p class="prepare-note" data-i18n="launcher.prepare.note" data-i18n-code="resources.assets.bak"></p><div class="prepare-actions"><button class="btn rust" id="patch"><span data-i18n="launcher.prepare.patch"></span> <span aria-hidden="true">↗</span></button><button class="btn primary" id="install"><span data-i18n="launcher.prepare.install"></span> <span aria-hidden="true">↗</span></button></div></section>
</div><aside class="status-panel reveal" style="--i:3" data-i18n-attr="aria-label:launcher.status.label"><div class="status-title"><h2 data-i18n="launcher.status.title"></h2><span data-i18n="launcher.status.tagline"></span></div><div><div class="check"><span data-i18n="launcher.status.executable"></span><span id="sExe"></span></div><div class="check"><span data-i18n="launcher.status.assets"></span><span id="sAssets"></span></div><div class="check"><span>BepInEx</span><span id="sBep"></span></div><div class="check"><span data-i18n="launcher.status.config"></span><span id="sConfig"></span></div><p class="status-foot"><span data-i18n="launcher.status.foot"></span><br><span data-i18n="launcher.status.client_version"></span><code id="clientReleaseVersion"></code><br><span data-i18n="launcher.status.game_version"></span><code id="gameReleaseVersion"></code><br><span data-i18n="launcher.status.log_path"></span><code id="persistentLogPath"></code></p><button class="text-btn" style="font-size:11px" id="refresh" data-i18n="launcher.status.refresh"></button><div class="update-box" id="updateBox" hidden><strong id="updateTitle"></strong><span id="updateNotes"></span><button class="text-btn" style="font-size:11px" id="updateAction" hidden></button></div></div><div class="log-wrap"><div class="log-heading"><span data-i18n="launcher.log.title"></span><time id="logTime">—</time></div><div class="log" id="log" role="status"><strong data-i18n="launcher.log.idle"></strong><span data-i18n="launcher.log.idle_hint"></span></div><details class="history"><summary data-i18n="launcher.log.history"></summary><ol id="historyList"></ol></details></div></aside></div>
<footer class="desk-footer reveal" style="--i:4"><span>BD2 LAUNCHER <span aria-hidden="true">/</span> <span data-i18n="launcher.footer.local_only"></span></span><span data-i18n="launcher.footer.no_secrets"></span></footer>
</section>
<section class="scene quit-scene" id="quitScene" hidden aria-labelledby="quitTitle"><div class="eyebrow reveal">LAUNCHER</div><h1 class="reveal" id="quitTitle" tabindex="-1">工具已退出</h1><p class="reveal">现在可以关闭这个页面。</p></section>
<section class="scene quit-scene" id="quitScene" hidden aria-labelledby="quitTitle"><div class="eyebrow reveal">LAUNCHER</div><h1 class="reveal" id="quitTitle" tabindex="-1" data-i18n="launcher.quit.title"></h1><p class="reveal" data-i18n="launcher.quit.hint"></p></section>
</main>
<footer class="bottom-bar" id="journey"><ol class="steps" aria-label="设置进度"><li data-step="directory" class="active" aria-current="step"><span class="num">01</span>选择目录</li><li data-step="server"><span class="num">02</span>设置服务器</li><li data-step="desk"><span class="num">03</span>BD2 启动器</li></ol><span class="bottom-note">BROWN DUST II · GAME LAUNCHER</span></footer>
<div id="proxyHome" hidden><div id="proxyFields"><label class="field-label" for="proxyMode">连接方式</label><select id="proxyMode" class="proxy-select"><option value="direct">直接连接</option><option value="manual">手动 HTTP 代理</option></select><div id="proxyAddressField" hidden style="margin-top:18px"><label class="field-label" for="proxyURL">HTTP 代理地址</label><input id="proxyURL" type="text" placeholder="http://127.0.0.1:7890" autocomplete="off" spellcheck="false"><p class="small-note">填写 http://主机:端口,不支持账号、路径或查询参数。</p></div><p class="small-note">保存后在下次启动游戏时生效。本机地址 localhost、127.0.0.1 和 ::1 始终直接连接。</p><p class="small-note">HTTP 代理通过 CONNECT 支持游戏的 HTTPS 连接,仍会验证证书。浏览器使用自身的代理设置。</p><p id="proxyResult" class="inline-result" role="status"></p></div></div>
<dialog id="editor" aria-labelledby="editorTitle"><div class="dialog-head"><h2 id="editorTitle">修改设置</h2><button class="dialog-close" id="closeEditor" aria-label="关闭设置">×</button></div><div id="editorContent"></div><p class="small-note">修改后请在启动器保存连接设置。</p><div class="dialog-actions"><button class="btn primary" id="doneEditor">完成修改</button></div></dialog>
<footer class="bottom-bar" id="journey"><ol class="steps" data-i18n-attr="aria-label:launcher.steps.label"><li data-step="directory" class="active" aria-current="step"><span class="num">01</span><span data-i18n="launcher.steps.directory"></span></li><li data-step="server"><span class="num">02</span><span data-i18n="launcher.steps.server"></span></li><li data-step="desk"><span class="num">03</span><span data-i18n="launcher.title"></span></li></ol><span class="bottom-note">BROWN DUST II · GAME LAUNCHER</span></footer>
<div id="proxyHome" hidden><div id="proxyFields"><label class="field-label" for="proxyMode" data-i18n="launcher.proxy.mode"></label><select id="proxyMode" class="proxy-select"><option value="direct" data-i18n="launcher.proxy.direct"></option><option value="manual" data-i18n="launcher.proxy.manual"></option></select><div id="proxyAddressField" hidden style="margin-top:18px"><label class="field-label" for="proxyURL" data-i18n="launcher.proxy.address"></label><input id="proxyURL" type="text" placeholder="http://127.0.0.1:7890" autocomplete="off" spellcheck="false"><p class="small-note" data-i18n="launcher.proxy.address_hint"></p></div><p class="small-note" data-i18n="launcher.proxy.apply_hint"></p><p class="small-note" data-i18n="launcher.proxy.https_hint"></p><p id="proxyResult" class="inline-result" role="status"></p></div></div>
<dialog id="editor" aria-labelledby="editorTitle"><div class="dialog-head"><h2 id="editorTitle" data-i18n="launcher.editor.title"></h2><button class="dialog-close" id="closeEditor" data-i18n-attr="aria-label:launcher.editor.close">×</button></div><div id="editorContent"></div><p class="small-note" data-i18n="launcher.editor.note"></p><div class="dialog-actions"><button class="btn primary" id="doneEditor" data-i18n="launcher.editor.done"></button></div></dialog>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<noscript><p style="padding:20px">请启用 JavaScript 以使用BD2 启动器。</p></noscript>
<noscript><p style="padding:20px">Enable JavaScript to use the BD2 Launcher. / 请启用 JavaScript 以使用 BD2 启动器。</p></noscript>
<script src="/text.js"></script>
<script>
(()=>{
(async ()=>{
'use strict';
let HOST_PLATFORM='',INITIAL_CDN='official',AUTO_OPEN=false;
const $=id=>document.getElementById(id);
const reduced=window.matchMedia('(prefers-reduced-motion: reduce)');
const CHINA_TIME_ZONES=new Set(['Asia/Shanghai','Asia/Chongqing','Asia/Harbin','Asia/Urumqi','Asia/Hong_Kong','Asia/Macau','Asia/Taipei']);
let detectedTimeZone='';try{detectedTimeZone=Intl.DateTimeFormat().resolvedOptions().timeZone||''}catch{}
const zhCN=CHINA_TIME_ZONES.has(detectedTimeZone);
const localized=(zh,en)=>zhCN?zh:en;
if(!zhCN){
document.documentElement.lang='en';
document.title='BD2 Launcher';
const translations=new Map(Object.entries({
'BD2 启动器 · 配置保存在本机':'BD2 Launcher · Settings stay on this computer','先从游戏目录':'Start with the game directory','开始。':'first.','选择已安装的游戏文件夹。':'Select the installed game folder.','我们会检查游戏程序和资源文件,再继续设置连接。':'We will inspect the game executable and assets before configuring the connection.','客户端配置':'Client configuration','选择游戏目录':'Select game directory','请选择包含':'Select the folder containing','的文件夹。':'.','游戏安装目录':'Game installation directory','浏览':'Browse','可直接填写路径,也可以浏览目录。':'Enter a path or browse for a directory.','检查目录':'Inspect directory','继续设置服务器':'Continue to server setup','此步骤只检查文件,不会修改游戏资源。':'This step only inspects files and does not modify game assets.','接下来,':'Next,','设置服务器。':'configure the server.','填写要连接的服务端地址。':'Enter the server you want to connect to.','进入启动器后,你可以选择资源来源、应用补丁和安装插件。':'In the launcher you can select a resource source, apply the patch, and install plugins.','目录已选择 · 之后仍可修改':'Directory selected · You can change it later','服务器地址':'Server address','填写完整地址,可以包含端口。':'Enter the complete origin, including a port when needed.','地址与端口':'Address and port','例如':'Example','不要添加':'Do not add','或其他路径。真实连接地址由 LI 插件读取。':'or another path. The LI plugin reads the actual connection address.','进入启动器':'Open launcher','返回目录设置':'Back to directory setup','BD2 启动器':'BD2 Launcher','管理连接设置,完成游戏启动前的准备。':'Manage connection settings and prepare the game client.','启动游戏':'Launch game','等待检查':'Waiting','连接设置':'Connection settings','随时可以修改':'Editable at any time','游戏目录':'Game directory','尚未选择':'Not selected','修改目录 ↗':'Change directory ↗','尚未填写':'Not entered','修改地址 ↗':'Change address ↗','资源来源':'Resource source','官方 CDN':'Official CDN','从官方节点下载资源,不占用服主的大文件流量。':'Download from official nodes without using the server owner’s bandwidth.','本机已下载资源':'Downloaded local resources','直接读取电脑上的 ServerData 和 GameData,不再下载相同文件。':'Read ServerData and GameData already stored on this computer.','服主资源':'Server-provided resources','由服务器提供资源地址;服主可自建 CDN,也可以反代官方 CDN。':'The server supplies resource URLs backed by either a private CDN or an official-CDN proxy.','本机 CDN 根目录':'Local CDN root directory','所选目录内必须同时包含':'The selected directory must contain both',' 和 ':' and ','。':'.','官方模式由客户端直连版本锁定的官方 CDN。':'Official mode connects directly to the release-locked official CDN.','验证资源来源 ↗':'Verify resource source ↗','保存连接设置':'Save connection settings','当前设置尚未保存。':'Current settings have not been saved.','补丁与插件':'Patch and plugins','操作前请先关闭游戏。补丁只修改内置 Intro 地址,并保留':'Close the game first. The patch only changes the built-in Intro address and retains a','备份。安装插件前,请先手动安装 BepInEx。':'backup. Install BepInEx manually before installing the plugins.','应用客户端补丁':'Apply client patch','安装 / 更新插件':'Install / update plugins','当前状态':'Current status','游戏程序':'Game executable','资源文件':'Asset file','需手动安装':'Manual install required','连接配置':'Connection configuration','尚未写入':'Not written','状态来自本机文件检查,不代表服务器在线。':'Status is based on local files and does not indicate server availability.','客户端版本:':'Client version:','游戏版本:':'Game version:','诊断日志:':'Diagnostic log:','重新检查 ↻':'Inspect again ↻','最近操作':'Recent operation','等待操作':'Waiting for an operation','选择游戏目录后即可开始检查。':'Select the game directory to begin.','查看操作记录':'View operation history','配置仅保存在你的电脑上':'Settings are stored only on your computer','不会保存账号凭据或服主密钥':'Account credentials and server-owner secrets are never stored','工具已退出':'Tool exited','现在可以关闭这个页面。':'You can close this page now.','选择目录':'Select directory','设置服务器':'Configure server','修改设置':'Edit settings','修改后请在启动器保存连接设置。':'Save changes from the launcher when finished.','完成修改':'Finish editing','请启用 JavaScript 以使用BD2 启动器。'Line truncated
}));
const walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);let node;
while(node=walker.nextNode()){if(node.parentElement&&['SCRIPT','STYLE'].includes(node.parentElement.tagName))continue;let value=node.nodeValue;for(const [source,target] of [...translations].sort((a,b)=>b[0].length-a[0].length))value=value.replaceAll(source,target);node.nodeValue=value}
document.querySelectorAll('[aria-label]').forEach(element=>{let value=element.getAttribute('aria-label');for(const [source,target] of [...translations].sort((a,b)=>b[0].length-a[0].length))value=value.replaceAll(source,target);element.setAttribute('aria-label',value)});
$('gameDir').placeholder='Example: E:\\Games\\Brown Dust II';$('origin').placeholder='https://play.example.com';$('localResourceDir').placeholder='Example: E:\\bd2\\dl';
}
const LOCALES=['en_us','ko_kr','ja_jp','zh_tw','zh_cn'],HTML_LANG={en_us:'en',ko_kr:'ko',ja_jp:'ja',zh_tw:'zh-TW',zh_cn:'zh-CN'},LOCALE_KEY='bd2.locale',translations={};
let locale='en_us',lastUpdate=null;
const staleRender = Symbol('stale render'), renderPasses = new Map(), renderNodes = new WeakMap();
function beginRender(id) { const store = typeof id === 'string' ? renderPasses : renderNodes, pass = {id, locale, store}; store.set(id, pass); return pass; }
function rendered(value, pass) { if (locale !== pass.locale || pass.store.get(pass.id) !== pass) throw staleRender; return value; }
const {Component}=window.BD2Text;
const own=(table,key)=>Boolean(table)&&Object.prototype.hasOwnProperty.call(table,key)&&typeof table[key]==='string';
function lookup(key){const selected=translations[locale],fallback=translations.en_us;return own(selected,key)?selected[key]:own(fallback,key)?fallback[key]:key}
Component.configure({lookup,locale:()=>locale,formatURL:'/text/format'});
const t=key=>lookup(key)??key;
const dynamicText = (key, ...args) => Component.translatable(key, ...args.map(value => value && typeof value.getString === 'function' ? value : value == null ? '' : String(value))).getString();
const textOf=value=>value&&typeof value.getString==='function'?value:Component.literal(value??'');
async function rich(element,component){const language=locale,text=await component.getString();if(language===locale){element.textContent=text;element.style.whiteSpace='pre-line'}}
async function applyStatic(){await Promise.all(Array.from(document.querySelectorAll('[data-i18n]')).map(async e=>await rich(e,Component.translatable(e.dataset.i18n,...(e.dataset.i18nCode?e.dataset.i18nCode.split('|'):[])))));document.querySelectorAll('[data-i18n-attr]').forEach(e=>e.dataset.i18nAttr.split(';').forEach(pair=>{const at=pair.indexOf(':');if(at>0)e.setAttribute(pair.slice(0,at).trim(),t(pair.slice(at+1).trim()))}))}
const live=new Set();
async function put(target,value){const e=typeof target==='string'?$(target):target,component=textOf(value),pass={};e.bd2Text=component;e.bd2Pass=pass;live.add(e);const text=await component.getString();if(e.bd2Pass===pass)e.textContent=text}
function detectLocale(){let saved='';try{saved=localStorage.getItem(LOCALE_KEY)||''}catch{}if(LOCALES.includes(saved))return saved;const tags=navigator.languages&&navigator.languages.length?navigator.languages:[navigator.language||''];for(const tag of tags){const l=String(tag).toLowerCase();if(/^ko(-|$)/.test(l))return'ko_kr';if(/^ja(-|$)/.test(l))return'ja_jp';if(/^zh(-|$)/.test(l))return/^zh-(tw|hk|mo)(-|$)/.test(l)||/-hant(-|$)/.test(l)?'zh_tw':'zh_cn';if(/^en(-|$)/.test(l))return'en_us'}return'en_us'}
async function loadTranslations(){await Promise.all(LOCALES.map(async l=>{try{const r=await fetch(`lang/${l}.json`);if(r.ok)translations[l]=await r.json()}catch{}}))}
async function setLocale(next,save){locale=LOCALES.includes(next)?next:'en_us';if(save)try{localStorage.setItem(LOCALE_KEY,locale)}catch{}document.documentElement.lang=HTML_LANG[locale];document.title=t('launcher.title');$('language').value=locale;await applyStatic();await Promise.all([...live].map(e=>{if(e.isConnected)return put(e,e.bd2Text);live.delete(e)}));await sync();if(lastUpdate)await renderUpdates(lastUpdate)}
let scene='directory',busy=false,transitioning=false,toastTimer,editorKind=null,savedSignature=null;
const status={executable:null,resources:null,bepinex:null,config:null};
function payload(){const mode=document.querySelector('input[name="cdn"]:checked').value;return{game_directory:$('gameDir').value.trim(),server_origin:$('origin').value.trim(),cdn_mode:mode,local_resource_directory:mode==='local'?$('localResourceDir').value.trim():'',proxy_url:$('proxyMode').value==='manual'?$('proxyURL').value.trim():'',ui_language:zhCN?'zh-CN':'en'}}
function payload(){const mode=document.querySelector('input[name="cdn"]:checked').value;return{game_directory:$('gameDir').value.trim(),server_origin:$('origin').value.trim(),cdn_mode:mode,local_resource_directory:mode==='local'?$('localResourceDir').value.trim():'',proxy_url:$('proxyMode').value==='manual'?$('proxyURL').value.trim():''}}
function signature(){return JSON.stringify({...payload(),proxy_mode:$('proxyMode').value})}
const backendMessages={'Selection cancelled':'已取消选择','Game client found':'已找到游戏客户端','Local resource directory found':'已找到本机资源目录','Game directory is valid':'游戏目录有效','The client will use the release-locked official CDN':'将由客户端直接连接版本锁定的官方 CDN','Local resources verified':'本机资源已验证','Server resource policy verified':'服务器资源策略已确认','Connection settings saved':'连接设置已保存','Client entry point patched; the original backup was retained':'客户端入口补丁完成;原文件备份已保留','Client patch is already complete; no asset file was rewritten':'客户端补丁已经完成,未再次改写资源文件','BD2 client plugins installed or updated':'BD2 客户端插件已安装或更新','BD2 client plugins are already up to date; no DLL was rewritten':'BD2 客户端插件已经是最新版本,未再次改写 DLL','Brown Dust II started':'Brown Dust II 已启动','Brown Dust II is already running':'Brown Dust II 已经在运行','Client tool exited':'客户端工具已退出'};
const localizeMessage=message=>zhCN?(backendMessages[message]||message):message;
const backendKeys={'Update check completed':'backend.update_checked','Launcher is restarting to finish the update':'backend.launcher_restarting','update service is unavailable':'backend.update_unavailable','Another update operation is in progress':'backend.update_busy','No launcher update is available':'backend.no_launcher_update','The launcher update has not finished downloading':'backend.launcher_update_incomplete','The launcher is updating; start the game after it finishes':'backend.launcher_updating','The game is running; its plugins update after it exits':'backend.game_running_plugins','The server is updating; try again after it finishes':'backend.server_maintenance','Selection cancelled':'backend.selection_cancelled','Game client found':'backend.game_found','Local resource directory found':'backend.local_resources_found','Game directory is valid':'backend.directory_valid','The client will use the release-locked official CDN':'backend.official_cdn','Local resources verified':'backend.local_verified','Server resource policy verified':'backend.server_policy_verified','Connection settings saved':'backend.settings_saved','Client entry point patched; the original backup was retained':'backend.patched','Client patch is already complete; no asset file was rewritten':'backend.patch_current','BD2 client plugins installed or updated':'backend.plugins_installed','BD2 client plugins are already up to date; no DLL was rewritten':'backend.plugins_current','Brown Dust II started':'backend.game_started','Brown Dust II is already running':'backend.game_running','Client tool exited':'backend.tool_exited'};
const PLUGINS_REJECTED=/^Server (\S+) no longer accepts these plugins: (.+)\. Update the plugins in the launcher first$/;
const pluginList=list=>({getString:async ()=>(await Promise.all(list.split(', ').map(async item=>{const m=/^(.+) (\S+) \(needs (\S+)\)$/.exec(item);return m?await dynamicText('backend.plugin_requirement',m[1],m[2],m[3]):item}))).join(t('common.list_separator'))});
const GAME_MISMATCH=/^Server game version (\S+) does not match client game version (\S+)$/;
function backendText(message){if(!message)return null;message=String(message);if(Object.prototype.hasOwnProperty.call(backendKeys,message))return Component.translatable(backendKeys[message]);const game=GAME_MISMATCH.exec(message);if(game)return Component.translatable('backend.game_mismatch',game[1],game[2]);const m=PLUGINS_REJECTED.exec(message);return m?Component.translatable('backend.plugins_rejected',m[1],pluginList(m[2])):Component.literal(message)}
class Problem extends Error{constructor(component){super('Launcher operation failed');this.component=component}}
const fail=(key,...args)=>new Problem(Component.translatable(key,...args));
const problemText=error=>error instanceof Problem?error.component:backendText(error&&error.message||String(error))||Component.translatable('launcher.operation.failed');
const nativeMethods={browse:'Browse',browseResources:'BrowseResources',inspect:'Inspect',resources:'Resources',save:'Save',patch:'Patch',install:'Install',launch:'Launch'};
function bridge(){const bindings=window.go&&window.go.app&&window.go.app.Studio;if(!bindings)throw new Error(localized('客户端原生接口尚未就绪','The native client interface is unavailable'));return bindings}
async function api(operation,body={}){let data;try{data=await bridge()[nativeMethods[operation]](body)}catch(error){throw new Error(localizeMessage(error.message||String(error)))}if(!data||!data.ok)throw new Error(localizeMessage(data&&data.message)||localized('操作失败','Operation failed'));if(data.message)data.message=localizeMessage(data.message);return data}
function show(message,error=false){message=message||(error?localized('操作未完成','Operation failed'):localized('操作已完成','Operation completed'));clearTimeout(toastTimer);const t=$('toast');t.textContent=message;t.className='toast show'+(error?' error':'');toastTimer=setTimeout(()=>t.className='toast',5200);$('log').replaceChildren();const title=document.createElement('strong');title.textContent=error?localized('操作未完成','Operation failed'):localized('操作已完成','Operation completed');const desc=document.createElement('span');desc.textContent=message;$('log').append(title,desc);const now=new Date(),time=now.toLocaleTimeString(zhCN?'zh-CN':'en-US',{hour:'2-digit',minute:'2-digit',second:'2-digit'});$('logTime').textContent=time;const row=document.createElement('li');if(error)row.className='error';const stamp=document.createElement('time');stamp.dateTime=now.toISOString();stamp.textContent=time;row.append(stamp,document.createTextNode(message));$('historyList').prepend(row);while($('historyList').children.length>20)$('historyList').lastElementChild.remove()}
function mark(id,value,yes=localized('已就绪','Ready'),no=localized('未检测到','Not found')){const e=$(id);e.textContent=value===null?localized('等待检查','Waiting'):value?yes:no;e.className=value===null?'':value?'ok':'warn'}
function renderStatus(){mark('sExe',status.executable);mark('sAssets',status.resources);mark('sBep',status.bepinex,localized('已安装','Installed'),localized('需手动安装','Manual install required'));mark('sConfig',status.config,localized('已写入','Written'),localized('尚未写入','Not written'));const checked=status.executable!==null&&status.resources!==null;const ready=status.executable&&status.resources;$('pulse').className='dot'+(checked?(ready?' good':' bad'):'');$('overallStatus').textContent=checked?(ready?localized('游戏文件已就绪','Game files ready'):localized('游戏文件待检查','Game files need attention')):localized('等待检查','Waiting');if(savedSignature&&signature()!==savedSignature){$('sConfig').textContent=localized('有未保存修改','Unsaved changes');$('sConfig').className='warn'}}
function sync(){const p=payload();$('directorySummary').textContent=p.game_directory||localized('尚未选择','Not selected');$('serverSummary').textContent=p.server_origin||localized('尚未填写','Not entered');$('proxySummary').textContent=$('proxyMode').value==='manual'?(p.proxy_url||localized('手动 HTTP 代理 · 尚未填写','Manual HTTP proxy · Address required')):localized('直接连接','Direct connection');$('proxyAddressField').hidden=$('proxyMode').value!=='manual';$('localResource').hidden=p.cdn_mode!=='local';$('routeHint').textContent=p.cdn_mode==='official'?localized('官方模式由客户端直连版本锁定的官方 CDN。','Official mode connects directly to the release-locked official CDN.'):p.cdn_mode==='local'?localized('本机模式不会请求服务器资源接口;资源版本仍必须与当前客户端一致。','Local mode does not call the server resource API; resources must still match this client release.'):localized('服主自建与反代在客户端中是同一种来源,地址统一由服务器返回。','Private hosting and reverse proxying are one client mode; the server returns the resource URLs.');$('dirtyNotice').hidden=signature()===savedSignature;renderStatus()}
function applyStatus(s){if(!s)return;if(s.game_directory)$('gameDir').value=s.game_directory;for(const key of Object.keys(status))status[key]=Boolean(s[key]);sync();$('directoryResult').textContent=status.executable&&status.resources?localized('游戏程序和资源文件已检测到。','Game executable and asset file found.'):localized('检查已完成,请在启动器查看缺失项。','Inspection completed; review missing items in the launcher.');$('directoryResult').className='inline-result'+(status.executable&&status.resources?'':' error')}
function invalidate(directory=false){if(directory){for(const key of Object.keys(status))status[key]=null;$('directoryResult').textContent=localized('目录已修改,请重新检查。','The directory changed; inspect it again.')}$('policy').hidden=true;sync()}
function requireDirectory(){if(!payload().game_directory){$('gameDir').focus();throw new Error(localized('请先选择游戏安装目录','Select the game installation directory first'))}}
function requireOrigin(){const value=$('origin').value.trim();let u;try{u=new URL(value)}catch{throw new Error(localized('请输入完整服务器地址,例如 http://127.0.0.1:8080','Enter a complete server origin, for example http://127.0.0.1:8080'))}if(!['http:','https:'].includes(u.protocol)||u.username||u.password||u.search||u.hash||(u.pathname!=='/'&&u.pathname!==''))throw new Error(localized('服务器地址仅填写 http(s) 地址与端口,不要包含路径、查询参数或账号信息','Enter only an HTTP(S) origin and port, without a path, query, or credentials'));const loopback=['localhost','127.0.0.1','[::1]'].includes(u.hostname.toLowerCase());if(u.protocol!=='https:'&&!loopback)throw new Error(localized('公网或局域网服务器必须使用 HTTPS;只有本机 loopback 可以使用 HTTP','Public and LAN servers must use HTTPS; only loopback may use HTTP'));$('origin').value=value.replace(/\/$/,'');$('serverResult').textContent='';sync()}
function requireResources(){const p=payload();if(p.cdn_mode==='local'&&!p.local_resource_directory){$('localResourceDir').focus();throw new Error(localized('请选择包含 ServerData 和 GameData 的本机 CDN 目录','Select a local CDN directory containing ServerData and GameData'))}}
function requireProxy(){if($('proxyMode').value!=='manual')return;const value=$('proxyURL').value.trim();let u;try{u=new URL(value)}catch{}if(!u||u.protocol!=='http:'||u.username||u.password||u.search||u.hash||u.pathname!=='/'||!/^http:\/\/(?:\[[^\]]+\]|[^\s/:?#@]+):[0-9]+$/.test(value)||Number(value.slice(value.lastIndexOf(':')+1))<1||Number(value.slice(value.lastIndexOf(':')+1))>65535){const message=localized('请输入 HTTP 代理地址,例如 http://127.0.0.1:7890;仅支持主机和端口','Enter an HTTP proxy address such as http://127.0.0.1:7890, with only a host and port');$('proxyResult').textContent=message;$('proxyResult').className='inline-result error';$('proxyURL').focus();throw new Error(message)}$('proxyURL').value=value;$('proxyResult').textContent='';sync()}
function bridge(){const bindings=window.go&&window.go.app&&window.go.app.Studio;if(!bindings)throw fail('launcher.error.bridge');return bindings}
async function api(operation,body={}){let data;try{data=await bridge()[nativeMethods[operation]](body)}catch(error){throw new Problem(problemText(error))}if(!data||!data.ok)throw new Problem(backendText(data&&data.message)||Component.translatable('launcher.operation.failed'));data.text=backendText(data.message);return data}
async function show(message,error=false){const result=Component.translatable(error?'launcher.operation.failed':'launcher.operation.completed'),body=message?textOf(message):result;clearTimeout(toastTimer);const toast=$('toast');await put(toast,body);toast.className='toast show'+(error?' error':'');toastTimer=setTimeout(()=>toast.className='toast',5200);const title=document.createElement('strong'),desc=document.createElement('span');await put(title,result);await put(desc,body);$('log').replaceChildren(title,desc);const now=new Date(),time=now.toLocaleTimeString(HTML_LANG[locale],{hour:'2-digit',minute:'2-digit',second:'2-digit'});$('logTime').textContent=time;const row=document.createElement('li'),stamp=document.createElement('time'),entry=document.createElement('span');if(error)row.className='error';stamp.dateTime=now.toISOString();stamp.textContent=time;await put(entry,body);row.append(stamp,entry);$('historyList').prepend(row);while($('historyList').children.length>20)$('historyList').lastElementChild.remove()}
async function mark(id,value,yes='launcher.status.ready',no='launcher.status.not_found'){const e=$(id);await put(e,Component.translatable(value===null?'launcher.status.waiting':value?yes:no));e.className=value===null?'':value?'ok':'warn'}
async function renderStatus(){await mark('sExe',status.executable);await mark('sAssets',status.resources);await mark('sBep',status.bepinex,'launcher.status.installed','launcher.status.manual_install');await mark('sConfig',status.config,'launcher.status.written','launcher.status.not_written');const checked=status.executable!==null&&status.resources!==null;const ready=status.executable&&status.resources;$('pulse').className='dot'+(checked?(ready?' good':' bad'):'');await put('overallStatus',Component.translatable(checked?(ready?'launcher.status.files_ready':'launcher.status.files_attention'):'launcher.status.waiting'));if(savedSignature&&signature()!==savedSignature){await put('sConfig',Component.translatable('launcher.status.unsaved'));$('sConfig').className='warn'}}
async function sync(){const p=payload(),manual=$('proxyMode').value==='manual';await put('directorySummary',p.game_directory||Component.translatable('launcher.connection.not_selected'));await put('serverSummary',p.server_origin||Component.translatable('launcher.connection.not_entered'));await put('proxySummary',manual?(p.proxy_url||Component.translatable('launcher.proxy.manual_missing')):Component.translatable('launcher.proxy.direct'));$('proxyAddressField').hidden=!manual;$('localResource').hidden=p.cdn_mode!=='local';await put('routeHint',Component.translatable('launcher.resources.hint.'+p.cdn_mode));$('dirtyNotice').hidden=signature()===savedSignature;await renderStatus()}
async function applyStatus(s){if(!s)return;if(s.game_directory)$('gameDir').value=s.game_directory;for(const key of Object.keys(status))status[key]=Boolean(s[key]);await sync();const found=status.executable&&status.resources;await put('directoryResult',Component.translatable(found?'launcher.directory.found':'launcher.directory.incomplete'));$('directoryResult').className='inline-result'+(found?'':' error')}
async function invalidate(directory=false){if(directory){for(const key of Object.keys(status))status[key]=null;await put('directoryResult',Component.translatable('launcher.directory.changed'))}$('policy').hidden=true;await sync()}
function requireDirectory(){if(!payload().game_directory){$('gameDir').focus();throw fail('launcher.error.directory_required')}}
async function requireOrigin(){const value=$('origin').value.trim();let u;try{u=new URL(value)}catch{throw fail('launcher.error.origin_invalid','http://127.0.0.1:8080')}if(!['http:','https:'].includes(u.protocol)||u.username||u.password||u.search||u.hash||(u.pathname!=='/'&&u.pathname!==''))throw fail('launcher.error.origin_shape');const loopback=['localhost','127.0.0.1','[::1]'].includes(u.hostname.toLowerCase());if(u.protocol!=='https:'&&!loopback)throw fail('launcher.error.origin_https');$('origin').value=value.replace(/\/$/,'');await put('serverResult','');await sync()}
function requireResources(){const p=payload();if(p.cdn_mode==='local'&&!p.local_resource_directory){$('localResourceDir').focus();throw fail('launcher.error.resources_required')}}
async function requireProxy(){if($('proxyMode').value!=='manual')return;const value=$('proxyURL').value.trim();let u;try{u=new URL(value)}catch{}if(!u||u.protocol!=='http:'||u.username||u.password||u.search||u.hash||u.pathname!=='/'||!/^http:\/\/(?:\[[^\]]+\]|[^\s/:?#@]+):[0-9]+$/.test(value)||Number(value.slice(value.lastIndexOf(':')+1))<1||Number(value.slice(value.lastIndexOf(':')+1))>65535){const message=Component.translatable('launcher.error.proxy_invalid','http://127.0.0.1:7890');await put('proxyResult',message);$('proxyResult').className='inline-result error';$('proxyURL').focus();throw new Problem(message)}$('proxyURL').value=value;await put('proxyResult','');await sync()}
function setBusy(value){busy=value;document.querySelectorAll('button:not(.window-control),input,select').forEach(e=>{e.disabled=value});document.body.setAttribute('aria-busy',String(value))}
async function action(id,fn){if(busy||transitioning)return;const b=$(id),old=b.innerHTML;setBusy(true);b.textContent=localized('请稍候…','Please wait…');try{await fn()}catch(e){const message=e.message||String(e);show(message,true);if(scene==='directory'||editorKind==='directory'){$('directoryResult').textContent=message;$('directoryResult').className='inline-result error'}if(scene==='server'||editorKind==='server'){$('serverResult').textContent=message;$('serverResult').className='inline-result error'}}finally{b.innerHTML=old;setBusy(false)}}
async function action(id,fn){if(busy||transitioning)return;const b=$(id),old=b.innerHTML;setBusy(true);b.textContent=t('launcher.operation.wait');try{await fn()}catch(e){const message=problemText(e);await show(message,true);if(scene==='directory'||editorKind==='directory'){await put('directoryResult',message);$('directoryResult').className='inline-result error'}if(scene==='server'||editorKind==='server'){await put('serverResult',message);$('serverResult').className='inline-result error'}}finally{b.innerHTML=old;setBusy(false)}}
const delay=ms=>new Promise(resolve=>setTimeout(resolve,ms));
async function navigateScene(next){if(transitioning||scene===next)return;transitioning=true;const old=$(scene+'Scene'),target=$(next+'Scene');if(!reduced.matches){old.classList.add('is-leaving');$('veil').classList.add('play');await delay(570)}old.hidden=true;old.classList.remove('is-leaving','is-entering');scene=next;document.body.dataset.scene=next;target.hidden=false;target.classList.add('is-entering');$('journey').hidden=next==='desk'||next==='quit';document.querySelectorAll('[data-step]').forEach(e=>{const active=e.dataset.step===next;e.classList.toggle('active',active);if(active)e.setAttribute('aria-current','step');else e.removeAttribute('aria-current')});window.scrollTo({top:0,behavior:'instant'});$(next==='directory'?'directoryTitle':next==='server'?'serverTitle':next==='desk'?'deskTitle':'quitTitle').focus({preventScroll:true});if(!reduced.matches)await delay(680);$('veil').classList.remove('play');transitioning=false}
async function inspect(){requireDirectory();const r=await api('inspect',payload());applyStatus(r.data);show(r.message);return r}
function openEditor(kind){if(busy||transitioning)return;editorKind=kind;$('editorTitle').textContent=kind==='directory'?localized('修改游戏目录','Change game directory'):kind==='server'?localized('修改服务器地址','Change server address'):localized('设置代理','Set proxy');$('editorContent').append($(kind+'Fields'));$('editor').showModal();$(kind==='directory'?'gameDir':kind==='server'?'origin':'proxyMode').focus()}
async function inspect(){requireDirectory();const r=await api('inspect',payload());await applyStatus(r.data);await show(r.text);return r}
async function openEditor(kind){if(busy||transitioning)return;editorKind=kind;await put('editorTitle',Component.translatable(kind==='directory'?'launcher.editor.directory':kind==='server'?'launcher.editor.server':'launcher.proxy.title'));$('editorContent').append($(kind+'Fields'));$('editor').showModal();$(kind==='directory'?'gameDir':kind==='server'?'origin':'proxyMode').focus()}
function closeEditor(){if(busy)return;$('editor').close()}
$('editor').addEventListener('close',()=>{if(editorKind)$(editorKind+'Home').append($(editorKind+'Fields'));editorKind=null;sync()});
$('editor').addEventListener('close',async ()=>{if(editorKind)$(editorKind+'Home').append($(editorKind+'Fields'));editorKind=null;await sync()});
$('editor').addEventListener('cancel',e=>{if(busy)e.preventDefault()});
$('closeEditor').onclick=closeEditor;
$('doneEditor').onclick=()=>{try{if(editorKind==='server')requireOrigin();else if(editorKind==='proxy')requireProxy();else requireDirectory();closeEditor()}catch(e){show(e.message,true)}};
$('editProxy').onclick=()=>openEditor('proxy');$('proxyMode').addEventListener('change',()=>{$('proxyResult').textContent='';invalidate()});$('proxyURL').addEventListener('input',()=>{$('proxyResult').textContent='';invalidate()});
$('editDirectory').onclick=()=>openEditor('directory');$('editServer').onclick=()=>openEditor('server');
$('gameDir').addEventListener('input',()=>invalidate(true));$('origin').addEventListener('input',()=>{$('serverResult').textContent='';invalidate()});$('localResourceDir').addEventListener('input',()=>invalidate());document.querySelectorAll('input[name="cdn"]').forEach(e=>e.addEventListener('change',()=>invalidate()));
$('browse').onclick=()=>action('browse',async()=>{const previous=payload().game_directory;const r=await api('browse',payload());if(r.data){applyStatus(r.data);if(payload().game_directory!==previous)$('policy').hidden=true}show(r.message)});
$('browseResources').onclick=()=>action('browseResources',async()=>{const r=await api('browseResources',payload());if(r.data){$('localResourceDir').value=r.data.local_directory||'';invalidate()}show(r.message)});
$('inspect').onclick=()=>action('inspect',inspect);$('refresh').onclick=()=>action('refresh',inspect);
$('directoryNext').onclick=()=>action('directoryNext',async()=>{await inspect();sync();await navigateScene('server')});
$('serverBack').onclick=()=>{if(!busy)navigateScene('directory')};
$('serverNext').onclick=()=>action('serverNext',async()=>{requireOrigin();sync();await navigateScene('desk')});
$('checkResources').onclick=()=>action('checkResources',async()=>{requireDirectory();requireOrigin();requireResources();requireProxy();const r=await api('resources',payload()),p=r.data||{},missing=localized('未返回','Missing');$('policy').hidden=false;$('policy').textContent=p.mode==='official'?localized('OFFICIAL · 客户端使用版本锁定的官方地址','OFFICIAL · The client uses release-locked official URLs'):p.mode==='local'?`LOCAL · ${p.local_directory||payload().local_resource_directory}\nServerData · ${p.server_data_url||missing}\nGameData · ${p.game_data_url||missing}`:`SERVER · ${localized('由服务器提供资源地址','Resource URLs supplied by the server')}\nServerData · ${p.server_data_url||missing}\nGameData · ${p.game_data_url||missing}\nBundle · ${p.bundle_version||missing}\nGameData · ${p.game_data_version||missing}`;show(r.message)});
function saved(){savedSignature=signature();status.config=true;sync()}
$('save').onclick=()=>action('save',async()=>{requireDirectory();requireOrigin();requireResources();requireProxy();const r=await api('save',payload());saved();show(r.message)});
$('patch').onclick=()=>action('patch',async()=>{requireDirectory();requireOrigin();requireResources();requireProxy();const r=await api('patch',payload());saved();show(r.message)});
$('install').onclick=()=>action('install',async()=>{requireDirectory();requireOrigin();requireResources();requireProxy();const r=await api('install',payload());status.bepinex=true;saved();show(r.message)});
$('launch').onclick=()=>action('launch',async()=>{requireDirectory();requireOrigin();requireResources();requireProxy();const r=await api('launch',payload());saved();show(r.message)});
$('doneEditor').onclick=async ()=>{try{if(editorKind==='server')await requireOrigin();else if(editorKind==='proxy')await requireProxy();else requireDirectory();closeEditor()}catch(e){await show(problemText(e),true)}};
$('editProxy').onclick=async ()=>await openEditor('proxy');$('proxyMode').addEventListener('change',async ()=>{await put('proxyResult','');await invalidate()});$('proxyURL').addEventListener('input',async ()=>{await put('proxyResult','');await invalidate()});
$('editDirectory').onclick=async ()=>await openEditor('directory');$('editServer').onclick=async ()=>await openEditor('server');
$('gameDir').addEventListener('input',async ()=>await invalidate(true));$('origin').addEventListener('input',async ()=>{await put('serverResult','');await invalidate()});$('localResourceDir').addEventListener('input',async ()=>await invalidate());document.querySelectorAll('input[name="cdn"]').forEach(e=>e.addEventListener('change',async ()=>await invalidate()));
$('browse').onclick=async ()=>await action('browse',async()=>{const previous=payload().game_directory;const r=await api('browse',{...payload(),dialog_title:t('launcher.dialog.game_directory')});if(r.data){await applyStatus(r.data);if(payload().game_directory!==previous)$('policy').hidden=true}await show(r.text)});
$('browseResources').onclick=async ()=>await action('browseResources',async()=>{const r=await api('browseResources',{...payload(),dialog_title:t('launcher.dialog.resource_directory')});if(r.data){$('localResourceDir').value=r.data.local_directory||'';await invalidate()}await show(r.text)});
$('inspect').onclick=async ()=>await action('inspect',inspect);$('refresh').onclick=async ()=>await action('refresh',inspect);
$('directoryNext').onclick=async ()=>await action('directoryNext',async()=>{await inspect();await sync();await navigateScene('server')});
$('serverBack').onclick=async ()=>{if(!busy)await navigateScene('directory')};
$('serverNext').onclick=async ()=>await action('serverNext',async()=>{await requireOrigin();await sync();await navigateScene('desk')});
$('checkResources').onclick=async ()=>await action('checkResources',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('resources',payload()),p=r.data||{},local=payload().local_resource_directory,v=value=>value||t('launcher.resources.missing');$('policy').hidden=false;await put('policy',{getString:()=>p.mode==='official'?`${t('launcher.resources.official.code')} · ${t('launcher.resources.policy_official')}`:p.mode==='local'?`${t('launcher.resources.local.code')} · ${p.local_directory||local}\nServerData · ${v(p.server_data_url)}\nGameData · ${v(p.game_data_url)}`:`${t('launcher.resources.server.code')} · ${t('launcher.resources.policy_server')}\nServerData · ${v(p.server_data_url)}\nGameData · ${v(p.game_data_url)}\nBundle · ${v(p.bundle_version)}\nGameData · ${v(p.game_data_version)}`});await show(r.text)});
async function saved(){savedSignature=signature();status.config=true;await sync()}
$('save').onclick=async ()=>await action('save',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('save',payload());await saved();await show(r.text)});
$('patch').onclick=async ()=>await action('patch',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('patch',payload());await saved();await show(r.text)});
$('install').onclick=async ()=>await action('install',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('install',payload());status.bepinex=true;await saved();await show(r.text)});
$('launch').onclick=async ()=>await action('launch',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('launch',payload());await saved();await show(r.text)});
$('language').addEventListener('change',async e=>await setLocale(e.target.value,true));
$('windowMinimise').onclick=()=>window.runtime?.WindowMinimise();
$('windowMaximise').onclick=()=>window.runtime?.WindowToggleMaximise();
document.querySelector('.topbar').ondblclick=e=>{if(!e.target.closest('.window-controls'))window.runtime?.WindowToggleMaximise()};
$('windowClose').onclick=()=>{clearTimeout(toastTimer);bridge().Quit().catch(error=>show(error.message||String(error),true))};
if(!zhCN){for(const [id,label] of [['windowMinimise','Minimise'],['windowMaximise','Maximise or restore'],['windowClose','Close']]){const button=$(id);button.title=label;button.setAttribute('aria-label',label)}document.querySelector('.window-controls').setAttribute('aria-label','Window controls')}
document.querySelector('.topbar').ondblclick=e=>{if(!e.target.closest('.window-controls,.lang-select'))window.runtime?.WindowToggleMaximise()};
$('windowClose').onclick=async ()=>{clearTimeout(toastTimer);try{bridge().Quit().catch(async error=>await show(problemText(error),true))}catch(error){await show(problemText(error),true)}};
$('gameDir').addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();(editorKind?$('inspect'):$('directoryNext')).click()}});$('origin').addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();(editorKind?$('doneEditor'):$('serverNext')).click()}});
async function initialize(){setBusy(true);try{const initial=await bridge().Initialize();HOST_PLATFORM=initial.platform;INITIAL_CDN=initial.cdn_mode;AUTO_OPEN=initial.auto_open;$('gameDir').value=initial.game_directory||'';$('origin').value=initial.server_origin||'http://127.0.0.1:8080';$('localResourceDir').value=initial.local_resource_directory||'';$('proxyURL').value=initial.proxy_url||'';$('proxyMode').value=initial.proxy_url?'manual':'direct';$('clientReleaseVersion').textContent=initial.client_version||'';$('gameReleaseVersion').textContent=initial.game_version||'';$('persistentLogPath').textContent=initial.log_path||'';const initialRadio=document.querySelector(`input[name="cdn"][value="${CSS.escape(INITIAL_CDN)}"]`);if(initialRadio)initialRadio.checked=true;if(HOST_PLATFORM==='darwin'){$('gameDir').placeholder=localized('例如 /Applications/BrownDust II.app','Example: /Applications/BrownDust II.app');$('directoryScene').querySelector('.description').textContent=localized('请选择 BrownDust II.app 或它所在的文件夹。','Select BrownDust II.app or its parent folder.')}sync();if($('gameDir').value.trim()){await inspect();if(AUTO_OPEN){saved();await navigateScene('desk')}}}catch(error){show(error.message||String(error),true)}finally{setBusy(false)}}
initialize();
async function initialize(){setBusy(true);try{const initial=await bridge().Initialize();HOST_PLATFORM=initial.platform;INITIAL_CDN=initial.cdn_mode;AUTO_OPEN=initial.auto_open;$('gameDir').value=initial.game_directory||'';$('origin').value=initial.server_origin||'http://127.0.0.1:8080';$('localResourceDir').value=initial.local_resource_directory||'';$('proxyURL').value=initial.proxy_url||'';$('proxyMode').value=initial.proxy_url?'manual':'direct';$('clientReleaseVersion').textContent=initial.client_version||'';$('gameReleaseVersion').textContent=initial.game_version||'';$('persistentLogPath').textContent=initial.log_path||'';const initialRadio=document.querySelector(`input[name="cdn"][value="${CSS.escape(INITIAL_CDN)}"]`);if(initialRadio)initialRadio.checked=true;if(HOST_PLATFORM==='darwin'){const description=$('directoryDescription');$('gameDir').dataset.i18nAttr='placeholder:launcher.directory.placeholder_mac';description.dataset.i18n='launcher.directory.description_mac';description.dataset.i18nCode='BrownDust II.app';await applyStatic()}await sync();if($('gameDir').value.trim()){await inspect();if(AUTO_OPEN){await saved();await navigateScene('desk')}}}catch(error){await show(problemText(error),true)}finally{setBusy(false)}}
const updateNotes=notes=>!notes?'':typeof notes==='string'?notes:notes[locale]||notes.en_us||Object.values(notes).find(Boolean)||'';
function formatBytes(bytes){const mb=bytes>=1048576,value=bytes/(mb?1048576:1024);try{return new Intl.NumberFormat(HTML_LANG[locale],{style:'unit',unit:mb?'megabyte':'kilobyte',maximumFractionDigits:1}).format(value)}catch{return value.toFixed(1)+(mb?' MB':' KB')}}
function formatDate(value){const date=new Date(value+'T00:00:00Z');if(!/^\d{4}-\d{2}-\d{2}$/.test(value)||isNaN(date))return value;try{return date.toLocaleDateString(HTML_LANG[locale],{year:'numeric',month:'long',day:'numeric',timeZone:'UTC'})}catch{return value}}
const lines=(...items)=>items.filter(Boolean).join('\n');
const updateMeta=async item=>[item.date?await dynamicText('update.released',formatDate(String(item.date))):'',item.bytes>0?await dynamicText('update.size',formatBytes(item.bytes)):''].filter(Boolean).join(' · ');
async function renderUpdates(u) {
const renderPass = beginRender('launcher-updates');
try {
if (!u) return;
lastUpdate = u;
const message = u.message && u.message.key
? rendered(await dynamicText(u.message.key, ...(u.message.args || [])), renderPass) : '';
let head = '', body = '', label = '', act = '';
if (u.busy) {
const pct = u.total ? Math.floor(u.done * 100 / u.total) : 0;
head = t('update.busy');
body = u.busy === 'downloading' ? rendered(await dynamicText('update.downloading', pct), renderPass)
: t(u.busy === 'restarting' ? 'update.restarting' : u.busy === 'checking' ? 'update.checking'
: u.busy === 'preparing' ? 'update.preparing' : 'update.installing');
} else if (u.launcher) {
head = rendered(await dynamicText('update.launcher.available', u.launcher.version), renderPass);
body = lines(message, rendered(await updateMeta(u.launcher), renderPass), updateNotes(u.launcher.notes));
label = t(u.launcher.ready ? 'update.launcher.restart' : 'update.launcher.download');
act = u.launcher.ready ? 'apply' : 'check';
} else if (u.game) {
head = rendered(await dynamicText('update.game.available', u.game.version), renderPass);
body = lines(t('update.game.exit_hint'), u.error, ...(u.waiting || []));
label = t('update.game.update'); act = 'check';
} else if (u.plugins) {
head = rendered(await dynamicText('update.plugins.available', u.plugins.version), renderPass);
body = lines(message, rendered(await updateMeta(u.plugins), renderPass), updateNotes(u.plugins.notes));
label = t('update.plugins.update'); act = 'check';
} else if (u.waiting && u.waiting.length) {
head = t('update.plugins.ready'); body = lines(message, t('update.plugins.ready_hint'), ...u.waiting);
} else if (u.error) {
head = t('update.failed'); body = lines(message, u.error); label = t('update.retry'); act = 'check';
} else if (message) head = message;
$('updateBox').hidden = !head;
$('updateTitle').textContent = head; $('updateNotes').textContent = body;
const button = $('updateAction');
button.hidden = !act; button.textContent = label; button.dataset.act = act;
} catch (error) { if (error !== staleRender) throw error; }
}
async function updateAction(){const act=$('updateAction').dataset.act;const method=act==='apply'?'ApplyLauncherUpdate':'CheckUpdates';let data;try{data=await bridge()[method]()}catch(error){throw new Problem(problemText(error))}await show(backendText(data&&data.message))}
$('updateAction').onclick=async ()=>await action('updateAction',updateAction);
async function pollUpdates(){try{await renderUpdates(await bridge().UpdateStatus())}catch(error){await show(Component.literal(error.message||String(error)),true)}}
async function start(){await loadTranslations();await setLocale(detectLocale(),false);setInterval(pollUpdates,4000);setTimeout(pollUpdates,1500);await initialize()}
window.addEventListener('unhandledrejection',event=>{console.error(event.reason);const box=$('toast');box.textContent=String(event.reason&&event.reason.message||event.reason);box.className='toast show error';clearTimeout(toastTimer);toastTimer=setTimeout(()=>box.className='toast',5200)});
await start();
})();
</script>
</body>
+190
View File
@@ -0,0 +1,190 @@
{
"launcher.title": "BD2 Launcher",
"launcher.top_note": "BD2 Launcher · Settings stay on this computer",
"launcher.language": "Language",
"launcher.window.controls": "Window controls",
"launcher.window.minimize": "Minimize",
"launcher.window.maximize": "Maximize or restore",
"launcher.window.close": "Close",
"launcher.browse": "Browse",
"launcher.directory.heading": "Start with the\ngame directory.",
"launcher.directory.lead": "Select the installed game folder.\nWe will check the game executable and asset files before setting up the connection.",
"launcher.directory.label": "BrownDust II · Client setup",
"launcher.directory.title": "Select game directory",
"launcher.directory.description": "Select the folder that contains %[1]s.",
"launcher.directory.description_mac": "Select %[1]s or the folder that contains it.",
"launcher.directory.field": "Game installation directory",
"launcher.directory.placeholder": "Example: E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "Example: /Applications/BrownDust II.app",
"launcher.directory.hint": "Enter a path directly or browse for a folder.",
"launcher.directory.inspect": "Check directory",
"launcher.directory.next": "Continue to server setup",
"launcher.directory.note": "This step only checks files; it does not modify game assets.",
"launcher.directory.found": "Game executable and asset file found.",
"launcher.directory.incomplete": "Check complete; review the missing items in the launcher.",
"launcher.directory.changed": "The directory changed; check it again.",
"launcher.server.heading": "Next, set up\nthe server.",
"launcher.server.lead": "Enter the address of the server to connect to.\nIn the launcher you can then choose a resource source, apply the patch, and install plugins.",
"launcher.server.label": "Directory selected · You can still change it later",
"launcher.server.title": "Server address",
"launcher.server.description": "Enter the full address; a port may be included.",
"launcher.server.field": "Address and port",
"launcher.server.hint": "Example: %[1]s\nDo not add %[2]s or any other path. The LI plugin reads the actual connection address.",
"launcher.server.next": "Open launcher",
"launcher.server.back": "← Back to directory setup",
"launcher.desk.subtitle": "Manage connection settings and get the game ready to launch.",
"launcher.launch": "Launch game",
"launcher.connection.title": "Connection settings",
"launcher.connection.editable": "Change anytime",
"launcher.connection.directory": "Game directory",
"launcher.connection.not_selected": "Not selected",
"launcher.connection.change_directory": "Change directory ↗",
"launcher.connection.not_entered": "Not entered",
"launcher.connection.change_server": "Change address ↗",
"launcher.connection.proxy": "Proxy",
"launcher.connection.set_proxy": "Set proxy ↗",
"launcher.proxy.title": "Set proxy",
"launcher.proxy.mode": "Connection mode",
"launcher.proxy.direct": "Direct connection",
"launcher.proxy.manual": "Manual HTTP proxy",
"launcher.proxy.manual_missing": "Manual HTTP proxy · Address not entered",
"launcher.proxy.address": "HTTP proxy address",
"launcher.proxy.address_hint": "Enter http://host:port. Credentials, paths, and query parameters are not supported.",
"launcher.proxy.apply_hint": "Changes take effect the next time the game launches. localhost, 127.0.0.1, and ::1 always connect directly.",
"launcher.proxy.https_hint": "The HTTP proxy carries the game's HTTPS connections through CONNECT, and certificates are still verified. Browsers use their own proxy settings.",
"launcher.resources.title": "Resource source",
"launcher.resources.group": "CDN source",
"launcher.resources.official.name": "Official CDN",
"launcher.resources.official.description": "Downloads resources from official servers without using the server owner's bandwidth for large files.",
"launcher.resources.local.name": "Downloaded local resources",
"launcher.resources.local.description": "Reads ServerData and GameData already on this computer instead of downloading the same files again.",
"launcher.resources.server.name": "Server-provided resources",
"launcher.resources.server.description": "The server supplies the resource URLs; its owner can host a private CDN or reverse-proxy the official CDN.",
"launcher.resources.local_root": "Local CDN root directory",
"launcher.resources.local_placeholder": "Example: E:\\bd2\\dl",
"launcher.resources.local_note": "The selected directory must contain both %[1]s and %[2]s.",
"launcher.resources.hint.official": "In official mode the client connects directly to the release-locked official CDN.",
"launcher.resources.hint.local": "Local mode does not call the server resource API; the resources must still match the current client version.",
"launcher.resources.hint.server": "Private hosting and reverse proxying are the same source to the client; the server returns the resource URLs.",
"launcher.resources.verify": "Verify resource source ↗",
"launcher.resources.missing": "Not returned",
"launcher.resources.policy_official": "The client uses release-locked official URLs",
"launcher.resources.policy_server": "Resource URLs supplied by the server",
"launcher.save": "Save connection settings",
"launcher.unsaved": "Current settings have not been saved.",
"launcher.prepare.title": "Patch and plugins",
"launcher.prepare.note": "Close the game first. The patch only changes the built-in Intro address and keeps a %[1]s backup. Install BepInEx manually before installing plugins.",
"launcher.prepare.patch": "Apply client patch",
"launcher.prepare.install": "Install / update plugins",
"launcher.status.label": "Client status",
"launcher.status.title": "Current status",
"launcher.status.executable": "Game executable",
"launcher.status.assets": "Asset file",
"launcher.status.config": "Connection config",
"launcher.status.waiting": "Not checked",
"launcher.status.ready": "Ready",
"launcher.status.not_found": "Not found",
"launcher.status.installed": "Installed",
"launcher.status.manual_install": "Install manually",
"launcher.status.written": "Written",
"launcher.status.not_written": "Not written",
"launcher.status.unsaved": "Unsaved changes",
"launcher.status.files_ready": "Game files ready",
"launcher.status.files_attention": "Game files need attention",
"launcher.status.foot": "Status comes from local file checks and does not mean the server is online.",
"launcher.status.client_version": "Client version: ",
"launcher.status.game_version": "Game version: ",
"launcher.status.log_path": "Diagnostic log: ",
"launcher.status.refresh": "Check again ↻",
"launcher.log.title": "Recent activity",
"launcher.log.idle": "No activity yet",
"launcher.log.idle_hint": "Select the game directory to start checking.",
"launcher.log.history": "View activity history",
"launcher.operation.completed": "Operation completed",
"launcher.operation.failed": "Operation failed",
"launcher.operation.wait": "Please wait…",
"launcher.footer.local_only": "Settings are saved only on your computer",
"launcher.footer.no_secrets": "Account credentials and server-owner keys are never saved",
"launcher.quit.title": "The launcher has exited",
"launcher.quit.hint": "You can close this page now.",
"launcher.steps.label": "Setup progress",
"launcher.steps.directory": "Select directory",
"launcher.steps.server": "Set up server",
"launcher.editor.title": "Edit settings",
"launcher.editor.close": "Close settings",
"launcher.editor.note": "After editing, save the connection settings in the launcher.",
"launcher.editor.done": "Done",
"launcher.editor.directory": "Change game directory",
"launcher.editor.server": "Change server address",
"launcher.dialog.game_directory": "Select the Brown Dust II installation directory",
"launcher.dialog.resource_directory": "Select the CDN directory containing ServerData and GameData",
"launcher.error.bridge": "The native client interface is not ready",
"launcher.error.directory_required": "Select the game installation directory first",
"launcher.error.origin_invalid": "Enter a complete server address, for example %[1]s",
"launcher.error.origin_shape": "Enter only an HTTP(S) address and port, without a path, query parameters, or account details",
"launcher.error.origin_https": "Public and LAN servers must use HTTPS; only local loopback addresses may use HTTP",
"launcher.error.resources_required": "Select a local CDN directory containing ServerData and GameData",
"launcher.error.proxy_invalid": "Enter an HTTP proxy address such as %[1]s; only a host and port are supported",
"common.list_separator": ", ",
"backend.update_checked": "Update check completed",
"backend.launcher_restarting": "The launcher is restarting to finish the update",
"backend.update_unavailable": "The update service is unavailable",
"backend.update_busy": "Another update operation is in progress",
"backend.no_launcher_update": "No launcher update is available",
"backend.launcher_update_incomplete": "The launcher update has not finished downloading",
"backend.launcher_updating": "The launcher is updating; start the game after it finishes",
"backend.game_running_plugins": "The game is running; its plugins update after it exits",
"backend.selection_cancelled": "Selection cancelled",
"backend.game_found": "Game client found",
"backend.local_resources_found": "Local resource directory found",
"backend.directory_valid": "Game directory is valid",
"backend.official_cdn": "The client will use the release-locked official CDN",
"backend.local_verified": "Local resources verified",
"backend.server_policy_verified": "Server resource policy verified",
"backend.settings_saved": "Connection settings saved",
"backend.patched": "Client entry point patched; the original backup was retained",
"backend.patch_current": "Client patch is already complete; no asset file was rewritten",
"backend.plugins_installed": "BD2 client plugins installed or updated",
"backend.plugins_current": "BD2 client plugins are already up to date; no DLL was rewritten",
"backend.game_started": "Brown Dust II started",
"backend.game_running": "Brown Dust II is already running",
"backend.tool_exited": "Client tool exited",
"backend.plugins_rejected": "Server %[1]s no longer accepts these plugins: %[2]s. Update the plugins in the launcher first",
"backend.plugin_requirement": "%[1]s %[2]s (needs %[3]s)",
"update.game.available": "Required game update %[1]s",
"update.game.exit_hint": "Close all game instances. The launcher downloads and verifies the required game and resources before the next launch.",
"update.game.update": "Update game",
"update.busy": "Updating…",
"update.downloading": "Downloading %[1]s%%",
"update.installing": "Installing update",
"update.restarting": "The launcher is about to restart",
"update.released": "Released %[1]s",
"update.size": "Download size %[1]s",
"update.failed": "Update check failed",
"update.retry": "Retry",
"update.launcher.available": "Launcher update %[1]s",
"update.launcher.restart": "Restart to update",
"update.launcher.download": "Download update",
"update.launcher.switched": "Launcher updated from %[1]s to %[2]s",
"update.launcher.switch_failed": "Update to %[1]s failed: %[2]s. Still using %[3]s",
"update.plugins.available": "Plugin update %[1]s",
"update.plugins.update": "Update plugins",
"update.plugins.ready": "Plugin update ready",
"update.plugins.ready_hint": "It takes effect after the running game exits.",
"update.plugins.updated": "Plugins updated to %[1]s",
"update.plugins.updated_waiting": "Plugins updated to %[1]s; running games pick them up after they exit",
"update.plugins.applied_after_exit": "The game exited; the plugin update has been applied",
"update.checking": "Checking for updates",
"update.preparing": "Preparing to start the game",
"backend.server_maintenance": "The server is updating; try again after it finishes",
"backend.game_mismatch": "Server game version %[1]s does not match client game version %[2]s",
"launcher.brand.title": "BD2 LAUNCHER",
"launcher.brand.subtitle": "GAME LAUNCHER",
"launcher.directory.step": "01 / GAME DIRECTORY",
"launcher.server.step": "02 / SERVER CONNECTION",
"launcher.desk.step": "03 / LAUNCHER",
"launcher.status.tagline": "LOCAL STATUS",
"launcher.resources.official.code": "OFFICIAL",
"launcher.resources.local.code": "LOCAL",
"launcher.resources.server.code": "SERVER"
}
+190
View File
@@ -0,0 +1,190 @@
{
"launcher.title": "BD2 ランチャー",
"launcher.top_note": "BD2 ランチャー · 設定はこの PC に保存されます",
"launcher.language": "言語",
"launcher.window.controls": "ウィンドウ操作",
"launcher.window.minimize": "最小化",
"launcher.window.maximize": "最大化 / 元に戻す",
"launcher.window.close": "閉じる",
"launcher.browse": "参照",
"launcher.directory.heading": "まずは\nフォルダー選択から。",
"launcher.directory.lead": "インストール済みのゲームフォルダーを選択してください。\nゲーム本体とリソースファイルを確認してから、接続設定に進みます。",
"launcher.directory.label": "BrownDust II · クライアント設定",
"launcher.directory.title": "ゲームフォルダーを選択",
"launcher.directory.description": "%[1]s があるフォルダーを選択してください。",
"launcher.directory.description_mac": "%[1]s またはそれがあるフォルダーを選択してください。",
"launcher.directory.field": "ゲームのインストール先",
"launcher.directory.placeholder": "例: E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "例: /Applications/BrownDust II.app",
"launcher.directory.hint": "パスを直接入力するか、参照して選択できます。",
"launcher.directory.inspect": "フォルダーを確認",
"launcher.directory.next": "サーバー設定へ進む",
"launcher.directory.note": "この手順ではファイルを確認するだけで、ゲームのリソースは変更しません。",
"launcher.directory.found": "ゲーム本体とリソースファイルが見つかりました。",
"launcher.directory.incomplete": "確認が完了しました。不足している項目はランチャーで確認してください。",
"launcher.directory.changed": "フォルダーが変更されました。もう一度確認してください。",
"launcher.server.heading": "次に、\nサーバーを設定します。",
"launcher.server.lead": "接続先のサーバーアドレスを入力してください。\nランチャーでは、リソースの取得元の選択、パッチの適用、プラグインのインストールができます。",
"launcher.server.label": "フォルダー選択済み · 後から変更できます",
"launcher.server.title": "サーバーアドレス",
"launcher.server.description": "完全なアドレスを入力してください。ポート番号も指定できます。",
"launcher.server.field": "アドレスとポート",
"launcher.server.hint": "例: %[1]s\n%[2]s などのパスは付けないでください。実際の接続先は LI プラグインが読み取ります。",
"launcher.server.next": "ランチャーを開く",
"launcher.server.back": "← フォルダー設定に戻る",
"launcher.desk.subtitle": "接続設定を管理し、ゲーム起動の準備を整えます。",
"launcher.launch": "ゲームを起動",
"launcher.connection.title": "接続設定",
"launcher.connection.editable": "いつでも変更できます",
"launcher.connection.directory": "ゲームフォルダー",
"launcher.connection.not_selected": "未選択",
"launcher.connection.change_directory": "フォルダーを変更 ↗",
"launcher.connection.not_entered": "未入力",
"launcher.connection.change_server": "アドレスを変更 ↗",
"launcher.connection.proxy": "プロキシ",
"launcher.connection.set_proxy": "プロキシを設定 ↗",
"launcher.proxy.title": "プロキシを設定",
"launcher.proxy.mode": "接続方法",
"launcher.proxy.direct": "直接接続",
"launcher.proxy.manual": "手動 HTTP プロキシ",
"launcher.proxy.manual_missing": "手動 HTTP プロキシ · 未入力",
"launcher.proxy.address": "HTTP プロキシのアドレス",
"launcher.proxy.address_hint": "http://ホスト:ポート の形式で入力してください。認証情報、パス、クエリパラメーターは使用できません。",
"launcher.proxy.apply_hint": "保存した設定は次回のゲーム起動時に反映されます。localhost、127.0.0.1、::1 は常に直接接続します。",
"launcher.proxy.https_hint": "HTTP プロキシは CONNECT でゲームの HTTPS 接続を中継し、証明書の検証も引き続き行います。ブラウザーは独自のプロキシ設定を使用します。",
"launcher.resources.title": "リソースの取得元",
"launcher.resources.group": "CDN の種類",
"launcher.resources.official.name": "公式 CDN",
"launcher.resources.official.description": "公式のサーバーからリソースをダウンロードします。サーバー管理者の大容量通信を消費しません。",
"launcher.resources.local.name": "ダウンロード済みのリソース",
"launcher.resources.local.description": "PC 上の ServerData と GameData を直接読み込み、同じファイルを再ダウンロードしません。",
"launcher.resources.server.name": "サーバー提供のリソース",
"launcher.resources.server.description": "サーバーがリソースのアドレスを提供します。管理者は独自の CDN を用意することも、公式 CDN をリバースプロキシすることもできます。",
"launcher.resources.local_root": "ローカル CDN のルートフォルダー",
"launcher.resources.local_placeholder": "例: E:\\bd2\\dl",
"launcher.resources.local_note": "選択するフォルダーには %[1]s と %[2]s の両方が必要です。",
"launcher.resources.hint.official": "公式モードでは、クライアントがバージョン固定の公式 CDN に直接接続します。",
"launcher.resources.hint.local": "ローカルモードではサーバーのリソース API を使用しません。リソースのバージョンは現在のクライアントと一致している必要があります。",
"launcher.resources.hint.server": "独自ホスティングとリバースプロキシは、クライアントからは同じ取得元として扱われます。アドレスはサーバーが返します。",
"launcher.resources.verify": "リソースの取得元を確認 ↗",
"launcher.resources.missing": "未取得",
"launcher.resources.policy_official": "クライアントはバージョン固定の公式アドレスを使用します",
"launcher.resources.policy_server": "リソースのアドレスはサーバーが提供します",
"launcher.save": "接続設定を保存",
"launcher.unsaved": "現在の設定はまだ保存されていません。",
"launcher.prepare.title": "パッチとプラグイン",
"launcher.prepare.note": "操作の前にゲームを終了してください。パッチは内蔵の Intro アドレスのみを変更し、%[1]s のバックアップを残します。プラグインをインストールする前に、BepInEx を手動でインストールしてください。",
"launcher.prepare.patch": "クライアントパッチを適用",
"launcher.prepare.install": "プラグインをインストール / 更新",
"launcher.status.label": "クライアントの状態",
"launcher.status.title": "現在の状態",
"launcher.status.executable": "ゲーム本体",
"launcher.status.assets": "リソースファイル",
"launcher.status.config": "接続設定",
"launcher.status.waiting": "未確認",
"launcher.status.ready": "準備完了",
"launcher.status.not_found": "見つかりません",
"launcher.status.installed": "インストール済み",
"launcher.status.manual_install": "手動インストールが必要",
"launcher.status.written": "書き込み済み",
"launcher.status.not_written": "未書き込み",
"launcher.status.unsaved": "未保存の変更あり",
"launcher.status.files_ready": "ゲームファイルの準備完了",
"launcher.status.files_attention": "ゲームファイルを確認してください",
"launcher.status.foot": "状態はローカルファイルの確認結果であり、サーバーがオンラインであることを示すものではありません。",
"launcher.status.client_version": "クライアントバージョン: ",
"launcher.status.game_version": "ゲームバージョン: ",
"launcher.status.log_path": "診断ログ: ",
"launcher.status.refresh": "再確認 ↻",
"launcher.log.title": "最近の操作",
"launcher.log.idle": "操作待ち",
"launcher.log.idle_hint": "ゲームフォルダーを選択すると確認を開始できます。",
"launcher.log.history": "操作履歴を表示",
"launcher.operation.completed": "操作が完了しました",
"launcher.operation.failed": "操作を完了できませんでした",
"launcher.operation.wait": "お待ちください…",
"launcher.footer.local_only": "設定はお使いの PC にのみ保存されます",
"launcher.footer.no_secrets": "アカウント情報やサーバー管理者の秘密鍵は保存されません",
"launcher.quit.title": "ツールを終了しました",
"launcher.quit.hint": "このページを閉じてかまいません。",
"launcher.steps.label": "設定の進行状況",
"launcher.steps.directory": "フォルダーを選択",
"launcher.steps.server": "サーバーを設定",
"launcher.editor.title": "設定を変更",
"launcher.editor.close": "設定を閉じる",
"launcher.editor.note": "変更後は、ランチャーで接続設定を保存してください。",
"launcher.editor.done": "完了",
"launcher.editor.directory": "ゲームフォルダーを変更",
"launcher.editor.server": "サーバーアドレスを変更",
"launcher.dialog.game_directory": "Brown Dust II のインストール先フォルダーを選択",
"launcher.dialog.resource_directory": "ServerData と GameData を含む CDN フォルダーを選択",
"launcher.error.bridge": "クライアントのネイティブインターフェースの準備ができていません",
"launcher.error.directory_required": "先にゲームのインストール先を選択してください",
"launcher.error.origin_invalid": "完全なサーバーアドレスを入力してください(例: %[1]s)",
"launcher.error.origin_shape": "サーバーアドレスには http(s) のアドレスとポートのみを入力し、パス、クエリパラメーター、アカウント情報は含めないでください",
"launcher.error.origin_https": "インターネットや LAN 上のサーバーには HTTPS が必要です。HTTP はローカルのループバックアドレスでのみ使用できます",
"launcher.error.resources_required": "ServerData と GameData を含むローカル CDN フォルダーを選択してください",
"launcher.error.proxy_invalid": "HTTP プロキシのアドレスを入力してください(例: %[1]s)。指定できるのはホストとポートのみです",
"common.list_separator": "、",
"backend.update_checked": "アップデートを確認しました",
"backend.launcher_restarting": "アップデートを完了するため、ランチャーを再起動しています",
"backend.update_unavailable": "アップデートサービスを利用できません",
"backend.update_busy": "別のアップデート処理が進行中です",
"backend.no_launcher_update": "利用可能なランチャーのアップデートはありません",
"backend.launcher_update_incomplete": "ランチャーのアップデートのダウンロードが完了していません",
"backend.launcher_updating": "ランチャーをアップデート中です。完了してからゲームを起動してください",
"backend.game_running_plugins": "ゲームが実行中です。プラグインはゲームの終了後に更新されます",
"backend.selection_cancelled": "選択をキャンセルしました",
"backend.game_found": "ゲームクライアントが見つかりました",
"backend.local_resources_found": "ローカルリソースのフォルダーが見つかりました",
"backend.directory_valid": "ゲームフォルダーは有効です",
"backend.official_cdn": "クライアントはバージョン固定の公式 CDN を使用します",
"backend.local_verified": "ローカルリソースを確認しました",
"backend.server_policy_verified": "サーバーのリソースポリシーを確認しました",
"backend.settings_saved": "接続設定を保存しました",
"backend.patched": "クライアントのエントリーポイントにパッチを適用しました。元のファイルのバックアップは保持されています",
"backend.patch_current": "クライアントパッチは適用済みです。リソースファイルは書き換えていません",
"backend.plugins_installed": "BD2 クライアントプラグインをインストールまたは更新しました",
"backend.plugins_current": "BD2 クライアントプラグインは最新です。DLL は書き換えていません",
"backend.game_started": "Brown Dust II を起動しました",
"backend.game_running": "Brown Dust II はすでに実行中です",
"backend.tool_exited": "クライアントツールを終了しました",
"backend.plugins_rejected": "サーバー %[1]s は次のプラグインを受け付けなくなりました: %[2]s。先にランチャーでプラグインを更新してください",
"backend.plugin_requirement": "%[1]s %[2]s(%[3]s が必要)",
"update.game.available": "必須のゲーム更新 %[1]s",
"update.game.exit_hint": "すべてのゲームを終了してください。次回起動前にゲームとリソースをダウンロードして検証します。",
"update.game.update": "ゲームを更新",
"update.busy": "アップデート中…",
"update.downloading": "ダウンロード中 %[1]s%%",
"update.installing": "アップデートをインストール中",
"update.restarting": "まもなくランチャーを再起動します",
"update.released": "%[1]s リリース",
"update.size": "ダウンロードサイズ %[1]s",
"update.failed": "アップデートを確認できませんでした",
"update.retry": "再試行",
"update.launcher.available": "ランチャーの新バージョン %[1]s",
"update.launcher.restart": "再起動してアップデート",
"update.launcher.download": "アップデートをダウンロード",
"update.launcher.switched": "ランチャーを %[1]s から %[2]s にアップデートしました",
"update.launcher.switch_failed": "%[1]s へのアップデートに失敗しました: %[2]s。引き続き %[3]s を使用します",
"update.plugins.available": "プラグインの新バージョン %[1]s",
"update.plugins.update": "プラグインを更新",
"update.plugins.ready": "プラグインの更新準備ができました",
"update.plugins.ready_hint": "実行中のゲームが終了すると自動的に反映されます。",
"update.plugins.updated": "プラグインを %[1]s に更新しました",
"update.plugins.updated_waiting": "プラグインを %[1]s に更新しました。実行中のゲームには終了後に反映されます",
"update.plugins.applied_after_exit": "ゲームが終了したため、プラグインの更新を適用しました",
"update.checking": "更新を確認中",
"update.preparing": "ゲームの起動を準備中",
"backend.server_maintenance": "サーバーを更新中です。完了後にもう一度お試しください",
"backend.game_mismatch": "サーバーのゲームバージョン %[1]s とクライアントのゲームバージョン %[2]s が一致しません",
"launcher.brand.title": "BD2 ランチャー",
"launcher.brand.subtitle": "ゲームランチャー",
"launcher.directory.step": "01 / ゲームフォルダー",
"launcher.server.step": "02 / サーバー接続",
"launcher.desk.step": "03 / ランチャー",
"launcher.status.tagline": "ローカル状態",
"launcher.resources.official.code": "公式",
"launcher.resources.local.code": "ローカル",
"launcher.resources.server.code": "サーバー"
}
+190
View File
@@ -0,0 +1,190 @@
{
"launcher.title": "BD2 런처",
"launcher.top_note": "BD2 런처 · 설정은 이 컴퓨터에 저장됩니다",
"launcher.language": "언어",
"launcher.window.controls": "창 제어",
"launcher.window.minimize": "최소화",
"launcher.window.maximize": "최대화 또는 이전 크기로 복원",
"launcher.window.close": "닫기",
"launcher.browse": "찾아보기",
"launcher.directory.heading": "게임 폴더부터\n시작하세요.",
"launcher.directory.lead": "설치된 게임 폴더를 선택하세요.\n게임 실행 파일과 리소스 파일을 확인한 뒤 연결 설정으로 넘어갑니다.",
"launcher.directory.label": "BrownDust II · 클라이언트 설정",
"launcher.directory.title": "게임 폴더 선택",
"launcher.directory.description": "%[1]s 파일이 있는 폴더를 선택하세요.",
"launcher.directory.description_mac": "%[1]s 또는 이 앱이 있는 폴더를 선택하세요.",
"launcher.directory.field": "게임 설치 폴더",
"launcher.directory.placeholder": "예: E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "예: /Applications/BrownDust II.app",
"launcher.directory.hint": "경로를 직접 입력하거나 폴더를 찾아볼 수 있습니다.",
"launcher.directory.inspect": "폴더 확인",
"launcher.directory.next": "서버 설정으로 계속",
"launcher.directory.note": "이 단계에서는 파일만 확인하며 게임 리소스를 수정하지 않습니다.",
"launcher.directory.found": "게임 실행 파일과 리소스 파일을 찾았습니다.",
"launcher.directory.incomplete": "확인을 마쳤습니다. 누락된 항목은 런처에서 확인하세요.",
"launcher.directory.changed": "폴더가 변경되었습니다. 다시 확인하세요.",
"launcher.server.heading": "이제\n서버를 설정하세요.",
"launcher.server.lead": "연결할 서버 주소를 입력하세요.\n런처에서 리소스 출처를 선택하고, 패치를 적용하고, 플러그인을 설치할 수 있습니다.",
"launcher.server.label": "폴더 선택 완료 · 나중에 변경할 수 있습니다",
"launcher.server.title": "서버 주소",
"launcher.server.description": "전체 주소를 입력하세요. 포트를 포함할 수 있습니다.",
"launcher.server.field": "주소 및 포트",
"launcher.server.hint": "예: %[1]s\n%[2]s 같은 경로는 붙이지 마세요. 실제 연결 주소는 LI 플러그인이 읽습니다.",
"launcher.server.next": "런처 열기",
"launcher.server.back": "← 폴더 설정으로 돌아가기",
"launcher.desk.subtitle": "연결 설정을 관리하고 게임 실행 준비를 마치세요.",
"launcher.launch": "게임 실행",
"launcher.connection.title": "연결 설정",
"launcher.connection.editable": "언제든지 변경 가능",
"launcher.connection.directory": "게임 폴더",
"launcher.connection.not_selected": "선택되지 않음",
"launcher.connection.change_directory": "폴더 변경 ↗",
"launcher.connection.not_entered": "입력되지 않음",
"launcher.connection.change_server": "주소 변경 ↗",
"launcher.connection.proxy": "프록시",
"launcher.connection.set_proxy": "프록시 설정 ↗",
"launcher.proxy.title": "프록시 설정",
"launcher.proxy.mode": "연결 방식",
"launcher.proxy.direct": "직접 연결",
"launcher.proxy.manual": "수동 HTTP 프록시",
"launcher.proxy.manual_missing": "수동 HTTP 프록시 · 주소 미입력",
"launcher.proxy.address": "HTTP 프록시 주소",
"launcher.proxy.address_hint": "http://호스트:포트 형식으로 입력하세요. 계정 정보, 경로, 쿼리 매개변수는 지원하지 않습니다.",
"launcher.proxy.apply_hint": "저장한 설정은 다음에 게임을 실행할 때 적용됩니다. localhost, 127.0.0.1, ::1은 항상 직접 연결합니다.",
"launcher.proxy.https_hint": "HTTP 프록시는 CONNECT를 통해 게임의 HTTPS 연결을 지원하며, 인증서도 그대로 검증합니다. 브라우저는 자체 프록시 설정을 사용합니다.",
"launcher.resources.title": "리소스 출처",
"launcher.resources.group": "CDN 유형",
"launcher.resources.official.name": "공식 CDN",
"launcher.resources.official.description": "공식 노드에서 리소스를 다운로드하므로 서버 운영자의 대용량 트래픽을 사용하지 않습니다.",
"launcher.resources.local.name": "이미 다운로드한 로컬 리소스",
"launcher.resources.local.description": "컴퓨터에 있는 ServerData와 GameData를 직접 읽으며 같은 파일을 다시 다운로드하지 않습니다.",
"launcher.resources.server.name": "서버 제공 리소스",
"launcher.resources.server.description": "서버가 리소스 주소를 제공합니다. 운영자는 자체 CDN을 운영하거나 공식 CDN을 리버스 프록시할 수 있습니다.",
"launcher.resources.local_root": "로컬 CDN 루트 폴더",
"launcher.resources.local_placeholder": "예: E:\\bd2\\dl",
"launcher.resources.local_note": "선택한 폴더에는 %[1]s 및 %[2]s 파일이 모두 있어야 합니다.",
"launcher.resources.hint.official": "공식 모드에서는 클라이언트가 버전이 고정된 공식 CDN에 직접 연결합니다.",
"launcher.resources.hint.local": "로컬 모드는 서버의 리소스 API를 호출하지 않습니다. 리소스 버전은 여전히 현재 클라이언트와 일치해야 합니다.",
"launcher.resources.hint.server": "자체 호스팅과 리버스 프록시는 클라이언트에서 같은 출처로 취급되며, 주소는 서버가 반환합니다.",
"launcher.resources.verify": "리소스 출처 확인 ↗",
"launcher.resources.missing": "반환되지 않음",
"launcher.resources.policy_official": "클라이언트가 버전이 고정된 공식 주소를 사용합니다",
"launcher.resources.policy_server": "서버가 리소스 주소를 제공합니다",
"launcher.save": "연결 설정 저장",
"launcher.unsaved": "현재 설정이 아직 저장되지 않았습니다.",
"launcher.prepare.title": "패치 및 플러그인",
"launcher.prepare.note": "작업 전에 게임을 종료하세요. 패치는 내장된 Intro 주소만 변경하며 %[1]s 백업을 남깁니다. 플러그인을 설치하기 전에 BepInEx를 먼저 직접 설치하세요.",
"launcher.prepare.patch": "클라이언트 패치 적용",
"launcher.prepare.install": "플러그인 설치 / 업데이트",
"launcher.status.label": "클라이언트 상태",
"launcher.status.title": "현재 상태",
"launcher.status.executable": "게임 실행 파일",
"launcher.status.assets": "리소스 파일",
"launcher.status.config": "연결 구성",
"launcher.status.waiting": "확인 대기 중",
"launcher.status.ready": "준비됨",
"launcher.status.not_found": "찾을 수 없음",
"launcher.status.installed": "설치됨",
"launcher.status.manual_install": "직접 설치 필요",
"launcher.status.written": "기록됨",
"launcher.status.not_written": "기록되지 않음",
"launcher.status.unsaved": "저장되지 않은 변경 사항",
"launcher.status.files_ready": "게임 파일 준비됨",
"launcher.status.files_attention": "게임 파일 확인 필요",
"launcher.status.foot": "상태는 로컬 파일 확인 결과이며 서버가 온라인임을 의미하지 않습니다.",
"launcher.status.client_version": "클라이언트 버전: ",
"launcher.status.game_version": "게임 버전: ",
"launcher.status.log_path": "진단 로그: ",
"launcher.status.refresh": "다시 확인 ↻",
"launcher.log.title": "최근 작업",
"launcher.log.idle": "작업 대기 중",
"launcher.log.idle_hint": "게임 폴더를 선택하면 확인을 시작할 수 있습니다.",
"launcher.log.history": "작업 기록 보기",
"launcher.operation.completed": "작업을 완료했습니다",
"launcher.operation.failed": "작업을 완료하지 못했습니다",
"launcher.operation.wait": "잠시 기다려 주세요…",
"launcher.footer.local_only": "설정은 사용자의 컴퓨터에만 저장됩니다",
"launcher.footer.no_secrets": "계정 자격 증명이나 서버 운영자 키는 저장하지 않습니다",
"launcher.quit.title": "도구가 종료되었습니다",
"launcher.quit.hint": "이제 이 페이지를 닫아도 됩니다.",
"launcher.steps.label": "설정 진행 상황",
"launcher.steps.directory": "폴더 선택",
"launcher.steps.server": "서버 설정",
"launcher.editor.title": "설정 변경",
"launcher.editor.close": "설정 닫기",
"launcher.editor.note": "변경한 후 런처에서 연결 설정을 저장하세요.",
"launcher.editor.done": "변경 완료",
"launcher.editor.directory": "게임 폴더 변경",
"launcher.editor.server": "서버 주소 변경",
"launcher.dialog.game_directory": "Brown Dust II 설치 폴더 선택",
"launcher.dialog.resource_directory": "ServerData와 GameData가 있는 CDN 폴더 선택",
"launcher.error.bridge": "클라이언트 네이티브 인터페이스가 아직 준비되지 않았습니다",
"launcher.error.directory_required": "먼저 게임 설치 폴더를 선택하세요",
"launcher.error.origin_invalid": "전체 서버 주소를 입력하세요. 예: %[1]s",
"launcher.error.origin_shape": "서버 주소에는 http(s) 주소와 포트만 입력하고 경로, 쿼리 매개변수, 계정 정보는 포함하지 마세요",
"launcher.error.origin_https": "인터넷 또는 LAN 서버는 HTTPS를 사용해야 합니다. HTTP는 로컬 루프백 주소에서만 사용할 수 있습니다",
"launcher.error.resources_required": "ServerData와 GameData가 있는 로컬 CDN 폴더를 선택하세요",
"launcher.error.proxy_invalid": "HTTP 프록시 주소를 입력하세요. 예: %[1]s (호스트와 포트만 지원)",
"common.list_separator": ", ",
"backend.update_checked": "업데이트 확인을 완료했습니다",
"backend.launcher_restarting": "업데이트를 마치기 위해 런처를 다시 시작합니다",
"backend.update_unavailable": "업데이트 서비스를 사용할 수 없습니다",
"backend.update_busy": "다른 업데이트 작업이 진행 중입니다",
"backend.no_launcher_update": "사용 가능한 런처 업데이트가 없습니다",
"backend.launcher_update_incomplete": "런처 업데이트 다운로드가 아직 끝나지 않았습니다",
"backend.launcher_updating": "런처를 업데이트하는 중입니다. 완료된 후 게임을 실행하세요",
"backend.game_running_plugins": "게임이 실행 중입니다. 플러그인은 게임이 종료된 후 업데이트됩니다",
"backend.selection_cancelled": "선택을 취소했습니다",
"backend.game_found": "게임 클라이언트를 찾았습니다",
"backend.local_resources_found": "로컬 리소스 폴더를 찾았습니다",
"backend.directory_valid": "유효한 게임 폴더입니다",
"backend.official_cdn": "클라이언트가 버전이 고정된 공식 CDN을 사용합니다",
"backend.local_verified": "로컬 리소스를 확인했습니다",
"backend.server_policy_verified": "서버 리소스 정책을 확인했습니다",
"backend.settings_saved": "연결 설정을 저장했습니다",
"backend.patched": "클라이언트 진입점을 패치했습니다. 원본 파일 백업은 유지됩니다",
"backend.patch_current": "클라이언트 패치가 이미 적용되어 있어 리소스 파일을 다시 쓰지 않았습니다",
"backend.plugins_installed": "BD2 클라이언트 플러그인을 설치하거나 업데이트했습니다",
"backend.plugins_current": "BD2 클라이언트 플러그인이 이미 최신 버전이어서 DLL을 다시 쓰지 않았습니다",
"backend.game_started": "Brown Dust II를 실행했습니다",
"backend.game_running": "Brown Dust II가 이미 실행 중입니다",
"backend.tool_exited": "클라이언트 도구가 종료되었습니다",
"backend.plugins_rejected": "서버 %[1]s에서 다음 플러그인을 더 이상 허용하지 않습니다: %[2]s. 먼저 런처에서 플러그인을 업데이트하세요",
"backend.plugin_requirement": "%[1]s %[2]s (%[3]s 필요)",
"update.game.available": "필수 게임 업데이트 %[1]s",
"update.game.exit_hint": "모든 게임을 종료하세요. 다음 실행 전에 게임과 리소스를 다운로드하고 검증합니다.",
"update.game.update": "게임 업데이트",
"update.busy": "업데이트 중…",
"update.downloading": "다운로드 중 %[1]s%%",
"update.installing": "업데이트 설치 중",
"update.restarting": "곧 런처가 다시 시작됩니다",
"update.released": "%[1]s 출시",
"update.size": "다운로드 크기 %[1]s",
"update.failed": "업데이트 확인 실패",
"update.retry": "다시 시도",
"update.launcher.available": "런처 새 버전 %[1]s",
"update.launcher.restart": "다시 시작하여 업데이트",
"update.launcher.download": "업데이트 다운로드",
"update.launcher.switched": "런처를 %[1]s 버전에서 %[2]s 버전으로 업데이트했습니다",
"update.launcher.switch_failed": "%[1]s 버전으로 업데이트하지 못했습니다: %[2]s. 현재 %[3]s 버전을 계속 사용합니다",
"update.plugins.available": "플러그인 새 버전 %[1]s",
"update.plugins.update": "플러그인 업데이트",
"update.plugins.ready": "플러그인 업데이트 준비 완료",
"update.plugins.ready_hint": "실행 중인 게임이 종료되면 자동으로 적용됩니다.",
"update.plugins.updated": "플러그인을 %[1]s 버전으로 업데이트했습니다",
"update.plugins.updated_waiting": "플러그인을 %[1]s 버전으로 업데이트했습니다. 실행 중인 게임에는 종료 후 적용됩니다",
"update.plugins.applied_after_exit": "게임이 종료되어 플러그인 업데이트를 적용했습니다",
"update.checking": "업데이트 확인 중",
"update.preparing": "게임 시작 준비 중",
"backend.server_maintenance": "서버 업데이트 중입니다. 완료 후 다시 시도해 주세요",
"backend.game_mismatch": "서버 게임 버전 %[1]s과 클라이언트 게임 버전 %[2]s이 일치하지 않습니다",
"launcher.brand.title": "BD2 런처",
"launcher.brand.subtitle": "게임 런처",
"launcher.directory.step": "01 / 게임 폴더",
"launcher.server.step": "02 / 서버 연결",
"launcher.desk.step": "03 / 런처",
"launcher.status.tagline": "로컬 상태",
"launcher.resources.official.code": "공식",
"launcher.resources.local.code": "로컬",
"launcher.resources.server.code": "서버"
}
+190
View File
@@ -0,0 +1,190 @@
{
"launcher.title": "BD2 启动器",
"launcher.top_note": "BD2 启动器 · 配置保存在本机",
"launcher.language": "语言",
"launcher.window.controls": "窗口控制",
"launcher.window.minimize": "最小化",
"launcher.window.maximize": "最大化或还原",
"launcher.window.close": "关闭",
"launcher.browse": "浏览",
"launcher.directory.heading": "先从游戏目录\n开始。",
"launcher.directory.lead": "选择已安装的游戏文件夹。\n我们会检查游戏程序和资源文件,再继续设置连接。",
"launcher.directory.label": "BrownDust II · 客户端配置",
"launcher.directory.title": "选择游戏目录",
"launcher.directory.description": "请选择包含 %[1]s 的文件夹。",
"launcher.directory.description_mac": "请选择 %[1]s 或它所在的文件夹。",
"launcher.directory.field": "游戏安装目录",
"launcher.directory.placeholder": "例如 E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "例如 /Applications/BrownDust II.app",
"launcher.directory.hint": "可直接填写路径,也可以浏览目录。",
"launcher.directory.inspect": "检查目录",
"launcher.directory.next": "继续设置服务器",
"launcher.directory.note": "此步骤只检查文件,不会修改游戏资源。",
"launcher.directory.found": "游戏程序和资源文件已检测到。",
"launcher.directory.incomplete": "检查已完成,请在启动器查看缺失项。",
"launcher.directory.changed": "目录已修改,请重新检查。",
"launcher.server.heading": "接下来,\n设置服务器。",
"launcher.server.lead": "填写要连接的服务端地址。\n进入启动器后,你可以选择资源来源、应用补丁和安装插件。",
"launcher.server.label": "目录已选择 · 之后仍可修改",
"launcher.server.title": "服务器地址",
"launcher.server.description": "填写完整地址,可以包含端口。",
"launcher.server.field": "地址与端口",
"launcher.server.hint": "例如 %[1]s\n不要添加 %[2]s 或其他路径。真实连接地址由 LI 插件读取。",
"launcher.server.next": "进入启动器",
"launcher.server.back": "← 返回目录设置",
"launcher.desk.subtitle": "管理连接设置,完成游戏启动前的准备。",
"launcher.launch": "启动游戏",
"launcher.connection.title": "连接设置",
"launcher.connection.editable": "随时可以修改",
"launcher.connection.directory": "游戏目录",
"launcher.connection.not_selected": "尚未选择",
"launcher.connection.change_directory": "修改目录 ↗",
"launcher.connection.not_entered": "尚未填写",
"launcher.connection.change_server": "修改地址 ↗",
"launcher.connection.proxy": "代理",
"launcher.connection.set_proxy": "设置代理 ↗",
"launcher.proxy.title": "设置代理",
"launcher.proxy.mode": "连接方式",
"launcher.proxy.direct": "直接连接",
"launcher.proxy.manual": "手动 HTTP 代理",
"launcher.proxy.manual_missing": "手动 HTTP 代理 · 尚未填写",
"launcher.proxy.address": "HTTP 代理地址",
"launcher.proxy.address_hint": "填写 http://主机:端口,不支持账号、路径或查询参数。",
"launcher.proxy.apply_hint": "保存后在下次启动游戏时生效。本机地址 localhost、127.0.0.1 和 ::1 始终直接连接。",
"launcher.proxy.https_hint": "HTTP 代理通过 CONNECT 支持游戏的 HTTPS 连接,仍会验证证书。浏览器使用自身的代理设置。",
"launcher.resources.title": "资源来源",
"launcher.resources.group": "CDN 类型",
"launcher.resources.official.name": "官方 CDN",
"launcher.resources.official.description": "从官方节点下载资源,不占用服主的大文件流量。",
"launcher.resources.local.name": "本机已下载资源",
"launcher.resources.local.description": "直接读取电脑上的 ServerData 和 GameData,不再下载相同文件。",
"launcher.resources.server.name": "服主资源",
"launcher.resources.server.description": "由服务器提供资源地址;服主可自建 CDN,也可以反代官方 CDN。",
"launcher.resources.local_root": "本机 CDN 根目录",
"launcher.resources.local_placeholder": "例如 E:\\bd2\\dl",
"launcher.resources.local_note": "所选目录内必须同时包含 %[1]s 和 %[2]s。",
"launcher.resources.hint.official": "官方模式由客户端直连版本锁定的官方 CDN。",
"launcher.resources.hint.local": "本机模式不会请求服务器资源接口;资源版本仍必须与当前客户端一致。",
"launcher.resources.hint.server": "服主自建与反代在客户端中是同一种来源,地址统一由服务器返回。",
"launcher.resources.verify": "验证资源来源 ↗",
"launcher.resources.missing": "未返回",
"launcher.resources.policy_official": "客户端使用版本锁定的官方地址",
"launcher.resources.policy_server": "由服务器提供资源地址",
"launcher.save": "保存连接设置",
"launcher.unsaved": "当前设置尚未保存。",
"launcher.prepare.title": "补丁与插件",
"launcher.prepare.note": "操作前请先关闭游戏。补丁只修改内置 Intro 地址,并保留 %[1]s 备份。安装插件前,请先手动安装 BepInEx。",
"launcher.prepare.patch": "应用客户端补丁",
"launcher.prepare.install": "安装 / 更新插件",
"launcher.status.label": "客户端状态",
"launcher.status.title": "当前状态",
"launcher.status.executable": "游戏程序",
"launcher.status.assets": "资源文件",
"launcher.status.config": "连接配置",
"launcher.status.waiting": "等待检查",
"launcher.status.ready": "已就绪",
"launcher.status.not_found": "未检测到",
"launcher.status.installed": "已安装",
"launcher.status.manual_install": "需手动安装",
"launcher.status.written": "已写入",
"launcher.status.not_written": "尚未写入",
"launcher.status.unsaved": "有未保存修改",
"launcher.status.files_ready": "游戏文件已就绪",
"launcher.status.files_attention": "游戏文件待检查",
"launcher.status.foot": "状态来自本机文件检查,不代表服务器在线。",
"launcher.status.client_version": "客户端版本:",
"launcher.status.game_version": "游戏版本:",
"launcher.status.log_path": "诊断日志:",
"launcher.status.refresh": "重新检查 ↻",
"launcher.log.title": "最近操作",
"launcher.log.idle": "等待操作",
"launcher.log.idle_hint": "选择游戏目录后即可开始检查。",
"launcher.log.history": "查看操作记录",
"launcher.operation.completed": "操作已完成",
"launcher.operation.failed": "操作未完成",
"launcher.operation.wait": "请稍候…",
"launcher.footer.local_only": "配置仅保存在你的电脑上",
"launcher.footer.no_secrets": "不会保存账号凭据或服主密钥",
"launcher.quit.title": "工具已退出",
"launcher.quit.hint": "现在可以关闭这个页面。",
"launcher.steps.label": "设置进度",
"launcher.steps.directory": "选择目录",
"launcher.steps.server": "设置服务器",
"launcher.editor.title": "修改设置",
"launcher.editor.close": "关闭设置",
"launcher.editor.note": "修改后请在启动器保存连接设置。",
"launcher.editor.done": "完成修改",
"launcher.editor.directory": "修改游戏目录",
"launcher.editor.server": "修改服务器地址",
"launcher.dialog.game_directory": "选择 Brown Dust II 安装目录",
"launcher.dialog.resource_directory": "选择包含 ServerData 和 GameData 的 CDN 目录",
"launcher.error.bridge": "客户端原生接口尚未就绪",
"launcher.error.directory_required": "请先选择游戏安装目录",
"launcher.error.origin_invalid": "请输入完整服务器地址,例如 %[1]s",
"launcher.error.origin_shape": "服务器地址仅填写 http(s) 地址与端口,不要包含路径、查询参数或账号信息",
"launcher.error.origin_https": "公网或局域网服务器必须使用 HTTPS;只有本机 loopback 可以使用 HTTP",
"launcher.error.resources_required": "请选择包含 ServerData 和 GameData 的本机 CDN 目录",
"launcher.error.proxy_invalid": "请输入 HTTP 代理地址,例如 %[1]s;仅支持主机和端口",
"common.list_separator": "、",
"backend.update_checked": "已检查更新",
"backend.launcher_restarting": "启动器正在重启以完成更新",
"backend.update_unavailable": "更新服务不可用",
"backend.update_busy": "另一项更新操作正在进行",
"backend.no_launcher_update": "没有可用的启动器更新",
"backend.launcher_update_incomplete": "启动器更新尚未下载完成",
"backend.launcher_updating": "启动器正在更新,请在更新完成后再启动游戏",
"backend.game_running_plugins": "游戏正在运行,插件将在游戏退出后更新",
"backend.selection_cancelled": "已取消选择",
"backend.game_found": "已找到游戏客户端",
"backend.local_resources_found": "已找到本机资源目录",
"backend.directory_valid": "游戏目录有效",
"backend.official_cdn": "将由客户端直接连接版本锁定的官方 CDN",
"backend.local_verified": "本机资源已验证",
"backend.server_policy_verified": "服务器资源策略已确认",
"backend.settings_saved": "连接设置已保存",
"backend.patched": "客户端入口补丁完成;原文件备份已保留",
"backend.patch_current": "客户端补丁已经完成,未再次改写资源文件",
"backend.plugins_installed": "BD2 客户端插件已安装或更新",
"backend.plugins_current": "BD2 客户端插件已经是最新版本,未再次改写 DLL",
"backend.game_started": "Brown Dust II 已启动",
"backend.game_running": "Brown Dust II 已经在运行",
"backend.tool_exited": "客户端工具已退出",
"backend.plugins_rejected": "服务器 %[1]s 已不再接受以下插件:%[2]s。请先在启动器中更新插件",
"backend.plugin_requirement": "%[1]s %[2]s(需要 %[3]s)",
"update.game.available": "游戏必须更新至 %[1]s",
"update.game.exit_hint": "请关闭所有游戏进程。启动器会在下次启动前下载并校验游戏和资源。",
"update.game.update": "更新游戏",
"update.busy": "正在更新…",
"update.downloading": "正在下载 %[1]s%%",
"update.installing": "正在安装更新",
"update.restarting": "启动器即将重启",
"update.released": "发布于 %[1]s",
"update.size": "下载大小 %[1]s",
"update.failed": "检查更新失败",
"update.retry": "重试",
"update.launcher.available": "启动器新版本 %[1]s",
"update.launcher.restart": "重启并更新",
"update.launcher.download": "下载更新",
"update.launcher.switched": "启动器已从 %[1]s 更新到 %[2]s",
"update.launcher.switch_failed": "更新到 %[1]s 失败:%[2]s。仍在使用 %[3]s",
"update.plugins.available": "插件新版本 %[1]s",
"update.plugins.update": "更新插件",
"update.plugins.ready": "插件更新已就绪",
"update.plugins.ready_hint": "正在运行的游戏退出后自动生效。",
"update.plugins.updated": "插件已更新到 %[1]s",
"update.plugins.updated_waiting": "插件已更新到 %[1]s;正在运行的游戏会在退出后使用新版本",
"update.plugins.applied_after_exit": "游戏已退出,插件更新已生效",
"update.checking": "正在检查更新",
"update.preparing": "正在准备启动游戏",
"backend.server_maintenance": "服务器正在更新,请稍后再试",
"backend.game_mismatch": "服务器游戏版本 %[1]s 与客户端游戏版本 %[2]s 不一致",
"launcher.brand.title": "BD2 启动器",
"launcher.brand.subtitle": "游戏启动器",
"launcher.directory.step": "01 / 游戏目录",
"launcher.server.step": "02 / 服务器连接",
"launcher.desk.step": "03 / 启动器",
"launcher.status.tagline": "本机状态",
"launcher.resources.official.code": "官方",
"launcher.resources.local.code": "本地",
"launcher.resources.server.code": "服务器"
}
+190
View File
@@ -0,0 +1,190 @@
{
"launcher.title": "BD2 啟動器",
"launcher.top_note": "BD2 啟動器 · 設定儲存在本機",
"launcher.language": "語言",
"launcher.window.controls": "視窗控制項",
"launcher.window.minimize": "最小化",
"launcher.window.maximize": "最大化或還原",
"launcher.window.close": "關閉",
"launcher.browse": "瀏覽",
"launcher.directory.heading": "先從遊戲目錄\n開始。",
"launcher.directory.lead": "選擇已安裝的遊戲資料夾。\n我們會先檢查遊戲程式和資源檔案,再繼續設定連線。",
"launcher.directory.label": "BrownDust II · 用戶端設定",
"launcher.directory.title": "選擇遊戲目錄",
"launcher.directory.description": "請選擇包含 %[1]s 的資料夾。",
"launcher.directory.description_mac": "請選擇 %[1]s 或其所在的資料夾。",
"launcher.directory.field": "遊戲安裝目錄",
"launcher.directory.placeholder": "例如 E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "例如 /Applications/BrownDust II.app",
"launcher.directory.hint": "可直接輸入路徑,也可以瀏覽資料夾。",
"launcher.directory.inspect": "檢查目錄",
"launcher.directory.next": "繼續設定伺服器",
"launcher.directory.note": "此步驟只會檢查檔案,不會修改遊戲資源。",
"launcher.directory.found": "已偵測到遊戲程式和資源檔案。",
"launcher.directory.incomplete": "檢查完成,請在啟動器中查看缺少的項目。",
"launcher.directory.changed": "目錄已變更,請重新檢查。",
"launcher.server.heading": "接下來,\n設定伺服器。",
"launcher.server.lead": "輸入要連線的伺服器位址。\n進入啟動器後,即可選擇資源來源、套用修補程式並安裝插件。",
"launcher.server.label": "已選擇目錄 · 之後仍可修改",
"launcher.server.title": "伺服器位址",
"launcher.server.description": "請輸入完整位址,可包含連接埠。",
"launcher.server.field": "位址與連接埠",
"launcher.server.hint": "例如 %[1]s\n請勿加上 %[2]s 或其他路徑。實際連線位址由 LI 插件讀取。",
"launcher.server.next": "進入啟動器",
"launcher.server.back": "← 返回目錄設定",
"launcher.desk.subtitle": "管理連線設定,完成啟動遊戲前的準備。",
"launcher.launch": "啟動遊戲",
"launcher.connection.title": "連線設定",
"launcher.connection.editable": "隨時可以修改",
"launcher.connection.directory": "遊戲目錄",
"launcher.connection.not_selected": "尚未選擇",
"launcher.connection.change_directory": "修改目錄 ↗",
"launcher.connection.not_entered": "尚未輸入",
"launcher.connection.change_server": "修改位址 ↗",
"launcher.connection.proxy": "代理",
"launcher.connection.set_proxy": "設定代理 ↗",
"launcher.proxy.title": "設定代理",
"launcher.proxy.mode": "連線方式",
"launcher.proxy.direct": "直接連線",
"launcher.proxy.manual": "手動 HTTP 代理",
"launcher.proxy.manual_missing": "手動 HTTP 代理 · 尚未輸入",
"launcher.proxy.address": "HTTP 代理位址",
"launcher.proxy.address_hint": "請輸入 http://主機:連接埠,不支援帳號、路徑或查詢參數。",
"launcher.proxy.apply_hint": "儲存後將於下次啟動遊戲時生效。本機位址 localhost、127.0.0.1 和 ::1 一律直接連線。",
"launcher.proxy.https_hint": "HTTP 代理透過 CONNECT 支援遊戲的 HTTPS 連線,且仍會驗證憑證。瀏覽器會使用自己的代理設定。",
"launcher.resources.title": "資源來源",
"launcher.resources.group": "CDN 類型",
"launcher.resources.official.name": "官方 CDN",
"launcher.resources.official.description": "從官方節點下載資源,不會占用伺服器管理者的大型檔案流量。",
"launcher.resources.local.name": "本機已下載的資源",
"launcher.resources.local.description": "直接讀取電腦上的 ServerData 和 GameData,不再重複下載相同檔案。",
"launcher.resources.server.name": "伺服器提供的資源",
"launcher.resources.server.description": "由伺服器提供資源位址;管理者可自架 CDN,也可以反向代理官方 CDN。",
"launcher.resources.local_root": "本機 CDN 根目錄",
"launcher.resources.local_placeholder": "例如 E:\\bd2\\dl",
"launcher.resources.local_note": "所選目錄必須同時包含 %[1]s 和 %[2]s。",
"launcher.resources.hint.official": "官方模式由用戶端直接連線至版本鎖定的官方 CDN。",
"launcher.resources.hint.local": "本機模式不會呼叫伺服器的資源介面;資源版本仍必須與目前的用戶端一致。",
"launcher.resources.hint.server": "自架與反向代理對用戶端而言是同一種來源,位址一律由伺服器回傳。",
"launcher.resources.verify": "驗證資源來源 ↗",
"launcher.resources.missing": "未回傳",
"launcher.resources.policy_official": "用戶端使用版本鎖定的官方位址",
"launcher.resources.policy_server": "由伺服器提供資源位址",
"launcher.save": "儲存連線設定",
"launcher.unsaved": "目前的設定尚未儲存。",
"launcher.prepare.title": "修補程式與插件",
"launcher.prepare.note": "操作前請先關閉遊戲。修補程式只會修改內建的 Intro 位址,並保留 %[1]s 備份。安裝插件前,請先手動安裝 BepInEx。",
"launcher.prepare.patch": "套用用戶端修補程式",
"launcher.prepare.install": "安裝 / 更新插件",
"launcher.status.label": "用戶端狀態",
"launcher.status.title": "目前狀態",
"launcher.status.executable": "遊戲程式",
"launcher.status.assets": "資源檔案",
"launcher.status.config": "連線設定檔",
"launcher.status.waiting": "等待檢查",
"launcher.status.ready": "已就緒",
"launcher.status.not_found": "未偵測到",
"launcher.status.installed": "已安裝",
"launcher.status.manual_install": "需手動安裝",
"launcher.status.written": "已寫入",
"launcher.status.not_written": "尚未寫入",
"launcher.status.unsaved": "有未儲存的變更",
"launcher.status.files_ready": "遊戲檔案已就緒",
"launcher.status.files_attention": "遊戲檔案需要檢查",
"launcher.status.foot": "狀態來自本機檔案檢查,不代表伺服器在線上。",
"launcher.status.client_version": "用戶端版本:",
"launcher.status.game_version": "遊戲版本:",
"launcher.status.log_path": "診斷記錄:",
"launcher.status.refresh": "重新檢查 ↻",
"launcher.log.title": "最近操作",
"launcher.log.idle": "等待操作",
"launcher.log.idle_hint": "選擇遊戲目錄後即可開始檢查。",
"launcher.log.history": "檢視操作記錄",
"launcher.operation.completed": "操作已完成",
"launcher.operation.failed": "操作未完成",
"launcher.operation.wait": "請稍候…",
"launcher.footer.local_only": "設定只會儲存在你的電腦上",
"launcher.footer.no_secrets": "不會儲存帳號憑證或伺服器管理者金鑰",
"launcher.quit.title": "工具已結束",
"launcher.quit.hint": "現在可以關閉此頁面。",
"launcher.steps.label": "設定進度",
"launcher.steps.directory": "選擇目錄",
"launcher.steps.server": "設定伺服器",
"launcher.editor.title": "修改設定",
"launcher.editor.close": "關閉設定",
"launcher.editor.note": "修改後請在啟動器中儲存連線設定。",
"launcher.editor.done": "完成修改",
"launcher.editor.directory": "修改遊戲目錄",
"launcher.editor.server": "修改伺服器位址",
"launcher.dialog.game_directory": "選擇 Brown Dust II 安裝目錄",
"launcher.dialog.resource_directory": "選擇包含 ServerData 和 GameData 的 CDN 目錄",
"launcher.error.bridge": "用戶端原生介面尚未就緒",
"launcher.error.directory_required": "請先選擇遊戲安裝目錄",
"launcher.error.origin_invalid": "請輸入完整的伺服器位址,例如 %[1]s",
"launcher.error.origin_shape": "伺服器位址只能填寫 http(s) 位址與連接埠,請勿包含路徑、查詢參數或帳號資訊",
"launcher.error.origin_https": "公用網路或區域網路伺服器必須使用 HTTPS;只有本機 loopback 位址可以使用 HTTP",
"launcher.error.resources_required": "請選擇包含 ServerData 和 GameData 的本機 CDN 目錄",
"launcher.error.proxy_invalid": "請輸入 HTTP 代理位址,例如 %[1]s;僅支援主機和連接埠",
"common.list_separator": "、",
"backend.update_checked": "已檢查更新",
"backend.launcher_restarting": "啟動器正在重新啟動以完成更新",
"backend.update_unavailable": "更新服務無法使用",
"backend.update_busy": "另一項更新作業正在進行中",
"backend.no_launcher_update": "目前沒有可用的啟動器更新",
"backend.launcher_update_incomplete": "啟動器更新尚未下載完成",
"backend.launcher_updating": "啟動器正在更新,請在更新完成後再啟動遊戲",
"backend.game_running_plugins": "遊戲正在執行,插件將在遊戲結束後更新",
"backend.selection_cancelled": "已取消選擇",
"backend.game_found": "已找到遊戲用戶端",
"backend.local_resources_found": "已找到本機資源目錄",
"backend.directory_valid": "遊戲目錄有效",
"backend.official_cdn": "用戶端將直接連線至版本鎖定的官方 CDN",
"backend.local_verified": "本機資源已驗證",
"backend.server_policy_verified": "已確認伺服器資源策略",
"backend.settings_saved": "連線設定已儲存",
"backend.patched": "已修補用戶端進入點,並保留原始檔案備份",
"backend.patch_current": "用戶端已完成修補,未重新改寫資源檔案",
"backend.plugins_installed": "BD2 用戶端插件已安裝或更新",
"backend.plugins_current": "BD2 用戶端插件已是最新版本,未重新改寫 DLL",
"backend.game_started": "Brown Dust II 已啟動",
"backend.game_running": "Brown Dust II 已在執行中",
"backend.tool_exited": "用戶端工具已結束",
"backend.plugins_rejected": "伺服器 %[1]s 已不再接受下列插件:%[2]s。請先在啟動器中更新插件",
"backend.plugin_requirement": "%[1]s %[2]s(需要 %[3]s)",
"update.game.available": "遊戲必須更新至 %[1]s",
"update.game.exit_hint": "請關閉所有遊戲程序。啟動器會在下次啟動前下載並驗證遊戲和資源。",
"update.game.update": "更新遊戲",
"update.busy": "正在更新…",
"update.downloading": "正在下載 %[1]s%%",
"update.installing": "正在安裝更新",
"update.restarting": "啟動器即將重新啟動",
"update.released": "發布於 %[1]s",
"update.size": "下載大小 %[1]s",
"update.failed": "檢查更新失敗",
"update.retry": "重試",
"update.launcher.available": "啟動器新版本 %[1]s",
"update.launcher.restart": "重新啟動並更新",
"update.launcher.download": "下載更新",
"update.launcher.switched": "啟動器已從 %[1]s 更新至 %[2]s",
"update.launcher.switch_failed": "更新至 %[1]s 失敗:%[2]s。仍在使用 %[3]s",
"update.plugins.available": "插件新版本 %[1]s",
"update.plugins.update": "更新插件",
"update.plugins.ready": "插件更新已就緒",
"update.plugins.ready_hint": "將在執行中的遊戲結束後自動生效。",
"update.plugins.updated": "插件已更新至 %[1]s",
"update.plugins.updated_waiting": "插件已更新至 %[1]s;執行中的遊戲會在結束後套用新版本",
"update.plugins.applied_after_exit": "遊戲已結束,插件更新已套用",
"update.checking": "正在檢查更新",
"update.preparing": "正在準備啟動遊戲",
"backend.server_maintenance": "伺服器正在更新,請稍後再試",
"backend.game_mismatch": "伺服器遊戲版本 %[1]s 與用戶端遊戲版本 %[2]s 不一致",
"launcher.brand.title": "BD2 啟動器",
"launcher.brand.subtitle": "遊戲啟動器",
"launcher.directory.step": "01 / 遊戲目錄",
"launcher.server.step": "02 / 伺服器連線",
"launcher.desk.step": "03 / 啟動器",
"launcher.status.tagline": "本機狀態",
"launcher.resources.official.code": "官方",
"launcher.resources.local.code": "本機",
"launcher.resources.server.code": "伺服器"
}
+15
View File
@@ -6,6 +6,7 @@ import (
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"io"
"os"
"path/filepath"
@@ -201,6 +202,20 @@ func extractArchive(path, root string, game bool, digest string) error {
ready = false
break
}
if !info.IsDir() {
installed, err := os.Open(entry.target)
if err != nil {
ready = false
break
}
hash := crc32.NewIEEE()
_, readErr := io.Copy(hash, installed)
closeErr := installed.Close()
if readErr != nil || closeErr != nil || hash.Sum32() != entry.file.CRC32 {
ready = false
break
}
}
}
if ready {
return nil
+16 -3
View File
@@ -9,6 +9,7 @@ import (
"strings"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/release"
"bd2server/internal/common/versionconfig"
)
@@ -17,6 +18,7 @@ type Options struct {
GameDir, ResourceDir, ServerOrigin string
Workers int
ProbeOnly bool
Pinned *release.GameResources
}
type Installation struct {
@@ -37,9 +39,20 @@ func Client(ctx context.Context, options Options, out io.Writer) (Installation,
if manifestPath == "" {
manifestPath = filepath.Join(packageDir, "client-download.json")
}
m, err := commonconfig.Load(manifestPath, manifest{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true, AllowBOM: true, RejectNull: true})
if err != nil {
return result, fmt.Errorf("download manifest: %w", err)
var m manifest
if options.Pinned != nil {
m = *options.Pinned
if err := m.Validate(); err != nil {
return result, err
}
if len(m.ResourceFiles) == 0 {
return result, errors.New("signed game update requires a complete resource inventory")
}
} else {
m, err = commonconfig.Load(manifestPath, manifest{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true, AllowBOM: true, RejectNull: true})
if err != nil {
return result, fmt.Errorf("download manifest: %w", err)
}
}
if !timestamp.MatchString(m.GameDataVersion) || !timestamp.MatchString(m.BundleVersion) || !gameVersionPattern.MatchString(m.GameVersion) || m.Platform != "StandaloneWindows64" || !strings.HasPrefix(m.GamePath, "/Build/") {
return result, errors.New("invalid Windows game download manifest")
+3 -17
View File
@@ -9,25 +9,11 @@ import (
"path/filepath"
"regexp"
"strings"
"bd2server/internal/common/release"
)
type manifest struct {
GameVersion string `json:"game_version"`
GameDataVersion string `json:"game_data_version"`
BundleVersion string `json:"bundle_version"`
Platform string `json:"platform"`
ServerOrigin string `json:"server_origin"`
BuildOrigins []string `json:"build_origins"`
ResourceOrigins []string `json:"resource_origins"`
GamePath string `json:"game_path"`
GameSHA256 string `json:"game_sha256"`
GameBytes int64 `json:"game_bytes"`
DataSHA256 string `json:"data_sha256"`
DataBytes int64 `json:"data_bytes"`
CatalogSHA256 string `json:"catalog_sha256"`
CatalogBytes int64 `json:"catalog_bytes"`
CatalogHash string `json:"catalog_hash"`
}
type manifest = release.GameResources
var timestamp = regexp.MustCompile(`^[0-9]{14}$`)
var sha256Pattern = regexp.MustCompile(`^[a-f0-9]{64}$`)
@@ -168,3 +168,42 @@ func TestUnsafeArchiveDoesNotAlterAnExistingInstallation(t *testing.T) {
t.Fatal("archive escaped game directory")
}
}
func TestOfficialGameRepairDoesNotTrustMarkerAndUnchangedFileSize(t *testing.T) {
root := t.TempDir()
path := filepath.Join(root, "game.zip")
out, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
archive := zip.NewWriter(out)
for _, name := range requiredGameFiles {
entry, err := archive.Create(name)
if err != nil {
t.Fatal(err)
}
if _, err := io.WriteString(entry, "official"); err != nil {
t.Fatal(err)
}
}
if err := archive.Close(); err != nil {
t.Fatal(err)
}
if err := out.Close(); err != nil {
t.Fatal(err)
}
game := filepath.Join(root, "game")
if err := extractArchive(path, game, true, "archive-digest"); err != nil {
t.Fatal(err)
}
target := filepath.Join(game, "UnityPlayer.dll")
if err := os.WriteFile(target, []byte("tampered"), 0600); err != nil {
t.Fatal(err)
}
if err := extractArchive(path, game, true, "archive-digest"); err != nil {
t.Fatal(err)
}
if actual, err := os.ReadFile(target); err != nil || string(actual) != "official" {
t.Fatalf("same-size corruption survived repair: %q, %v", actual, err)
}
}
+41 -4
View File
@@ -13,15 +13,38 @@ import (
"strings"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/release"
"bd2server/internal/common/resourcecatalog"
)
func (d *downloader) resources(ctx context.Context, root string, m manifest, serverPath, dataPath string, serverOrigins, dataOrigins []string, workers int) error {
pins := make(map[string]release.ResourceFile, len(m.ResourceFiles))
usedPins := make(map[string]bool, len(m.ResourceFiles))
for _, pin := range m.ResourceFiles {
pins[pin.Path] = pin
}
receive := func(files []file, origins []string, workers int) error {
if len(pins) != 0 {
for i := range files {
relative, err := filepath.Rel(root, files[i].target)
if err != nil {
return err
}
pin, ok := pins[filepath.ToSlash(relative)]
if !ok {
return fmt.Errorf("signed resource inventory is missing %s", relative)
}
files[i].digest, files[i].size = pin.SHA256, pin.Size
usedPins[pin.Path] = true
}
}
return d.receiveAll(ctx, files, origins, workers)
}
serverDir := filepath.Join(root, "ServerData", m.Platform, "HD", m.BundleVersion)
dataDir := filepath.Join(root, "GameData", m.GameDataVersion)
catalog := filepath.Join(serverDir, "catalog_alpha.json")
hashPath := filepath.Join(serverDir, "catalog_alpha.hash")
if err := d.receiveAll(ctx, []file{{remote: serverPath + "/catalog_alpha.json", target: catalog, digest: m.CatalogSHA256, size: m.CatalogBytes}, {remote: serverPath + "/catalog_alpha.hash", target: hashPath}}, serverOrigins, 2); err != nil {
if err := receive([]file{{remote: serverPath + "/catalog_alpha.json", target: catalog, digest: m.CatalogSHA256, size: m.CatalogBytes}, {remote: serverPath + "/catalog_alpha.hash", target: hashPath}}, serverOrigins, 2); err != nil {
return err
}
hash, err := os.ReadFile(hashPath)
@@ -29,7 +52,7 @@ func (d *downloader) resources(ctx context.Context, root string, m manifest, ser
return err
}
actualHash := strings.TrimSpace(string(hash))
if !regexp.MustCompile(`^[a-fA-F0-9]{32}$`).MatchString(actualHash) || (m.CatalogHash != "" && actualHash != m.CatalogHash) {
if !regexp.MustCompile(`^[a-fA-F0-9]{32}$`).MatchString(actualHash) || (m.CatalogHash != "" && !strings.EqualFold(actualHash, m.CatalogHash)) {
return errors.New("ServerData catalog hash does not match the selected version")
}
raw, err := os.ReadFile(catalog)
@@ -53,7 +76,7 @@ func (d *downloader) resources(ctx context.Context, root string, m manifest, ser
if err != nil {
return err
}
if err := d.receiveAll(ctx, []file{{remote: dataPath + "/design.version", target: filepath.Join(dataDir, "design.version")}, {remote: dataPath + "/release/common-dbdata.info", target: filepath.Join(dataDir, "release", "common-dbdata.info")}, {remote: dataPath + "/release/common-dbdata.bin", target: filepath.Join(dataDir, "release", "common-dbdata.bin"), digest: m.DataSHA256, size: m.DataBytes}}, dataOrigins, 3); err != nil {
if err := receive([]file{{remote: dataPath + "/design.version", target: filepath.Join(dataDir, "design.version")}, {remote: dataPath + "/release/common-dbdata.info", target: filepath.Join(dataDir, "release", "common-dbdata.info")}, {remote: dataPath + "/release/common-dbdata.bin", target: filepath.Join(dataDir, "release", "common-dbdata.bin"), digest: m.DataSHA256, size: m.DataBytes}}, dataOrigins, 3); err != nil {
return err
}
var design struct {
@@ -96,7 +119,21 @@ func (d *downloader) resources(ctx context.Context, root string, m manifest, ser
}
files = append(files, file{remote: serverPath + "/" + escapedPath(path), target: target, bundle: true})
}
if err := d.receiveAll(ctx, files, serverOrigins, workers); err != nil {
if err := receive(files, serverOrigins, workers); err != nil {
return err
}
var additional []file
for _, pin := range m.ResourceFiles {
if usedPins[pin.Path] {
continue
}
target, err := safeTarget(root, pin.Path)
if err != nil {
return err
}
additional = append(additional, file{remote: "/" + escapedPath(pin.Path), target: target, digest: pin.SHA256, size: pin.Size})
}
if err := receive(additional, serverOrigins, workers); err != nil {
return err
}
var total int64
+3 -1
View File
@@ -13,6 +13,8 @@ import (
"path/filepath"
"sort"
"strings"
commonconfig "bd2server/internal/common/config"
)
type buildManifest struct {
@@ -260,5 +262,5 @@ func saveBuildJSON(path string, raw []byte) error {
if err := temporary.Close(); err != nil {
return err
}
return replaceFile(temporary.Name(), path)
return commonconfig.ReplaceFile(temporary.Name(), path)
}
+240 -80
View File
@@ -2,18 +2,25 @@ package plugin
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path"
"path/filepath"
"slices"
"strings"
"sync"
clientlayout "bd2server/internal/client/layout"
commonconfig "bd2server/internal/common/config"
)
const (
BepInExReleasesURL = "https://github.com/BepInEx/BepInEx/releases"
// managedFile records which files in BepInEx/plugins this launcher owns,
// so a later set can remove a dropped plugin without touching others.
managedFile = ".bd2-managed.json"
)
type Spec struct {
@@ -28,18 +35,28 @@ var (
GameNames = Spec{fileName: "BD2.GameNames.dll"}
)
// Shipped lists every plugin the launcher installs, including the shared
// runtime the others depend on.
var Shipped = []Spec{LocalIdentity, LoginUI, CashShop, FChat, GameNames}
func (s Spec) FileName() string { return s.fileName }
func (s Spec) validate() error {
if s.fileName == "" || filepath.Base(s.fileName) != s.fileName || filepath.Ext(s.fileName) != ".dll" {
if s.fileName == "" || filepath.Base(s.fileName) != s.fileName || path.Base(s.fileName) != s.fileName || strings.ContainsAny(s.fileName, `\:`) || filepath.Ext(s.fileName) != ".dll" {
return errors.New("clientplugin: invalid plugin specification")
}
return nil
}
type Result struct {
Destination string
Changed bool
Destination string `json:"destination"`
Changed bool `json:"changed"`
}
type SetResult struct {
Changed bool `json:"changed"`
Files []Result `json:"files"`
Removed []string `json:"removed,omitempty"`
}
func ResolvePackaged(spec Spec, explicit string) (string, error) {
@@ -56,93 +73,236 @@ func ResolvePackaged(spec Spec, explicit string) (string, error) {
return filepath.Join(filepath.Dir(executable), "plugins", spec.fileName), nil
}
// Install verifies that the user installed BepInEx, then atomically stages the
// packaged plugin and its adjacent shared game-names runtime into its plugins
// directory. It never installs or downloads BepInEx itself.
func Install(spec Spec, gameDir, source string) (Result, error) {
if err := spec.validate(); err != nil {
return Result{}, err
}
if gameDir == "" || source == "" {
return Result{}, errors.New("clientplugin: game directory and plugin source are required")
}
gameDir = filepath.Clean(gameDir)
source = filepath.Clean(source)
installation, err := clientlayout.Resolve(gameDir)
if err != nil {
return Result{}, fmt.Errorf("clientplugin: resolve game layout: %w", err)
}
bepInEx := filepath.Join(installation.BepInEx, "core", "BepInEx.dll")
if info, err := os.Stat(bepInEx); err != nil || info.IsDir() {
return Result{}, fmt.Errorf("clientplugin: BepInEx is not installed; install it manually from %s, then run the client tool again; %s was not copied", BepInExReleasesURL, spec.fileName)
}
sourceData, err := os.ReadFile(source)
if err != nil {
return Result{}, fmt.Errorf("clientplugin: read packaged %s: %w", spec.fileName, err)
}
if len(sourceData) == 0 {
return Result{}, fmt.Errorf("clientplugin: packaged %s is empty", spec.fileName)
}
// Read both artifacts before touching the installation. The runtime table
// library is shipped beside every plugin, including explicit development paths.
var runtimeData []byte
if spec == LocalIdentity || spec == LoginUI || spec == CashShop || spec == FChat {
runtimeSource := filepath.Join(filepath.Dir(source), GameNames.fileName)
runtimeData, err = os.ReadFile(runtimeSource)
if err != nil {
return Result{}, fmt.Errorf("clientplugin: read shared runtime %s: %w", runtimeSource, err)
}
if len(runtimeData) == 0 {
return Result{}, fmt.Errorf("clientplugin: packaged %s is empty", GameNames.fileName)
}
}
changed := false
if runtimeData != nil {
runtimeResult, err := installData(GameNames, installation.Plugins, runtimeData)
if err != nil {
return Result{}, err
}
changed = runtimeResult.Changed
}
result, err := installData(spec, installation.Plugins, sourceData)
result.Changed = result.Changed || changed
return result, err
var installMu sync.Mutex
type staged struct {
name, temporary, destination, backup string
data []byte
}
func installData(spec Spec, pluginDir string, sourceData []byte) (Result, error) {
destination := filepath.Join(pluginDir, spec.fileName)
if installed, err := os.ReadFile(destination); err == nil {
if bytes.Equal(hash(installed), hash(sourceData)) {
return Result{Destination: destination}, nil
}
} else if !errors.Is(err, os.ErrNotExist) {
return Result{}, fmt.Errorf("clientplugin: inspect installed plugin: %w", err)
// InstallSet installs sources into the game's BepInEx/plugins as one unit:
// every file is staged first, then all are swapped in, and a failure part way
// restores the files that were already replaced. Only files listed in the
// previous managed set are ever removed; other plugins, configuration and
// language files are left alone. It never installs BepInEx itself.
func InstallSet(gameDir string, sources []string) (SetResult, error) {
installMu.Lock()
defer installMu.Unlock()
if gameDir == "" || len(sources) == 0 {
return SetResult{}, errors.New("clientplugin: game directory and plugin sources are required")
}
if err := os.MkdirAll(pluginDir, 0o755); err != nil {
return Result{}, fmt.Errorf("clientplugin: create plugin directory: %w", err)
}
temporary, err := os.CreateTemp(pluginDir, "."+spec.fileName+"-*.tmp")
installation, err := clientlayout.Resolve(filepath.Clean(gameDir))
if err != nil {
return Result{}, fmt.Errorf("clientplugin: create temporary plugin: %w", err)
return SetResult{}, fmt.Errorf("clientplugin: resolve game layout: %w", err)
}
temporaryPath := temporary.Name()
defer func() { _ = os.Remove(temporaryPath) }()
if _, err = io.Copy(temporary, bytes.NewReader(sourceData)); err == nil {
if info, err := os.Stat(filepath.Join(installation.BepInEx, "core", "BepInEx.dll")); err != nil || info.IsDir() {
return SetResult{}, fmt.Errorf("clientplugin: BepInEx is not installed; install it manually from %s, then run the client tool again", BepInExReleasesURL)
}
directory := installation.Plugins
if err := os.MkdirAll(directory, 0o755); err != nil {
return SetResult{}, fmt.Errorf("clientplugin: create plugin directory: %w", err)
}
var files []*staged
names := make([]string, 0, len(sources))
for _, source := range sources {
name := filepath.Base(source)
if err := (Spec{fileName: name}).validate(); err != nil {
return SetResult{}, err
}
data, err := os.ReadFile(source)
if err != nil {
return SetResult{}, fmt.Errorf("clientplugin: read packaged %s: %w", name, err)
}
if len(data) == 0 {
return SetResult{}, fmt.Errorf("clientplugin: packaged %s is empty", name)
}
for _, existing := range names {
if strings.EqualFold(existing, name) {
return SetResult{}, fmt.Errorf("clientplugin: duplicate plugin %s", name)
}
}
names = append(names, name)
files = append(files, &staged{name: name, destination: filepath.Join(directory, name), data: data})
}
result := SetResult{}
var changed []*staged
for _, f := range files {
installed, err := os.ReadFile(f.destination)
if err == nil && bytes.Equal(installed, f.data) {
result.Files = append(result.Files, Result{Destination: f.destination})
continue
}
if err != nil && !errors.Is(err, os.ErrNotExist) {
return SetResult{}, fmt.Errorf("clientplugin: inspect installed plugin: %w", err)
}
changed = append(changed, f)
result.Files = append(result.Files, Result{Destination: f.destination, Changed: true})
}
previous, err := readManaged(directory)
if err != nil {
return SetResult{}, err
}
var dropped []string
for _, name := range previous {
if !slices.ContainsFunc(names, func(candidate string) bool { return strings.EqualFold(candidate, name) }) {
dropped = append(dropped, name)
}
}
defer func() {
for _, f := range changed {
if f.temporary != "" {
_ = os.Remove(f.temporary)
}
}
}()
for _, f := range changed {
temporary, err := stageFile(directory, f.name, f.data)
if err != nil {
return SetResult{}, err
}
f.temporary = temporary
}
backupDir, err := os.MkdirTemp(directory, ".bd2-transaction-*")
if err != nil {
return SetResult{}, err
}
var replaced []*staged
restore := func(cause error) (SetResult, error) {
var failures []error
for _, f := range slices.Backward(replaced) {
if f.backup != "" {
if err := commonconfig.ReplaceFile(f.backup, f.destination); err != nil {
failures = append(failures, fmt.Errorf("restore %s: %w", f.name, err))
}
} else if err := os.Remove(f.destination); err != nil && !errors.Is(err, os.ErrNotExist) {
failures = append(failures, err)
}
}
if len(failures) != 0 {
return SetResult{}, fmt.Errorf("clientplugin: install failed; rollback incomplete (backups in %s): %w", backupDir, errors.Join(append([]error{cause}, failures...)...))
}
_ = os.RemoveAll(backupDir)
return SetResult{}, fmt.Errorf("clientplugin: install failed; previous plugins restored: %w", cause)
}
swap := func(f *staged) error {
info, err := os.Lstat(f.destination)
if err == nil {
if !info.Mode().IsRegular() {
return fmt.Errorf("clientplugin: %s is not a regular file", f.destination)
}
f.backup = filepath.Join(backupDir, f.name)
if err := os.Rename(f.destination, f.backup); err != nil {
return err
}
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
replaced = append(replaced, f)
if f.temporary != "" {
if err := commonconfig.ReplaceFile(f.temporary, f.destination); err != nil {
return err
}
f.temporary = ""
}
return nil
}
for _, f := range changed {
if err := swap(f); err != nil {
return restore(err)
}
}
for _, name := range dropped {
f := &staged{name: name, destination: filepath.Join(directory, name)}
if err := swap(f); err != nil {
return restore(err)
}
if f.backup != "" {
result.Removed = append(result.Removed, name)
}
}
if !slices.Equal(previous, names) {
if err := commonconfig.Save(filepath.Join(directory, managedFile), names, commonconfig.WriteOptions{}); err != nil {
return restore(fmt.Errorf("record managed plugins: %w", err))
}
}
if err := os.RemoveAll(backupDir); err != nil {
return result, fmt.Errorf("clientplugin: plugins installed but backup cleanup failed: %w", err)
}
result.Changed = len(changed) != 0 || len(result.Removed) != 0 || !slices.Equal(previous, names)
return result, nil
}
func stageFile(directory, name string, data []byte) (string, error) {
temporary, err := os.CreateTemp(directory, "."+name+"-*.tmp")
if err != nil {
return "", fmt.Errorf("clientplugin: create temporary plugin: %w", err)
}
if _, err = temporary.Write(data); err == nil {
err = temporary.Sync()
}
if closeErr := temporary.Close(); err == nil {
err = closeErr
}
if err != nil {
return Result{}, fmt.Errorf("clientplugin: stage plugin: %w", err)
_ = os.Remove(temporary.Name())
return "", fmt.Errorf("clientplugin: stage plugin: %w", err)
}
if err := replaceFile(temporaryPath, destination); err != nil {
return Result{}, fmt.Errorf("clientplugin: install plugin (close the game client first): %w", err)
}
return Result{Destination: destination, Changed: true}, nil
return temporary.Name(), nil
}
func hash(data []byte) []byte {
sum := sha256.Sum256(data)
return sum[:]
func readManaged(directory string) ([]string, error) {
raw, err := os.ReadFile(filepath.Join(directory, managedFile))
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("clientplugin: read managed plugins: %w", err)
}
var names []string
if err := json.Unmarshal(raw, &names); err != nil {
return nil, fmt.Errorf("clientplugin: decode managed plugins: %w", err)
}
seen := map[string]bool{}
for _, name := range names {
if seen[strings.ToLower(name)] {
return nil, fmt.Errorf("clientplugin: duplicate managed plugin %q", name)
}
seen[strings.ToLower(name)] = true
if err := (Spec{fileName: name}).validate(); err != nil {
return nil, fmt.Errorf("clientplugin: invalid managed plugin %q", name)
}
}
return names, nil
}
// Installed reports whether the game's plugin directory already holds
// exactly these files.
func Installed(gameDir string, sources []string) (bool, error) {
installMu.Lock()
defer installMu.Unlock()
installation, err := clientlayout.Resolve(filepath.Clean(gameDir))
if err != nil {
return false, err
}
for _, source := range sources {
want, err := os.ReadFile(source)
if err != nil {
return false, err
}
have, err := os.ReadFile(filepath.Join(installation.Plugins, filepath.Base(source)))
if err != nil || !bytes.Equal(have, want) {
return false, nil
}
}
previous, err := readManaged(installation.Plugins)
if err != nil {
return false, err
}
for _, name := range previous {
if !slices.ContainsFunc(sources, func(source string) bool { return strings.EqualFold(filepath.Base(source), name) }) {
return false, nil
}
}
return true, nil
}
+220
View File
@@ -0,0 +1,220 @@
package plugin
import (
"errors"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestInstallSetReplacesOnlyTheManagedPlugins(t *testing.T) {
root := t.TempDir()
write := func(relative, value string) string {
t.Helper()
path := filepath.Join(root, filepath.FromSlash(relative))
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(value), 0o600); err != nil {
t.Fatal(err)
}
return path
}
read := func(relative string) (string, error) {
raw, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(relative)))
return string(raw), err
}
game := filepath.Join(root, "game")
write("game/BrownDust II.exe", "fixture")
write("game/BrownDust II_Data/resources.assets", "fixture")
write("game/BepInEx/core/BepInEx.dll", "fixture")
write("game/BepInEx/plugins/OtherMod.dll", "player's own plugin")
write("game/BepInEx/config/BD2FChat.cfg", "player settings")
first := []string{write("v1/BD2LoginUI.dll", "login v1"), write("v1/BD2FChat.dll", "chat v1")}
result, err := InstallSet(game, first)
if err != nil || !result.Changed {
t.Fatalf("first install = %+v, %v", result, err)
}
// The next set drops FChat and changes LoginUI.
second := []string{write("v2/BD2LoginUI.dll", "login v2")}
result, err = InstallSet(game, second)
if err != nil || !result.Changed {
t.Fatalf("second install = %+v, %v", result, err)
}
if got, _ := read("game/BepInEx/plugins/BD2LoginUI.dll"); got != "login v2" {
t.Errorf("LoginUI = %q, want the new set's file", got)
}
if _, err := read("game/BepInEx/plugins/BD2FChat.dll"); !errors.Is(err, os.ErrNotExist) {
t.Errorf("a plugin dropped from the managed set was left installed: %v", err)
}
if got, _ := read("game/BepInEx/plugins/OtherMod.dll"); got != "player's own plugin" {
t.Errorf("an unmanaged plugin was touched: %q", got)
}
if got, _ := read("game/BepInEx/config/BD2FChat.cfg"); got != "player settings" {
t.Errorf("plugin configuration was touched: %q", got)
}
result, err = InstallSet(game, second)
if err != nil || result.Changed {
t.Fatalf("reinstalling the same set = %+v, %v; want no change", result, err)
}
}
func TestInstalledDetectsAnOutdatedPlugin(t *testing.T) {
root := t.TempDir()
write := func(relative, value string) string {
t.Helper()
path := filepath.Join(root, filepath.FromSlash(relative))
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(value), 0o600); err != nil {
t.Fatal(err)
}
return path
}
game := filepath.Join(root, "game")
write("game/BrownDust II.exe", "fixture")
write("game/BrownDust II_Data/resources.assets", "fixture")
write("game/BepInEx/plugins/BD2LoginUI.dll", "login v1")
newer := []string{write("store/BD2LoginUI.dll", "login v2")}
if installed, err := Installed(game, newer); err != nil || installed {
t.Fatalf("Installed with an older DLL = %v, %v; want false so the launcher installs the set", installed, err)
}
missing := []string{write("store/BD2FChat.dll", "chat")}
if installed, err := Installed(game, missing); err != nil || installed {
t.Fatalf("Installed with a missing DLL = %v, %v; want false", installed, err)
}
write("game/BepInEx/plugins/BD2LoginUI.dll", "login v2")
if installed, err := Installed(game, newer); err != nil || !installed {
t.Fatalf("Installed with matching DLL = %v, %v; want true", installed, err)
}
}
func pluginFixture(t *testing.T) (string, func(string, string) string) {
t.Helper()
root := t.TempDir()
write := func(relative, value string) string {
t.Helper()
path := filepath.Join(root, filepath.FromSlash(relative))
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(value), 0o600); err != nil {
t.Fatal(err)
}
return path
}
write("game/BrownDust II.exe", "fixture")
write("game/BrownDust II_Data/resources.assets", "fixture")
write("game/BepInEx/core/BepInEx.dll", "fixture")
write("game/BepInEx/plugins/OtherMod.dll", "player plugin")
write("game/BepInEx/config/BD2FChat.cfg", "player config")
write("game/BepInEx/plugins/lang/custom.json", "player language")
return root, write
}
func assertPluginFiles(t *testing.T, root string, want map[string]string) {
t.Helper()
for name, expected := range want {
raw, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(name)))
if err != nil || string(raw) != expected {
t.Errorf("%s = %q, %v; want %q", name, raw, err, expected)
}
}
}
func TestInstallSetRollsBackWhenDroppedPluginCannotBeRemoved(t *testing.T) {
root, write := pluginFixture(t)
game := filepath.Join(root, "game")
first := []string{write("v1/BD2LoginUI.dll", "old login"), write("v1/BD2FChat.dll", "old chat")}
if _, err := InstallSet(game, first); err != nil {
t.Fatal(err)
}
chat := filepath.Join(game, "BepInEx", "plugins", "BD2FChat.dll")
if err := os.Remove(chat); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(chat, 0o700); err != nil {
t.Fatal(err)
}
write("game/BepInEx/plugins/BD2FChat.dll/player.txt", "do not remove")
next := []string{write("v2/BD2LoginUI.dll", "new login"), write("v2/BD2CashShop.dll", "new shop")}
if _, err := InstallSet(game, next); err == nil {
t.Fatal("install succeeded despite an undeletable managed entry")
}
assertPluginFiles(t, root, map[string]string{
"game/BepInEx/plugins/BD2LoginUI.dll": "old login",
"game/BepInEx/plugins/BD2FChat.dll/player.txt": "do not remove",
"game/BepInEx/plugins/OtherMod.dll": "player plugin",
"game/BepInEx/config/BD2FChat.cfg": "player config",
"game/BepInEx/plugins/lang/custom.json": "player language",
})
if _, err := os.Stat(filepath.Join(game, "BepInEx", "plugins", "BD2CashShop.dll")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("new plugin survived rollback: %v", err)
}
names, err := readManaged(filepath.Join(game, "BepInEx", "plugins"))
if err != nil || len(names) != 2 || names[1] != "BD2FChat.dll" {
t.Fatalf("managed ownership changed: %v, %v", names, err)
}
}
func TestInstallSetRollsBackEveryChangeWhenMetadataIsLocked(t *testing.T) {
if runtime.GOOS != "windows" {
t.Skip("Windows denies replacing open metadata files")
}
root, write := pluginFixture(t)
game := filepath.Join(root, "game")
first := []string{write("v1/BD2LoginUI.dll", "old login"), write("v1/BD2FChat.dll", "old chat")}
if _, err := InstallSet(game, first); err != nil {
t.Fatal(err)
}
metadata := filepath.Join(game, "BepInEx", "plugins", managedFile)
old, err := os.ReadFile(metadata)
if err != nil {
t.Fatal(err)
}
lock, err := os.Open(metadata)
if err != nil {
t.Fatal(err)
}
defer func() {
if err := lock.Close(); err != nil {
t.Error(err)
}
}()
next := []string{write("v2/BD2LoginUI.dll", "new login"), write("v2/BD2CashShop.dll", "new shop")}
if _, err := InstallSet(game, next); err == nil || !strings.Contains(err.Error(), "record managed plugins") {
t.Fatalf("want failure after DLL replacement and removal, got %v", err)
}
assertPluginFiles(t, root, map[string]string{
"game/BepInEx/plugins/BD2LoginUI.dll": "old login",
"game/BepInEx/plugins/BD2FChat.dll": "old chat",
"game/BepInEx/plugins/" + managedFile: string(old),
"game/BepInEx/plugins/OtherMod.dll": "player plugin",
"game/BepInEx/config/BD2FChat.cfg": "player config",
"game/BepInEx/plugins/lang/custom.json": "player language",
})
if _, err := os.Stat(filepath.Join(game, "BepInEx", "plugins", "BD2CashShop.dll")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("new plugin survived rollback: %v", err)
}
}
func TestInstallSetRejectsOwnershipThatEscapesThePluginDirectory(t *testing.T) {
root, write := pluginFixture(t)
game := filepath.Join(root, "game")
write("game/BepInEx/plugins/.bd2-managed.json", `["../config/player.dll"]`)
write("game/BepInEx/config/player.dll", "player data")
source := write("v2/BD2LoginUI.dll", "new login")
if _, err := InstallSet(game, []string{source}); err == nil {
t.Fatal("accepted ownership outside plugins")
}
assertPluginFiles(t, root, map[string]string{"game/BepInEx/config/player.dll": "player data"})
if _, err := os.Stat(filepath.Join(game, "BepInEx", "plugins", "BD2LoginUI.dll")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("changed DLL despite invalid ownership: %v", err)
}
}
@@ -1,9 +0,0 @@
//go:build !windows
package plugin
import "os"
func replaceFile(source, destination string) error {
return os.Rename(source, destination)
}
@@ -1,34 +0,0 @@
//go:build windows
package plugin
import (
"os"
"syscall"
"unsafe"
)
var moveFileEx = syscall.NewLazyDLL("kernel32.dll").NewProc("MoveFileExW")
func replaceFile(source, destination string) error {
sourcePtr, err := syscall.UTF16PtrFromString(source)
if err != nil {
return err
}
destinationPtr, err := syscall.UTF16PtrFromString(destination)
if err != nil {
return err
}
result, _, callErr := moveFileEx.Call(
uintptr(unsafe.Pointer(sourcePtr)),
uintptr(unsafe.Pointer(destinationPtr)),
0x1|0x8, // MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH
)
if result == 0 {
if callErr != syscall.Errno(0) {
return callErr
}
return os.ErrInvalid
}
return nil
}
+104 -10
View File
@@ -18,10 +18,11 @@ import (
const (
localCatalogPrefix = "{UnityEngine.AddressableAssets.Addressables.RuntimePath}\\"
localCatalogBackup = "catalog.json.bd2-before-local-sync"
localBundleManifest = ".bd2-local-bundles.json"
maximumCatalogBytes = 128 << 20
)
func installCurrentLocalCatalog(gameDir, localRoot, bundleVersion string) error {
func InstallLocalCatalog(gameDir, localRoot, bundleVersion string) error {
installation, err := clientlayout.Resolve(gameDir)
if err != nil {
return err
@@ -34,7 +35,15 @@ func installCurrentLocalCatalog(gameDir, localRoot, bundleVersion string) error
return err
}
aa := filepath.Join(installation.Data, "StreamingAssets", "aa")
raw, err = localizeCatalog(raw, release, aa)
managed, err := managedCatalogBundles(aa)
if err != nil {
return err
}
paths, err := resourcecatalog.BundlePaths(raw)
if err != nil {
return err
}
raw, err = localizeCatalog(raw, release, aa, managed)
if err != nil {
return err
}
@@ -56,6 +65,25 @@ func installCurrentLocalCatalog(gameDir, localRoot, bundleVersion string) error
return fmt.Errorf("install current local Addressables catalog: %w", err)
}
}
var records []managedBundle
for _, relative := range paths {
sourceInfo, err := os.Stat(filepath.Join(release, filepath.FromSlash(relative)))
if err != nil {
return err
}
targetInfo, err := os.Stat(filepath.Join(aa, filepath.FromSlash(relative)))
if err != nil {
return err
}
records = append(records, managedBundle{Path: relative, SourceSize: sourceInfo.Size(), SourceModified: sourceInfo.ModTime().UnixNano(), TargetSize: targetInfo.Size(), TargetModified: targetInfo.ModTime().UnixNano()})
}
managedRaw, err := json.Marshal(records)
if err != nil {
return err
}
if err := replaceCatalog(filepath.Join(aa, localBundleManifest), managedRaw); err != nil {
return fmt.Errorf("record managed Addressables bundles: %w", err)
}
hash, err := os.ReadFile(sourceHash)
if err != nil {
return fmt.Errorf("read local ServerData catalog hash: %w", err)
@@ -158,7 +186,37 @@ func readCatalog(path string) ([]byte, error) {
return raw, nil
}
func localizeCatalog(raw []byte, release, aa string) ([]byte, error) {
type managedBundle struct {
Path string `json:"path"`
SourceSize int64 `json:"source_size"`
SourceModified int64 `json:"source_modified"`
TargetSize int64 `json:"target_size"`
TargetModified int64 `json:"target_modified"`
}
func managedCatalogBundles(aa string) (map[string]managedBundle, error) {
managed := map[string]managedBundle{}
raw, err := os.ReadFile(filepath.Join(aa, localBundleManifest))
if errors.Is(err, os.ErrNotExist) {
return managed, nil
}
if err != nil {
return nil, err
}
var records []managedBundle
if err := json.Unmarshal(raw, &records); err != nil {
return nil, fmt.Errorf("read managed Addressables bundles: %w", err)
}
for _, record := range records {
if _, err := resourcecatalog.BundlePath(resourcecatalog.RemotePrefix + "/platform/HD/version/" + record.Path); err != nil {
return nil, err
}
managed[record.Path] = record
}
return managed, nil
}
func localizeCatalog(raw []byte, release, aa string, managed map[string]managedBundle) ([]byte, error) {
document, ids, err := resourcecatalog.Decode(raw)
if err != nil {
return nil, err
@@ -172,7 +230,7 @@ func localizeCatalog(raw []byte, release, aa string) ([]byte, error) {
}
source := filepath.Join(release, filepath.FromSlash(relative))
destination := filepath.Join(aa, filepath.FromSlash(relative))
if err := ensureCatalogBundleLink(source, destination); err != nil {
if err := ensureCatalogBundleLink(source, destination, managed[relative]); err != nil {
return nil, err
}
ids[index] = localCatalogPrefix + strings.ReplaceAll(filepath.ToSlash(relative), "/", "\\")
@@ -201,26 +259,62 @@ func localizeCatalog(raw []byte, release, aa string) ([]byte, error) {
return localized, nil
}
func ensureCatalogBundleLink(source, destination string) error {
func ensureCatalogBundleLink(source, destination string, managed managedBundle) error {
sourceInfo, err := os.Stat(source)
if err != nil || !sourceInfo.Mode().IsRegular() {
return fmt.Errorf("local ServerData catalog references a missing bundle: %s", source)
}
if destinationInfo, err := os.Stat(destination); err == nil {
if !destinationInfo.Mode().IsRegular() || !os.SameFile(sourceInfo, destinationInfo) {
if !destinationInfo.Mode().IsRegular() {
return fmt.Errorf("game Addressables bundle conflicts with the selected local release: %s", destination)
}
return nil
if os.SameFile(sourceInfo, destinationInfo) {
return nil
}
if managed.Path == "" {
return fmt.Errorf("game Addressables bundle conflicts with the selected local release: %s", destination)
}
if sourceInfo.Size() == managed.SourceSize && sourceInfo.ModTime().UnixNano() == managed.SourceModified && destinationInfo.Size() == managed.TargetSize && destinationInfo.ModTime().UnixNano() == managed.TargetModified {
return nil
}
} else if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("inspect game Addressables bundle: %w", err)
}
if err := os.MkdirAll(filepath.Dir(destination), 0o755); err != nil {
return fmt.Errorf("create game Addressables bundle directory: %w", err)
}
if err := os.Link(source, destination); err != nil {
return fmt.Errorf("hard-link local bundle without duplicating it (keep the game and local resources on the same filesystem): %w", err)
staged, err := os.CreateTemp(filepath.Dir(destination), ".bundle-local-*")
if err != nil {
return err
}
return nil
path := staged.Name()
defer func() { _ = staged.Close(); _ = os.Remove(path) }()
if err := staged.Close(); err != nil {
return err
}
if err := os.Remove(path); err != nil {
return err
}
if err := os.Link(source, path); err != nil {
in, err := os.Open(source)
if err != nil {
return err
}
defer func() { _ = in.Close() }()
out, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
if err != nil {
return err
}
written, copyErr := io.Copy(out, in)
syncErr, closeErr := out.Sync(), out.Close()
if err := errors.Join(copyErr, syncErr, closeErr); err != nil {
return err
}
if written != sourceInfo.Size() {
return errors.New("incomplete local Addressables bundle copy")
}
}
return os.Rename(path, destination)
}
func writeExclusiveFile(path string, data []byte, mode os.FileMode) error {
@@ -0,0 +1,94 @@
package setup
import (
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
func TestLocalCatalogRefreshReplacesManagedBundlesAndPreservesBuiltins(t *testing.T) {
root := t.TempDir()
resources := t.TempDir()
if runtime.GOOS == "windows" {
if _, err := os.Stat("E:\\"); err == nil && !strings.EqualFold(filepath.VolumeName(root), "E:") {
crossDrive, err := os.MkdirTemp("E:\\", "bd2-localcatalog-test-")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := os.RemoveAll(crossDrive); err != nil {
t.Error(err)
}
})
resources = crossDrive
t.Logf("checking cross-volume resource copies: game=%s resources=%s", filepath.VolumeName(root), filepath.VolumeName(resources))
}
}
game := filepath.Join(root, "instance", "game")
aa := filepath.Join(game, "BrownDust II_Data", "StreamingAssets", "aa")
write := func(path, value string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(value), 0600); err != nil {
t.Fatal(err)
}
}
write(filepath.Join(game, "BrownDust II.exe"), "game")
write(filepath.Join(game, "BrownDust II_Data", "resources.assets"), "assets")
write(filepath.Join(root, "instance", "instance.json"), `{"schema_version":1,"id":"instance"}`)
write(filepath.Join(aa, "catalog.json"), `{"m_InternalIds":["{UnityEngine.AddressableAssets.Addressables.RuntimePath}\\builtin.bundle"]}`)
write(filepath.Join(aa, "builtin.bundle"), "keep builtin")
const version = "20261007175947"
release := filepath.Join(resources, "ServerData", "StandaloneWindows64", "HD", version)
write(filepath.Join(release, "catalog_alpha.json"), `{"m_InternalIds":["{BDNetwork.CdnInfo.Info}/StandaloneWindows64/HD/20261007175947/scene.bundle","{UnityEngine.AddressableAssets.Addressables.RuntimePath}\\builtin.bundle"]}`)
write(filepath.Join(release, "catalog_alpha.hash"), "0f90a94601be05737f86a4ec7a1c889f")
source := filepath.Join(release, "scene.bundle")
write(source, "old bytes")
if err := InstallLocalCatalog(game, resources, version); err != nil {
t.Fatal(err)
}
streamed := filepath.Join(aa, "scene.bundle")
if actual, err := os.ReadFile(streamed); err != nil || string(actual) != "old bytes" {
t.Fatalf("initial resource was not installed: %q, %v", actual, err)
}
previous, err := os.Stat(source)
if err != nil {
t.Fatal(err)
}
write(source+".new", "new bytes")
changed := previous.ModTime().Add(2 * time.Second)
if err := os.Chtimes(source+".new", changed, changed); err != nil {
t.Fatal(err)
}
if err := os.Rename(source+".new", source); err != nil {
t.Fatal(err)
}
if err := InstallLocalCatalog(game, resources, version); err != nil {
t.Fatal(err)
}
if actual, err := os.ReadFile(streamed); err != nil || string(actual) != "new bytes" {
t.Fatalf("managed resource kept the old source inode: %q, %v", actual, err)
}
if actual, err := os.ReadFile(filepath.Join(aa, "builtin.bundle")); err != nil || string(actual) != "keep builtin" {
t.Fatalf("unrelated builtin changed: %q, %v", actual, err)
}
installed, err := os.Stat(streamed)
if err != nil {
t.Fatal(err)
}
if err := InstallLocalCatalog(game, resources, version); err != nil {
t.Fatal(err)
}
unchanged, err := os.Stat(streamed)
if err != nil {
t.Fatal(err)
}
if !os.SameFile(installed, unchanged) {
t.Fatal("unchanged cached resource was unnecessarily replaced")
}
}
+15 -39
View File
@@ -15,6 +15,7 @@ import (
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
@@ -48,12 +49,7 @@ type ResourcePolicy struct {
LocalDirectory string `json:"local_directory,omitempty"`
}
type InstallResult struct {
LocalIdentity plugin.Result `json:"local_identity"`
LoginUI plugin.Result `json:"login_ui"`
CashShop plugin.Result `json:"cash_shop"`
FChat plugin.Result `json:"fchat"`
}
type InstallResult = plugin.SetResult
func Inspect(gameDir string, versions versionconfig.Config) (GameStatus, error) {
if strings.TrimSpace(gameDir) == "" {
@@ -90,7 +86,7 @@ func SaveSettings(gameDir string, settings clientconfig.Settings, versions versi
return clientconfig.Settings{}, err
}
if normalized.CDNMode == clientconfig.CDNLocal {
if err := installCurrentLocalCatalog(gameDir, normalized.LocalResourceDirectory, versions.BundleVersion); err != nil {
if err := InstallLocalCatalog(gameDir, normalized.LocalResourceDirectory, versions.BundleVersion); err != nil {
return clientconfig.Settings{}, err
}
}
@@ -133,39 +129,19 @@ func InstallPlugins(
if _, err := SaveSettings(gameDir, settings, versions); err != nil {
return InstallResult{}, err
}
localSource, err := plugin.ResolvePackaged(plugin.LocalIdentity, localIdentitySource)
if err != nil {
return InstallResult{}, err
var sources []string
for spec, explicit := range map[plugin.Spec]string{plugin.LocalIdentity: localIdentitySource, plugin.LoginUI: loginUISource, plugin.CashShop: cashShopSource, plugin.FChat: fChatSource} {
source, err := plugin.ResolvePackaged(spec, explicit)
if err != nil {
return InstallResult{}, err
}
sources = append(sources, source)
}
loginSource, err := plugin.ResolvePackaged(plugin.LoginUI, loginUISource)
if err != nil {
return InstallResult{}, err
}
cashSource, err := plugin.ResolvePackaged(plugin.CashShop, cashShopSource)
if err != nil {
return InstallResult{}, err
}
fchatSource, err := plugin.ResolvePackaged(plugin.FChat, fChatSource)
if err != nil {
return InstallResult{}, err
}
local, err := plugin.Install(plugin.LocalIdentity, gameDir, localSource)
if err != nil {
return InstallResult{}, err
}
login, err := plugin.Install(plugin.LoginUI, gameDir, loginSource)
if err != nil {
return InstallResult{}, err
}
cash, err := plugin.Install(plugin.CashShop, gameDir, cashSource)
if err != nil {
return InstallResult{}, err
}
fchat, err := plugin.Install(plugin.FChat, gameDir, fchatSource)
if err != nil {
return InstallResult{}, err
}
return InstallResult{LocalIdentity: local, LoginUI: login, CashShop: cash, FChat: fchat}, nil
// The shared runtime ships beside the plugins, including development builds.
localSource, _ := plugin.ResolvePackaged(plugin.LocalIdentity, localIdentitySource)
sources = append(sources, filepath.Join(filepath.Dir(localSource), plugin.GameNames.FileName()))
sort.Strings(sources)
return plugin.InstallSet(gameDir, sources)
}
func FetchResourcePolicy(ctx context.Context, client *http.Client, settings clientconfig.Settings, versions versionconfig.Config) (ResourcePolicy, error) {
+332
View File
@@ -0,0 +1,332 @@
package update
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
clientconfig "bd2server/internal/client/config"
"bd2server/internal/client/download"
"bd2server/internal/client/setup"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/release"
"bd2server/internal/common/versionconfig"
)
const gameReceiptFile = ".bd2-update-receipt.json"
type gameReceipt struct {
Fingerprint string `json:"fingerprint"`
ResourceFingerprint string `json:"resource_fingerprint"`
GameVersion string `json:"game_version"`
BundleVersion string `json:"bundle_version"`
GameDataVersion string `json:"game_data_version"`
Resources string `json:"resources"`
Files []verifiedGameFile `json:"files,omitempty"`
}
type verifiedGameFile struct {
Path string `json:"path"`
Size int64 `json:"size"`
Modified int64 `json:"modified"`
SHA256 string `json:"sha256"`
}
func readGameReceipt(game string) (gameReceipt, error) {
return commonconfig.Load(filepath.Join(game, gameReceiptFile), gameReceipt{}, commonconfig.DecodeOptions{RejectTrailing: true, RejectNull: true})
}
func gameReceiptMatches(game, id string) bool {
receipt, err := readGameReceipt(game)
if err != nil || receipt.Fingerprint != id {
return false
}
for _, file := range receipt.Files {
info, err := os.Stat(file.Path)
if err != nil || !info.Mode().IsRegular() || info.Size() != file.Size {
return false
}
if info.ModTime().UnixNano() != file.Modified && !release.Matches(file.Path, release.File{Size: file.Size, SHA256: file.SHA256}) {
return false
}
}
return true
}
func (m *Manager) Versions(game string) versionconfig.Config {
v := m.options.Versions
if receipt, err := readGameReceipt(game); err == nil {
v.GameVersion, v.BundleVersion, v.GameDataVersion = receipt.GameVersion, receipt.BundleVersion, receipt.GameDataVersion
}
return v
}
func (m *Manager) ensureGame(ctx context.Context, game string) error {
m.mu.Lock()
fp := m.fingerprint
fingerprintErr := m.fingerprintErr
m.mu.Unlock()
if fingerprintErr != nil {
return fingerprintErr
}
if fp == nil {
m.mu.Lock()
delete(m.gamePending, game)
if len(m.gamePending) == 0 {
m.status.Game = nil
}
m.mu.Unlock()
return nil
}
previous, previousErr := readGameReceipt(game)
if gameReceiptMatches(game, fp.ID) && (!fp.RequireGameUpdate || previous.ResourceFingerprint == fp.GameFingerprint && len(previous.Files) > 0) {
return nil
}
if fp.RequireClientUpdate && clientUpdateRequired(m.options.Versions.ClientVersion, fp.ClientVersion) {
return fmt.Errorf("update the launcher to %s before updating the game", fp.ClientVersion)
}
reuseResources := previousErr == nil && previous.ResourceFingerprint == fp.GameFingerprint && fp.GameFingerprint != "" && len(previous.Files) > 0 && gameReceiptMatches(game, previous.Fingerprint)
installGame := fp.RequireGameUpdate && !reuseResources
if installGame {
if fp.Game == nil {
return errors.New("required game update has no signed download inventory")
}
m.mu.Lock()
m.status.Game = &Offer{Version: fp.Game.GameVersion}
m.mu.Unlock()
for _, instance := range m.instances() {
if running, err := m.gameRunning(instance); err != nil {
return err
} else if running {
m.mu.Lock()
m.gamePending[game] = true
m.mu.Unlock()
return errors.New("close all game instances to install the required game and resource update")
}
}
if running, err := m.gameRunning(game); err != nil {
return err
} else if running {
m.mu.Lock()
m.gamePending[game] = true
m.mu.Unlock()
return errors.New("close the game to install the required game and resource update")
}
}
v := m.Versions(game)
resources := ""
if installGame {
settings, err := clientconfig.Load(game)
if err != nil {
return fmt.Errorf("load game settings before updating: %w", err)
}
resources = settings.LocalResourceDirectory
if resources == "" {
resources = filepath.Join(m.options.Directory, "resources")
}
installed, err := download.Client(ctx, download.Options{PackageDir: m.options.Directory, GameDir: game, ResourceDir: resources, Workers: 8, Pinned: fp.Game}, io.Discard)
if err != nil {
return err
}
v.GameVersion, v.BundleVersion, v.GameDataVersion = installed.Versions.GameVersion, installed.Versions.BundleVersion, installed.Versions.GameDataVersion
resources = installed.ResourceDir
if _, err := setup.Patch(game, settings, v); err != nil {
return fmt.Errorf("restore game connection patch: %w", err)
}
if err := setup.InstallLocalCatalog(game, resources, v.BundleVersion); err != nil {
return fmt.Errorf("prepare verified game resource catalog: %w", err)
}
}
receipt := gameReceipt{Fingerprint: fp.ID, GameVersion: v.GameVersion, BundleVersion: v.BundleVersion, GameDataVersion: v.GameDataVersion, Resources: resources}
if installGame {
receipt.ResourceFingerprint = fp.GameFingerprint
for _, pin := range fp.Game.ResourceFiles {
path := filepath.Join(resources, filepath.FromSlash(pin.Path))
info, err := os.Stat(path)
if err != nil {
return err
}
if !info.Mode().IsRegular() || info.Size() != pin.Size {
return fmt.Errorf("required resource was not installed: %s", pin.Path)
}
receipt.Files = append(receipt.Files, verifiedGameFile{Path: path, Size: pin.Size, Modified: info.ModTime().UnixNano(), SHA256: pin.SHA256})
prefix := "ServerData/" + fp.Game.Platform + "/HD/" + fp.Game.BundleVersion + "/"
if relative, ok := strings.CutPrefix(pin.Path, prefix); ok && strings.EqualFold(filepath.Ext(relative), ".bundle") {
streamed := filepath.Join(game, "BrownDust II_Data", "StreamingAssets", "aa", filepath.FromSlash(relative))
streamedInfo, err := os.Stat(streamed)
if err != nil {
return err
}
receipt.Files = append(receipt.Files, verifiedGameFile{Path: streamed, Size: pin.Size, Modified: streamedInfo.ModTime().UnixNano(), SHA256: pin.SHA256})
}
}
for _, relative := range []string{"BrownDust II.exe", "UnityPlayer.dll", "BrownDust II_Data/globalgamemanagers", "BrownDust II_Data/Managed/Assembly-CSharp.dll", "BrownDust II_Data/resources.assets", "BrownDust II_Data/StreamingAssets/aa/catalog.json", "BrownDust II_Data/StreamingAssets/aa/.bd2-local-bundles.json"} {
path := filepath.Join(game, filepath.FromSlash(relative))
info, err := os.Stat(path)
if err != nil {
return err
}
digest, err := release.HashFile(path)
if err != nil {
return err
}
receipt.Files = append(receipt.Files, verifiedGameFile{Path: path, Size: info.Size(), Modified: info.ModTime().UnixNano(), SHA256: digest})
}
} else if previousErr == nil {
receipt.Files, receipt.Resources, receipt.ResourceFingerprint = previous.Files, previous.Resources, previous.ResourceFingerprint
}
if err := commonconfig.Save(filepath.Join(game, gameReceiptFile), receipt, commonconfig.WriteOptions{FileMode: 0644}); err != nil {
return err
}
m.mu.Lock()
delete(m.gamePending, game)
if len(m.gamePending) == 0 {
m.status.Game = nil
}
m.mu.Unlock()
return nil
}
func (m *Manager) CommitGame(ctx context.Context) error {
if !m.begin("installing") {
return operationBusy()
}
defer m.end()
var first error
for _, game := range m.instances() {
settings, err := clientconfig.Load(game)
if err != nil {
if first == nil {
first = err
}
continue
}
if err := m.CheckServer(ctx, m.options.Client, settings.ServerOrigin); err != nil {
if first == nil {
first = err
}
continue
}
if err := m.ensureGame(ctx, game); err != nil && first == nil {
first = err
}
}
m.mu.Lock()
if first != nil {
m.status.Error = first.Error()
} else {
m.status.Error = ""
}
m.mu.Unlock()
return first
}
func (m *Manager) installGameUpdates(ctx context.Context) {
m.mu.Lock()
waiting := len(m.gamePending) != 0
m.mu.Unlock()
if waiting {
_ = m.CommitGame(ctx)
}
}
// PrepareGame resolves the server's signed requirement before inspecting a
// possibly obsolete game installation with the new release's versions.
func (m *Manager) PrepareGame(ctx context.Context, game, origin string) error {
if !m.begin("preparing") {
return operationBusy()
}
defer m.end()
if err := m.CheckServer(ctx, m.options.Client, origin); err != nil {
return err
}
return m.ensureGame(ctx, game)
}
func LaunchEnvironment(environment []string, game, clientVersion string) []string {
values := map[string]string{"BD2_CLIENT_VERSION": clientVersion, "BD2_UPDATE_FINGERPRINT": "", "BD2_RESOURCE_FINGERPRINT": "", "BD2_RESOURCE_DIRECTORY": "", "BD2_GAME_VERSION": "", "BD2_BUNDLE_VERSION": "", "BD2_GAME_DATA_VERSION": ""}
if receipt, err := readGameReceipt(game); err == nil && gameReceiptMatches(game, receipt.Fingerprint) {
values["BD2_UPDATE_FINGERPRINT"] = receipt.Fingerprint
values["BD2_RESOURCE_FINGERPRINT"] = receipt.ResourceFingerprint
if receipt.ResourceFingerprint != "" && len(receipt.Files) > 0 {
values["BD2_RESOURCE_DIRECTORY"] = receipt.Resources
}
values["BD2_GAME_VERSION"], values["BD2_BUNDLE_VERSION"], values["BD2_GAME_DATA_VERSION"] = receipt.GameVersion, receipt.BundleVersion, receipt.GameDataVersion
}
result := make([]string, 0, len(environment)+len(values))
for _, entry := range environment {
key, _, _ := strings.Cut(entry, "=")
if _, replace := values[strings.ToUpper(key)]; !replace {
result = append(result, entry)
}
}
for key, value := range values {
result = append(result, key+"="+value)
}
return result
}
func (m *Manager) loadPackagedFingerprint() {
fp, err := release.LoadFingerprint(filepath.Join(m.options.Directory, release.FingerprintFileName), m.keys)
if err == nil {
m.fingerprint = fp
} else if !errors.Is(err, os.ErrNotExist) {
m.status.Error = err.Error()
m.fingerprintErr = err
}
}
func (m *Manager) fetchServerFingerprint(ctx context.Context, client *http.Client, origin, id string) error {
address, err := url.JoinPath(origin, "client", "update-fingerprint")
if err != nil {
return err
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil)
if err != nil {
return err
}
response, err := client.Do(request)
if err != nil {
return fmt.Errorf("fetch server update fingerprint: %w", err)
}
defer func() { _ = response.Body.Close() }()
if response.StatusCode != http.StatusOK {
return fmt.Errorf("server update fingerprint: HTTP %d", response.StatusCode)
}
raw, err := io.ReadAll(io.LimitReader(response.Body, (32<<20)+1))
if err != nil {
return err
}
if len(raw) > 32<<20 {
return errors.New("server update fingerprint exceeds size limit")
}
fp, err := release.VerifyFingerprint(raw, m.keys)
if err != nil {
return err
}
if fp.ID != id {
return errors.New("server update requirement changed; retry after the update finishes")
}
m.mu.Lock()
m.fingerprint = &fp
m.fingerprintErr = nil
m.mu.Unlock()
return nil
}
func clientUpdateRequired(current, target string) bool {
newer, err := release.Newer(current, target)
return err != nil || newer
}
func (m *Manager) clearServerRequirement() {
m.mu.Lock()
m.fingerprint = nil
m.mu.Unlock()
}
+85
View File
@@ -0,0 +1,85 @@
package update
import (
"context"
"crypto/sha256"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/release"
)
func TestGameReceiptRechecksContentWhenInstalledMetadataChanges(t *testing.T) {
root := t.TempDir()
path := filepath.Join(root, "resource.bundle")
if err := os.WriteFile(path, []byte("trusted"), 0600); err != nil {
t.Fatal(err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
receipt := gameReceipt{Fingerprint: "target", Files: []verifiedGameFile{{Path: path, Size: 7, Modified: info.ModTime().UnixNano(), SHA256: fmt.Sprintf("%x", sha256.Sum256([]byte("trusted")))}}}
if err := commonconfig.Save(filepath.Join(root, gameReceiptFile), receipt, commonconfig.WriteOptions{}); err != nil {
t.Fatal(err)
}
if !gameReceiptMatches(root, "target") {
t.Fatal("verified installation was not recognized")
}
if gameReceiptMatches(root, "different-target") {
t.Fatal("receipt accepted a different required fingerprint")
}
if err := os.WriteFile(path, []byte("corrupt"), 0600); err != nil {
t.Fatal(err)
}
changed := info.ModTime().Add(2 * time.Second)
if err := os.Chtimes(path, changed, changed); err != nil {
t.Fatal(err)
}
if gameReceiptMatches(root, "target") {
t.Fatal("same-length content corruption was trusted")
}
if err := os.WriteFile(path, []byte("trusted"), 0600); err != nil {
t.Fatal(err)
}
if err := os.Chtimes(path, changed, changed); err != nil {
t.Fatal(err)
}
if !gameReceiptMatches(root, "target") {
t.Fatal("unchanged verified bytes were rejected after a metadata-only change")
}
}
func TestServerOnlyFingerprintChangeReusesVerifiedGameResources(t *testing.T) {
root := t.TempDir()
path := filepath.Join(root, "resource.bundle")
if err := os.WriteFile(path, []byte("trusted"), 0600); err != nil {
t.Fatal(err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
resourceID := strings.Repeat("a", 64)
previous := gameReceipt{Fingerprint: strings.Repeat("1", 64), ResourceFingerprint: resourceID, GameVersion: "2.36.7", BundleVersion: "20261007175947", GameDataVersion: "20261008155037", Files: []verifiedGameFile{{Path: path, Size: 7, Modified: info.ModTime().UnixNano(), SHA256: fmt.Sprintf("%x", sha256.Sum256([]byte("trusted")))}}}
if err := commonconfig.Save(filepath.Join(root, gameReceiptFile), previous, commonconfig.WriteOptions{}); err != nil {
t.Fatal(err)
}
m := New(Options{Directory: t.TempDir()})
m.fingerprint = &release.Fingerprint{ID: strings.Repeat("2", 64), GameFingerprint: resourceID, RequireGameUpdate: true, Game: &release.GameResources{GameVersion: "2.36.7"}}
if err := m.ensureGame(context.Background(), root); err != nil {
t.Fatalf("unchanged resource identity required a game download or process inspection: %v", err)
}
actual, err := readGameReceipt(root)
if err != nil {
t.Fatal(err)
}
if actual.Fingerprint != m.fingerprint.ID || actual.ResourceFingerprint != resourceID || actual.GameVersion != previous.GameVersion || len(actual.Files) != 1 {
t.Fatalf("server-only update lost verified game state: %+v", actual)
}
}
+820
View File
@@ -0,0 +1,820 @@
// Package update keeps the launcher and its game plugins current. It checks
// the signed release manifest in the background, downloads only the files
// whose digests differ, and installs them without touching anything running:
// the launcher switches through a restart, and a plugin set is installed into
// each game instance only while that instance is closed.
package update
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"maps"
"net/http"
"net/url"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"time"
clientlayout "bd2server/internal/client/layout"
"bd2server/internal/client/plugin"
"bd2server/internal/client/setup"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/i18n"
"bd2server/internal/common/release"
"bd2server/internal/common/versionconfig"
)
// StoreFile describes the launcher's plugin store, plugins/plugins.json.
const StoreFile = "plugins.json"
// ManifestEnvironment overrides the built-in manifest URL.
const ManifestEnvironment = "BD2_UPDATE_MANIFEST_URL"
type Store struct {
Version string `json:"version"`
Files []StoredFile `json:"files"`
}
type StoredFile struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Version string `json:"version,omitempty"`
SHA256 string `json:"sha256"`
}
type Offer struct {
Version string `json:"version"`
Date string `json:"date,omitempty"`
Notes i18n.Text `json:"notes,omitempty"`
Bytes int64 `json:"bytes"`
Ready bool `json:"ready"`
}
type Status struct {
Enabled bool `json:"enabled"`
Checked time.Time `json:"checked,omitzero"`
Error string `json:"error,omitempty"`
Launcher *Offer `json:"launcher,omitempty"`
Plugins *Offer `json:"plugins,omitempty"`
Game *Offer `json:"game,omitempty"`
Busy string `json:"busy,omitempty"`
Done int64 `json:"done,omitempty"`
Total int64 `json:"total,omitempty"`
// Waiting lists game directories whose new plugins install on exit.
Waiting []string `json:"waiting,omitempty"`
Message *Message `json:"message,omitempty"`
}
// Message is a translation key with arguments, rendered by the launcher UI.
type Message struct {
Key string `json:"key"`
Args []string `json:"args,omitempty"`
}
func message(key string, args ...string) *Message { return &Message{Key: key, Args: args} }
type Options struct {
Versions versionconfig.Config
Directory string
Logger *slog.Logger
Client *http.Client
// Games returns the main game directory the launcher manages.
Games func() string
}
type Manager struct {
options Options
manifestURL string
keys []release.TrustedKey
operation sync.Mutex
envelope []byte
mu sync.Mutex
status Status
manifest *release.Manifest
fingerprint *release.Fingerprint
fingerprintErr error
gamePending map[string]bool
pending map[string]bool
}
func New(options Options) *Manager {
if options.Logger == nil {
options.Logger = slog.Default()
}
address := strings.TrimSpace(os.Getenv(ManifestEnvironment))
if address == "" {
address = release.BuiltinChannel().ManifestURL
}
m := &Manager{options: options, manifestURL: address, keys: release.BuiltinChannel().TrustedKeys, pending: map[string]bool{}, gamePending: map[string]bool{}}
m.status.Enabled = address != ""
m.loadPackagedFingerprint()
if result := TakeResult(options.Directory); result != nil {
if result.OK {
m.status.Message = message("update.launcher.switched", result.From, result.To)
} else {
m.status.Message = message("update.launcher.switch_failed", result.To, result.Message, result.From)
}
options.Logger.Info("launcher switch result", "from", result.From, "to", result.To, "ok", result.OK, "message", result.Message)
}
return m
}
func (m *Manager) Status() Status {
m.mu.Lock()
defer m.mu.Unlock()
out := m.status
cloneOffer := func(o *Offer) *Offer {
if o == nil {
return nil
}
out := *o
out.Notes = maps.Clone(o.Notes)
return &out
}
out.Launcher, out.Plugins, out.Game = cloneOffer(out.Launcher), cloneOffer(out.Plugins), cloneOffer(out.Game)
if out.Message != nil {
message := *out.Message
message.Args = slices.Clone(message.Args)
out.Message = &message
}
out.Waiting = nil
for game := range m.pending {
out.Waiting = append(out.Waiting, game)
}
for game := range m.gamePending {
if !m.pending[game] {
out.Waiting = append(out.Waiting, game)
}
}
slices.Sort(out.Waiting)
return out
}
// Busy reports a running download or installation; launches wait for it.
func (m *Manager) Busy() bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.status.Busy != ""
}
func (m *Manager) setBusy(value string) bool {
m.mu.Lock()
defer m.mu.Unlock()
if value != "" && m.status.Busy != "" {
return false
}
m.status.Busy, m.status.Done, m.status.Total = value, 0, 0
return true
}
func operationBusy() error {
return errors.New("Another update operation is in progress") //nolint:staticcheck // ST1005: shown to players
}
func (m *Manager) begin(busy string) bool {
if !m.operation.TryLock() {
return false
}
m.setBusy(busy)
return true
}
func (m *Manager) end() { m.setBusy(""); m.operation.Unlock() }
// Run checks shortly after start and then every six hours, downloads what
// is newer, installs a downloaded plugin set wherever no game runs, and
// installs the rest as each game instance exits.
func (m *Manager) Run(ctx context.Context) {
if !m.status.Enabled {
return
}
check := time.NewTimer(3 * time.Second)
defer check.Stop()
watch := time.NewTicker(5 * time.Second)
defer watch.Stop()
for {
select {
case <-ctx.Done():
return
case <-check.C:
m.refresh(ctx)
check.Reset(6 * time.Hour)
case <-watch.C:
m.installGameUpdates(ctx)
m.installWaiting()
}
}
}
func (m *Manager) refresh(ctx context.Context) {
if err := m.Check(ctx); err != nil {
m.options.Logger.Warn("update check failed", "error", err)
return
}
if err := m.Download(ctx); err != nil {
m.options.Logger.Warn("update download failed", "error", err)
return
}
if err := m.CommitGame(ctx); err != nil {
m.options.Logger.Warn("game resources not installed", "error", err)
}
if err := m.CommitPlugins(); err != nil {
m.options.Logger.Warn("plugin update not installed", "error", err)
}
}
// Check fetches the manifest and works out what this launcher lacks.
func (m *Manager) Check(ctx context.Context) error {
if !m.begin("checking") {
return operationBusy()
}
defer m.end()
fetchCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
manifest, envelope, err := release.FetchManifest(fetchCtx, m.options.Client, m.manifestURL, m.keys)
m.mu.Lock()
defer m.mu.Unlock()
m.status.Checked = time.Now().UTC()
if err != nil {
m.status.Error = err.Error()
return err
}
m.status.Error = ""
m.manifest = &manifest
if manifest.Fingerprint != nil {
m.fingerprint = manifest.Fingerprint
m.fingerprintErr = nil
}
m.status.Game = nil
if fp := manifest.Fingerprint; fp != nil && fp.RequireGameUpdate && fp.Game != nil {
for _, game := range m.instances() {
if !gameReceiptMatches(game, fp.ID) {
m.gamePending[game] = true
m.status.Game = &Offer{Version: fp.Game.GameVersion}
}
}
}
m.envelope = envelope
m.status.Launcher, m.status.Plugins = nil, nil
if c := manifest.Launcher; c != nil && newer(m.options.Versions.ClientVersion, c.Version) {
if files := m.missing(c.FilesFor(release.Platform()), m.options.Directory); len(files) != 0 {
m.status.Launcher = offer(c, files, m.launcherStaging(c.Version))
}
}
if c := manifest.Plugins; c != nil && !newer(c.Version, m.storeVersion()) {
if files := m.missing(c.Files, filepath.Join(m.options.Directory, "plugins")); len(files) != 0 || !m.storeMatches(c) {
m.status.Plugins = offer(c, files, m.pluginStaging(c.Version))
}
}
return nil
}
func newer(current, candidate string) bool {
ok, err := release.Newer(current, candidate)
return err == nil && ok
}
func offer(c *release.Component, files []release.File, staging string) *Offer {
o := &Offer{Version: c.Version, Date: c.Date, Notes: c.Notes, Ready: true}
for _, f := range files {
o.Bytes += f.Size
if !release.Matches(filepath.Join(staging, f.Name), f) {
o.Ready = false
}
}
return o
}
func (m *Manager) missing(files []release.File, directory string) []release.File {
var out []release.File
for _, f := range files {
if !release.Matches(filepath.Join(directory, f.Name), f) {
out = append(out, f)
}
}
return out
}
func (m *Manager) launcherStaging(version string) string {
return filepath.Join(m.options.Directory, ".update", "launcher", version)
}
func (m *Manager) pluginStaging(version string) string {
return filepath.Join(m.options.Directory, ".update", "plugins", version)
}
// ReadStore returns the launcher's plugin store description.
func ReadStore(directory string) (Store, error) {
var store Store
raw, err := os.ReadFile(filepath.Join(directory, "plugins", StoreFile))
if err != nil {
return store, err
}
return store, json.Unmarshal(raw, &store)
}
func (m *Manager) storeVersion() string {
store, err := ReadStore(m.options.Directory)
if err != nil || store.Version == "" {
return m.options.Versions.ClientVersion
}
return store.Version
}
func (m *Manager) storeMatches(component *release.Component) bool {
store, err := ReadStore(m.options.Directory)
if err != nil || store.Version != component.Version || len(store.Files) != len(component.Files) {
return false
}
for i, f := range component.Files {
have := store.Files[i]
if have.Name != f.Name || have.SHA256 != f.SHA256 || have.ID != f.ID || have.Version != f.Version {
return false
}
}
return true
}
// Download fetches every offered file that is not already staged.
func (m *Manager) Download(ctx context.Context) error {
if !m.begin("downloading") {
return operationBusy()
}
defer m.end()
m.mu.Lock()
manifest := m.manifest
launcher, plugins := m.status.Launcher, m.status.Plugins
m.mu.Unlock()
if manifest == nil || (launcher == nil && plugins == nil) {
return nil
}
type job struct {
files []release.File
staging string
offer *Offer
}
var jobs []job
var total int64
if launcher != nil && !launcher.Ready {
files := m.missing(manifest.Launcher.FilesFor(release.Platform()), m.options.Directory)
jobs = append(jobs, job{files, m.launcherStaging(manifest.Launcher.Version), launcher})
total += launcher.Bytes
}
if plugins != nil && !plugins.Ready {
files := m.missing(manifest.Plugins.Files, filepath.Join(m.options.Directory, "plugins"))
jobs = append(jobs, job{files, m.pluginStaging(manifest.Plugins.Version), plugins})
total += plugins.Bytes
}
m.mu.Lock()
m.status.Total = total
m.mu.Unlock()
var finished int64
for _, j := range jobs {
for _, f := range j.files {
_, err := release.Download(ctx, m.options.Client, m.manifestURL, f, j.staging, func(_ string, done, _ int64) {
m.mu.Lock()
m.status.Done = finished + done
m.mu.Unlock()
})
if err != nil {
return err
}
finished += f.Size
}
m.mu.Lock()
j.offer.Ready = true
m.mu.Unlock()
}
return nil
}
// CommitPlugins moves a downloaded plugin set into the launcher's store and
// installs it into every closed game instance; running ones wait.
func (m *Manager) CommitPlugins() error {
if !m.begin("installing") {
return operationBusy()
}
defer m.end()
m.mu.Lock()
manifest, plugins := m.manifest, m.status.Plugins
m.mu.Unlock()
if manifest == nil || plugins == nil || !plugins.Ready {
return nil
}
if err := m.replaceStore(manifest.Plugins); err != nil {
return err
}
m.mu.Lock()
m.status.Plugins = nil
m.mu.Unlock()
_ = os.RemoveAll(filepath.Join(m.options.Directory, ".update", "plugins"))
var waiting []string
for _, game := range m.instances() {
if running, err := m.gameRunning(game); err != nil || running {
waiting = append(waiting, game)
m.mu.Lock()
m.pending[game] = true
m.mu.Unlock()
continue
}
if err := m.ensurePlugins(game); err != nil {
m.mu.Lock()
m.pending[game] = true
m.mu.Unlock()
waiting = append(waiting, game)
m.options.Logger.Warn("plugin set not installed", "game", game, "error", err)
}
}
result := message("update.plugins.updated", manifest.Plugins.Version)
if len(waiting) != 0 {
result = message("update.plugins.updated_waiting", manifest.Plugins.Version)
}
m.mu.Lock()
m.status.Message = result
m.mu.Unlock()
m.options.Logger.Info("plugin store updated", "version", manifest.Plugins.Version, "waiting", waiting)
return nil
}
// replaceStore builds the complete new store beside the old one and swaps
// the directories, so the store always holds one consistent set.
func (m *Manager) replaceStore(c *release.Component) error {
current := filepath.Join(m.options.Directory, "plugins")
next := current + ".new"
previous := current + ".previous"
if err := os.RemoveAll(next); err != nil {
return err
}
if err := os.MkdirAll(next, 0o755); err != nil {
return err
}
defer func() { _ = os.RemoveAll(next) }()
store := Store{Version: c.Version}
for _, f := range c.Files {
source := filepath.Join(current, f.Name)
if !release.Matches(source, f) {
source = filepath.Join(m.pluginStaging(c.Version), f.Name)
if !release.Matches(source, f) {
return fmt.Errorf("plugin %s was not downloaded completely", f.Name)
}
}
if err := copyFile(source, filepath.Join(next, f.Name)); err != nil {
return err
}
if !release.Matches(filepath.Join(next, f.Name), f) {
return fmt.Errorf("plugin %s changed while copying", f.Name)
}
store.Files = append(store.Files, StoredFile{ID: f.ID, Name: f.Name, Version: f.Version, SHA256: f.SHA256})
}
if err := commonconfig.Save(filepath.Join(next, StoreFile), store, commonconfig.WriteOptions{}); err != nil {
return err
}
if err := os.RemoveAll(previous); err != nil {
return err
}
if err := os.Rename(current, previous); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
if err := os.Rename(next, current); err != nil {
if restoreErr := os.Rename(previous, current); restoreErr != nil && !errors.Is(restoreErr, os.ErrNotExist) {
return errors.Join(err, fmt.Errorf("restore plugin store: %w", restoreErr))
}
return err
}
return nil
}
// StoreSources lists the plugin files of the current store set.
func (m *Manager) StoreSources() ([]string, error) {
m.operation.Lock()
defer m.operation.Unlock()
return m.storeSources()
}
func (m *Manager) storeSources() ([]string, error) {
directory := filepath.Join(m.options.Directory, "plugins")
store, err := ReadStore(m.options.Directory)
if err != nil {
return nil, err
}
var sources []string
if len(store.Files) == 0 {
return nil, errors.New("plugin store contains no files")
}
for _, f := range store.Files {
if filepath.Base(f.Name) != f.Name || strings.ContainsAny(f.Name, `\:`) || filepath.Ext(f.Name) != ".dll" {
return nil, fmt.Errorf("invalid stored plugin %q", f.Name)
}
source := filepath.Join(directory, f.Name)
digest, err := release.HashFile(source)
if err != nil {
return nil, err
}
if digest != f.SHA256 {
return nil, fmt.Errorf("stored plugin %s failed verification", f.Name)
}
sources = append(sources, source)
}
return sources, nil
}
// EnsurePlugins installs the store set into a closed game instance when it
// differs from what that instance has.
func (m *Manager) EnsurePlugins(game string) error {
if !m.begin("installing") {
return operationBusy()
}
defer m.end()
return m.ensurePlugins(game)
}
func (m *Manager) ensurePlugins(game string) error {
sources, err := m.storeSources()
if errors.Is(err, os.ErrNotExist) {
return nil // development builds install plugins explicitly
}
if err != nil {
return err
}
if versions := m.Versions(game); versions.GameVersion != "" {
store, err := ReadStore(m.options.Directory)
if err != nil {
return err
}
releaseVersion, err := release.ParseVersion(store.Version)
if err != nil {
return err
}
if releaseVersion.GameVersion() != versions.GameVersion {
return errors.New("the downloaded plugins require the game update to finish first")
}
if _, err := setup.Inspect(game, versions); err != nil {
return err
}
}
if installed, err := plugin.Installed(game, sources); err != nil || installed {
if installed {
m.mu.Lock()
delete(m.pending, game)
m.mu.Unlock()
}
return err
}
if running, err := m.gameRunning(game); err != nil {
return err
} else if running {
return errors.New("The game is running; its plugins update after it exits") //nolint:staticcheck // ST1005: shown to players
}
_, err = plugin.InstallSet(game, sources)
if err == nil {
m.mu.Lock()
delete(m.pending, game)
m.mu.Unlock()
m.options.Logger.Info("plugin set installed", "game", game)
}
return err
}
func (m *Manager) installWaiting() {
if !m.begin("installing") {
return
}
defer m.end()
m.mu.Lock()
var games []string
for game := range m.pending {
games = append(games, game)
}
m.mu.Unlock()
for _, game := range games {
if running, err := m.gameRunning(game); err != nil || running {
continue
}
if err := m.ensurePlugins(game); err != nil {
m.options.Logger.Warn("plugin set not installed after game exit", "game", game, "error", err)
continue
}
m.mu.Lock()
m.status.Message = message("update.plugins.applied_after_exit")
m.mu.Unlock()
}
}
func (m *Manager) gameRunning(game string) (bool, error) {
installation, err := clientlayout.Resolve(game)
if err != nil {
return false, err
}
running, err := runningExecutables()
if err != nil {
return false, err
}
return running[executableKey(installation.Executable)], nil
}
// instances lists the main game directory and the second clients prepared
// beside it, which share downloads but are installed separately.
func (m *Manager) instances() []string {
if m.options.Games == nil {
return nil
}
main := m.options.Games()
installation, err := clientlayout.Resolve(main)
if err != nil {
return nil
}
games := []string{main}
parent := filepath.Join(filepath.Dir(installation.Root), "BD2 Instances")
entries, _ := os.ReadDir(parent)
for _, entry := range entries {
candidate := filepath.Join(parent, entry.Name(), "game")
if installation.Kind == clientlayout.MacOS {
candidate = filepath.Join(candidate, filepath.Base(installation.Root))
}
if _, err := clientlayout.Resolve(candidate); err == nil {
games = append(games, candidate)
}
}
return games
}
// ApplyLauncher switches to the downloaded launcher and restarts it. On
// Windows a copy of the launcher performs the switch after quit is called.
func (m *Manager) ApplyLauncher(quit func()) error {
if !m.begin("restarting") {
return operationBusy()
}
defer m.end()
m.mu.Lock()
manifest, launcher := m.manifest, m.status.Launcher
m.mu.Unlock()
if manifest == nil || launcher == nil {
return errors.New("No launcher update is available") //nolint:staticcheck // ST1005: shown to players
}
if !launcher.Ready {
return errors.New("The launcher update has not finished downloading") //nolint:staticcheck // ST1005: shown to players
}
staging := m.launcherStaging(launcher.Version)
current := m.options.Versions.ClientVersion
if err := m.prepareLauncher(staging, manifest.Launcher); err != nil {
return err
}
if !helperRequired {
if err := switchLauncher(staging, m.options.Directory, current, launcher.Version, m.keys); err != nil {
return err
}
if err := writeResult(m.options.Directory, Result{From: current, To: launcher.Version, OK: true, At: time.Now().UTC()}); err != nil {
return err
}
if err := startDetached(filepath.Join(m.options.Directory, launcherExecutable())); err != nil {
return err
}
quit()
return nil
}
helper := filepath.Join(m.options.Directory, ".update", "helper", launcherExecutable())
source, err := os.Executable()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(helper), 0o755); err != nil {
return err
}
if err := copyFile(source, helper); err != nil {
return fmt.Errorf("prepare launcher updater: %w", err)
}
if err := startDetached(helper, HelperFlag, staging, m.options.Directory, fmt.Sprint(os.Getpid()), current, launcher.Version); err != nil {
return err
}
m.options.Logger.Info("launcher updater started; exiting", "from", current, "to", launcher.Version)
quit()
return nil
}
// Compatibility is what a server reports at /client/compatibility.
type Compatibility struct {
ServerVersion string `json:"server_version"`
GameVersion string `json:"game_version"`
MinimumPlugins map[string]string `json:"minimum_plugins"`
LoginsClosed bool `json:"logins_closed"`
Fingerprint *release.Fingerprint `json:"fingerprint,omitempty"`
FingerprintURL string `json:"fingerprint_url,omitempty"`
}
// CheckServer refuses a launch when the server needs newer plugins than the
// store holds. Servers without the endpoint impose no requirement.
func (m *Manager) CheckServer(ctx context.Context, client *http.Client, origin string) error {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
store, err := ReadStore(m.options.Directory)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
address, err := url.JoinPath(origin, "client", "compatibility")
if err != nil {
return err
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil)
if err != nil {
return err
}
if client == nil {
client = http.DefaultClient
}
response, err := client.Do(request)
if err != nil {
m.clearServerRequirement()
return nil // the resource check reports unreachable servers
}
defer func() { _ = response.Body.Close() }()
if response.StatusCode != http.StatusOK {
m.clearServerRequirement()
return nil
}
var compat Compatibility
if err := json.NewDecoder(io.LimitReader(response.Body, 16<<10)).Decode(&compat); err != nil {
m.clearServerRequirement()
return nil
}
if compat.LoginsClosed {
return errors.New("The server is updating; try again after it finishes") //nolint:staticcheck // ST1005: shown to players
}
if compat.Fingerprint != nil {
m.mu.Lock()
known := m.fingerprint != nil && m.fingerprint.ID == compat.Fingerprint.ID
m.mu.Unlock()
if !known {
if err := m.fetchServerFingerprint(ctx, client, origin, compat.Fingerprint.ID); err != nil {
return err
}
}
} else {
m.clearServerRequirement()
}
versions := m.options.Versions
m.mu.Lock()
fp := m.fingerprint
m.mu.Unlock()
if fp != nil && fp.RequireClientUpdate && clientUpdateRequired(versions.ClientVersion, fp.ClientVersion) {
return fmt.Errorf("update the launcher to %s before launching", fp.ClientVersion)
}
if fp != nil && fp.RequireClientUpdate {
compat.MinimumPlugins = fp.MinimumPlugins
}
if compat.GameVersion != "" && versions.GameVersion != "" && compat.GameVersion != versions.GameVersion && (fp == nil || fp.Game == nil || fp.Game.GameVersion != compat.GameVersion) {
return fmt.Errorf("Server game version %s does not match client game version %s", compat.GameVersion, versions.GameVersion) //nolint:staticcheck // ST1005: shown to players
}
installed := map[string]string{}
for _, f := range store.Files {
if f.ID != "" {
installed[f.ID] = f.Version
}
}
var stale []string
for id, minimum := range compat.MinimumPlugins {
current := installed[id]
a, aErr := release.ParseVersion(current)
b, bErr := release.ParseVersion(minimum)
if aErr != nil || bErr != nil || a.Kind != b.Kind || a.HasGame != b.HasGame || a.Compare(b) < 0 {
stale = append(stale, fmt.Sprintf("%s %s (needs %s)", id, current, minimum))
}
}
slices.Sort(stale)
if len(stale) != 0 {
return fmt.Errorf("Server %s no longer accepts these plugins: %s. Update the plugins in the launcher first", compat.ServerVersion, strings.Join(stale, ", ")) //nolint:staticcheck // ST1005: shown to players
}
return nil
}
// WithLaunch keeps updates excluded until the prepared game process has started.
func (m *Manager) WithLaunch(ctx context.Context, client *http.Client, game, origin string, launch func() error) error {
if !m.begin("preparing") {
return operationBusy()
}
defer m.end()
if err := m.CheckServer(ctx, client, origin); err != nil {
return err
}
if err := m.ensureGame(ctx, game); err != nil {
return err
}
if running, err := m.gameRunning(game); err != nil {
return err
} else if !running {
if err := m.ensurePlugins(game); err != nil {
return err
}
}
return launch()
}
+317
View File
@@ -0,0 +1,317 @@
package update
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"bd2server/internal/common/release"
"bd2server/internal/common/versionconfig"
)
func TestDownloadPinsManifestAndExcludesCompetingOperations(t *testing.T) {
root := t.TempDir()
component := &release.Component{Version: "2.36.7+client.0.2.0", Files: []release.File{releaseFile(launcherExecutable(), "new executable")}}
raw, keys := signedFixture(t, component, nil)
entered, resume := make(chan struct{}), make(chan struct{})
var unblock sync.Once
var checks atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/manifest.json" {
checks.Add(1)
_, _ = w.Write(raw)
return
}
close(entered)
<-resume
_, _ = w.Write([]byte("new executable"))
}))
defer server.Close()
defer unblock.Do(func() { close(resume) })
m := New(Options{Directory: root, Versions: versionconfig.Config{ClientVersion: "2.36.7+client.0.1.0"}})
m.manifestURL, m.keys = server.URL+"/manifest.json", keys
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := m.Check(ctx); err != nil {
t.Fatal(err)
}
completed := make(chan error, 1)
go func() { completed <- m.Download(ctx) }()
select {
case <-entered:
case <-ctx.Done():
t.Fatal("download never started")
}
for name, action := range map[string]func() error{
"check": func() error { return m.Check(ctx) },
"download": func() error { return m.Download(ctx) },
"commit": m.CommitPlugins,
"apply": func() error { return m.ApplyLauncher(func() { t.Error("quit during another operation") }) },
} {
if err := action(); err == nil || !strings.Contains(err.Error(), "in progress") {
t.Errorf("%s competed with a download: %v", name, err)
}
}
if checks.Load() != 1 {
t.Errorf("competing check fetched a new manifest: %d requests", checks.Load())
}
snapshot := m.Status()
snapshot.Launcher.Version, snapshot.Launcher.Ready = "mutated", true
if actual := m.Status().Launcher; actual.Version != component.Version || actual.Ready {
t.Errorf("status caller changed active offer: %+v", actual)
}
unblock.Do(func() { close(resume) })
if err := <-completed; err != nil {
t.Fatal(err)
}
if state := m.Status(); state.Busy != "" || !state.Launcher.Ready {
t.Fatalf("download did not finish its original offer: %+v", state)
}
writeFixture(t, filepath.Join(m.launcherStaging(component.Version), launcherExecutable()), "tampered bytes")
quit := false
if err := m.ApplyLauncher(func() { quit = true }); err == nil || quit {
t.Fatalf("accepted staged file changed after Ready: quit=%v, err=%v", quit, err)
}
}
func TestPluginOnlyRemovalStillOffersAndAppliesTheNewSet(t *testing.T) {
root := t.TempDir()
keep := releaseFile("BD2LoginUI.dll", "same login")
component := &release.Component{Version: "2.36.7+client.0.2.0", Files: []release.File{keep}}
raw, keys := signedFixture(t, nil, component)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write(raw) }))
defer server.Close()
m := New(Options{Directory: root, Versions: versionconfig.Config{ClientVersion: "2.36.7+client.0.1.0"}})
m.manifestURL, m.keys = server.URL+"/manifest.json", keys
writeFixture(t, filepath.Join(root, "plugins", keep.Name), "same login")
writeFixture(t, filepath.Join(root, "plugins", "BD2FChat.dll"), "old chat")
store := Store{Version: "2.36.7+client.0.1.0", Files: []StoredFile{{Name: keep.Name, SHA256: keep.SHA256}, {Name: "BD2FChat.dll"}}}
encoded, err := json.Marshal(store)
if err != nil {
t.Fatal(err)
}
writeFixture(t, filepath.Join(root, "plugins", StoreFile), string(encoded))
if err := m.Check(context.Background()); err != nil {
t.Fatal(err)
}
if state := m.Status(); state.Plugins == nil || !state.Plugins.Ready || state.Plugins.Bytes != 0 {
t.Fatalf("removing a plugin should require no new download: %+v", state)
}
if err := m.CommitPlugins(); err != nil {
t.Fatal(err)
}
assertContent(t, filepath.Join(root, "plugins", keep.Name), "same login")
if _, err := os.Stat(filepath.Join(root, "plugins", "BD2FChat.dll")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("dropped plugin remains: %v", err)
}
store, err = ReadStore(root)
if err != nil || store.Version != component.Version || len(store.Files) != 1 {
t.Fatalf("store = %+v, %v", store, err)
}
}
func TestUpdateWaitingProcess(t *testing.T) {
if marker := os.Getenv("BD2_UPDATE_TEST_PROCESS_MARKER"); marker != "" {
if err := os.WriteFile(marker, []byte("ready"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := io.Copy(io.Discard, os.Stdin); err != nil {
t.Fatal(err)
}
}
}
func startWaitingProcess(t *testing.T, path string) (int, func()) {
t.Helper()
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := copyFile(executable, path); err != nil {
t.Fatal(err)
}
marker := filepath.Join(t.TempDir(), "child-ready")
child := exec.Command(path, "-test.run=^TestUpdateWaitingProcess$")
child.Env = append(os.Environ(), "BD2_UPDATE_TEST_PROCESS_MARKER="+marker)
input, err := child.StdinPipe()
if err != nil {
t.Fatal(err)
}
if err := child.Start(); err != nil {
_ = input.Close()
t.Fatal(err)
}
waited := make(chan error, 1)
go func() { waited <- child.Wait() }()
var once sync.Once
stop := func() {
once.Do(func() {
_ = input.Close()
select {
case err := <-waited:
if err != nil {
t.Errorf("fixture process exited unsuccessfully: %v", err)
}
case <-time.After(10 * time.Second):
_ = child.Process.Kill()
<-waited
t.Error("fixture process did not exit after stdin closed")
}
})
}
t.Cleanup(stop)
deadline := time.Now().Add(10 * time.Second)
for {
if _, err := os.Stat(marker); err == nil {
break
}
if time.Now().After(deadline) {
t.Fatal("fixture process failed to start")
}
time.Sleep(10 * time.Millisecond)
}
return child.Process.Pid, stop
}
func TestPluginUpdateWaitsForRunningGameExitAndPreservesPlayerConfig(t *testing.T) {
root := t.TempDir()
game := filepath.Join(root, "game")
writeFixture(t, filepath.Join(game, "BrownDust II_Data", "resources.assets"), "fixture")
writeFixture(t, filepath.Join(game, "BepInEx", "core", "BepInEx.dll"), "fixture")
pluginPath := filepath.Join(game, "BepInEx", "plugins", "BD2LoginUI.dll")
writeFixture(t, pluginPath, "old login")
configPath := filepath.Join(game, "BepInEx", "config", "BD2LoginUI.cfg")
writeFixture(t, configPath, "player settings")
_, stopGame := startWaitingProcess(t, filepath.Join(game, "BrownDust II.exe"))
f := releaseFile("BD2LoginUI.dll", "new login")
component := &release.Component{Version: "2.36.7+client.0.2.0", Files: []release.File{f}}
raw, keys := signedFixture(t, nil, component)
var downloads atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/manifest.json":
_, _ = w.Write(raw)
case "/" + f.Name:
downloads.Add(1)
_, _ = w.Write([]byte("new login"))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
m := New(Options{Directory: root, Games: func() string { return game }, Versions: versionconfig.Config{ClientVersion: "2.36.7+client.0.1.0"}})
m.manifestURL, m.keys = server.URL+"/manifest.json", keys
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := m.Check(ctx); err != nil {
t.Fatal(err)
}
if offer := m.Status().Plugins; offer == nil || offer.Ready || offer.Version != component.Version {
t.Fatalf("signed plugin manifest did not offer a download: %+v", offer)
}
if err := m.Download(ctx); err != nil {
t.Fatal(err)
}
if downloads.Load() != 1 {
t.Fatalf("plugin artifact downloads = %d; want 1", downloads.Load())
}
assertContent(t, filepath.Join(m.pluginStaging(component.Version), f.Name), "new login")
if err := m.CommitPlugins(); err != nil {
t.Fatal(err)
}
assertContent(t, filepath.Join(root, "plugins", f.Name), "new login")
store, err := ReadStore(root)
if err != nil || store.Version != component.Version || len(store.Files) != 1 || store.Files[0].SHA256 != f.SHA256 {
t.Fatalf("committed plugin store = %+v, %v", store, err)
}
if waiting := m.Status().Waiting; len(waiting) != 1 || waiting[0] != game {
t.Fatalf("running game was not queued for installation: %v", waiting)
}
if err := m.EnsurePlugins(game); err == nil || !strings.Contains(err.Error(), "game is running") {
t.Fatalf("installation did not reject the running game: %v", err)
}
m.installWaiting()
assertContent(t, pluginPath, "old login")
assertContent(t, configPath, "player settings")
if waiting := m.Status().Waiting; len(waiting) != 1 || waiting[0] != game {
t.Fatalf("running game lost its pending installation: %v", waiting)
}
stopGame()
m.installWaiting()
assertContent(t, pluginPath, "new login")
assertContent(t, configPath, "player settings")
if waiting := m.Status().Waiting; len(waiting) != 0 {
t.Fatalf("installed game remains pending after exit: %v", waiting)
}
}
func TestWithLaunchKeepsUpdatesExcludedThroughProcessStartAndReturnsLaunchError(t *testing.T) {
root := t.TempDir()
game := filepath.Join(root, "game")
writeFixture(t, filepath.Join(game, "BrownDust II.exe"), "fixture")
writeFixture(t, filepath.Join(game, "BrownDust II_Data", "resources.assets"), "fixture")
server := httptest.NewServer(http.NotFoundHandler())
defer server.Close()
m := New(Options{Directory: root})
failure := errors.New("process start failed")
called := false
err := m.WithLaunch(context.Background(), server.Client(), game, server.URL, func() error {
called = true
if !m.Busy() {
t.Error("operation was released before process start")
}
if err := m.CommitPlugins(); err == nil {
t.Error("plugin commit started during process launch")
}
return failure
})
if !called || !errors.Is(err, failure) {
t.Fatalf("launch callback = %v, %v", called, err)
}
if m.Busy() {
t.Error("failed process launch left updates blocked")
}
if err := m.CommitPlugins(); err != nil {
t.Fatalf("updates cannot resume after launch failure: %v", err)
}
}
func TestServerCompatibilityRejectsMissingPluginsAndTemporaryLoginClosure(t *testing.T) {
for _, scenario := range []struct {
name string
compat Compatibility
version string
expected string
}{
{name: "missing plugin", compat: Compatibility{ServerVersion: "2.36.7+server.0.2.0", MinimumPlugins: map[string]string{"login-ui": "1.2.0"}}, expected: "login-ui"},
{name: "login closed", compat: Compatibility{LoginsClosed: true}, expected: "server is updating"},
{name: "game version", compat: Compatibility{GameVersion: "2.37.0"}, version: "2.36.7", expected: "does not match"},
} {
t.Run(scenario.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if err := json.NewEncoder(w).Encode(scenario.compat); err != nil {
t.Error(err)
}
}))
defer server.Close()
m := New(Options{Directory: t.TempDir(), Versions: versionconfig.Config{GameVersion: scenario.version}})
if err := m.CheckServer(context.Background(), server.Client(), server.URL); err == nil || !strings.Contains(err.Error(), scenario.expected) {
t.Fatalf("server compatibility accepted incompatible launch: %v", err)
}
})
}
}
@@ -0,0 +1,60 @@
//go:build !windows
package update
import (
"bufio"
"bytes"
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"time"
)
// runningExecutables lists the full executable paths of running processes.
// On macOS ps reports the path inside the application bundle.
func runningExecutables() (map[string]bool, error) {
output, err := exec.Command("ps", "-axww", "-o", "comm=").Output()
if err != nil {
return nil, err
}
out := map[string]bool{}
scanner := bufio.NewScanner(bytes.NewReader(output))
for scanner.Scan() {
if line := strings.TrimSpace(scanner.Text()); line != "" {
out[executableKey(line)] = true
}
}
return out, scanner.Err()
}
func executableKey(path string) string { return filepath.Clean(path) }
func waitForExit(pid int, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
process, err := os.FindProcess(pid)
if err != nil || process.Signal(syscall.Signal(0)) != nil {
return nil
}
time.Sleep(200 * time.Millisecond)
}
return errors.New("the launcher did not exit in time")
}
func startDetached(name string, args ...string) error {
command := exec.Command(name, args...)
command.Dir = filepath.Dir(name)
command.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if err := command.Start(); err != nil {
return err
}
return command.Process.Release()
}
// helperRequired: Unix renames over a running executable safely, so the
// launcher switches its own files and starts the new copy directly.
const helperRequired = false
@@ -0,0 +1,95 @@
//go:build windows
package update
import (
"errors"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"time"
"unsafe"
"golang.org/x/sys/windows"
)
// runningExecutables returns the full image paths of running processes,
// lower-cased so the main client and a second instance stay distinct even
// though both run "BrownDust II.exe".
func runningExecutables() (map[string]bool, error) {
snapshot, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0)
if err != nil {
return nil, err
}
defer func() { _ = windows.CloseHandle(snapshot) }()
entry := windows.ProcessEntry32{Size: uint32(unsafe.Sizeof(windows.ProcessEntry32{}))}
if err := windows.Process32First(snapshot, &entry); err != nil {
return nil, err
}
out := map[string]bool{}
for {
if path, ok := imagePath(entry.ProcessID); ok {
out[strings.ToLower(filepath.Clean(path))] = true
}
if err := windows.Process32Next(snapshot, &entry); err != nil {
if errors.Is(err, windows.ERROR_NO_MORE_FILES) {
return out, nil
}
return nil, err
}
}
}
func imagePath(pid uint32) (string, bool) {
handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid)
if err != nil {
return "", false
}
defer func() { _ = windows.CloseHandle(handle) }()
buffer := make([]uint16, windows.MAX_LONG_PATH)
size := uint32(len(buffer))
if err := windows.QueryFullProcessImageName(handle, 0, &buffer[0], &size); err != nil {
return "", false
}
return windows.UTF16ToString(buffer[:size]), true
}
func executableKey(path string) string { return strings.ToLower(filepath.Clean(path)) }
// waitForExit blocks until pid has exited or timeout passes.
func waitForExit(pid int, timeout time.Duration) error {
handle, err := windows.OpenProcess(windows.SYNCHRONIZE, false, uint32(pid))
if err != nil {
if errors.Is(err, windows.ERROR_INVALID_PARAMETER) {
return nil
}
return err
}
defer func() { _ = windows.CloseHandle(handle) }()
event, err := windows.WaitForSingleObject(handle, uint32(timeout/time.Millisecond))
if err != nil {
return err
}
if event == uint32(windows.WAIT_TIMEOUT) {
return errors.New("the launcher did not exit in time")
}
return nil
}
// startDetached starts a process that outlives the launcher.
func startDetached(name string, args ...string) error {
command := exec.Command(name, args...)
command.Dir = filepath.Dir(name)
command.SysProcAttr = &syscall.SysProcAttr{CreationFlags: windows.DETACHED_PROCESS | windows.CREATE_NEW_PROCESS_GROUP}
command.Env = os.Environ()
if err := command.Start(); err != nil {
return err
}
return command.Process.Release()
}
// helperRequired: Windows cannot replace a running executable, so a copy of
// the launcher finishes the switch after this process exits.
const helperRequired = true
+252
View File
@@ -0,0 +1,252 @@
package update
import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"time"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/release"
)
// HelperFlag starts bd2client as the small updater that finishes a launcher
// switch after the running launcher has exited.
const HelperFlag = "--apply-launcher-update"
const resultFile = "result.json"
const launcherManifestFile = "manifest.json"
// Result is what the next launcher start reports about a launcher switch.
type Result struct {
From string `json:"from"`
To string `json:"to"`
OK bool `json:"ok"`
Message string `json:"message"`
At time.Time `json:"at"`
}
func launcherExecutable() string {
if runtime.GOOS == "windows" {
return "bd2client.exe"
}
return "bd2client"
}
// RunHelper is the entry point for HelperFlag: staging target pid from to.
func RunHelper(args []string) error {
return runHelper(args, release.BuiltinChannel().TrustedKeys, startDetached)
}
func runHelper(args []string, keys []release.TrustedKey, start func(string, ...string) error) error {
if len(args) != 5 {
return errors.New("usage: bd2client --apply-launcher-update STAGING TARGET PID FROM TO")
}
staging, target, from, to := args[0], args[1], args[3], args[4]
pid, err := strconv.Atoi(args[2])
if err != nil || pid <= 0 {
return errors.New("invalid launcher process ID")
}
result := Result{From: from, To: to, At: time.Now().UTC()}
if err := waitForExit(pid, time.Minute); err != nil {
result.Message = err.Error()
return errors.Join(err, writeResult(target, result))
} else if err := switchLauncher(staging, target, from, to, keys); err != nil {
result.Message = err.Error()
} else {
result.OK = true
}
recordErr := writeResult(target, result)
startErr := start(filepath.Join(target, launcherExecutable()))
var switchErr error
if !result.OK {
switchErr = errors.New(result.Message)
}
return errors.Join(switchErr, recordErr, startErr)
}
func (m *Manager) prepareLauncher(staging string, component *release.Component) error {
if err := os.MkdirAll(staging, 0o755); err != nil {
return err
}
for _, f := range component.FilesFor(release.Platform()) {
staged := filepath.Join(staging, f.Name)
if !release.Matches(staged, f) {
current := filepath.Join(m.options.Directory, f.Name)
if !release.Matches(current, f) {
return fmt.Errorf("launcher %s failed verification", f.Name)
}
if err := copyFile(current, staged); err != nil {
return err
}
if !release.Matches(staged, f) {
return fmt.Errorf("launcher %s changed while staging", f.Name)
}
}
}
if runtime.GOOS != "windows" {
if err := os.Chmod(filepath.Join(staging, launcherExecutable()), 0o755); err != nil {
return err
}
}
return commonconfig.WriteFile(filepath.Join(staging, launcherManifestFile), m.envelope)
}
func launcherFiles(staging, to string, keys []release.TrustedKey) ([]release.File, error) {
raw, err := os.ReadFile(filepath.Join(staging, launcherManifestFile))
if err != nil {
return nil, err
}
manifest, err := release.Verify(raw, keys)
if err != nil {
return nil, err
}
if manifest.Channel != release.BuiltinChannel().Name || manifest.Launcher == nil || manifest.Launcher.Version != to {
return nil, errors.New("launcher manifest does not match this update")
}
files := manifest.Launcher.FilesFor(release.Platform())
if !slices.ContainsFunc(files, func(f release.File) bool { return f.Name == launcherExecutable() }) {
return nil, errors.New("launcher manifest does not contain the executable")
}
for _, f := range files {
if !release.Matches(filepath.Join(staging, f.Name), f) {
return nil, fmt.Errorf("launcher %s failed verification", f.Name)
}
}
return files, nil
}
// switchLauncher verifies the signed set again before replacing any files.
func switchLauncher(staging, target, from, to string, keys []release.TrustedKey) error {
if version, err := release.ParseVersion(from); err != nil || version.Kind != "client" {
return errors.New("invalid previous launcher version")
}
files, err := launcherFiles(staging, to, keys)
if err != nil {
return err
}
rollback := filepath.Join(target, ".update", "rollback", from)
if err := os.MkdirAll(rollback, 0o755); err != nil {
return err
}
transaction, err := os.MkdirTemp(rollback, "switch-*")
if err != nil {
return err
}
type move struct{ name, backup string }
var done []move
undo := func(cause error) error {
var failures []error
for _, m := range slices.Backward(done) {
current := filepath.Join(target, m.name)
if m.backup != "" {
if err := commonconfig.ReplaceFile(m.backup, current); err != nil {
failures = append(failures, fmt.Errorf("restore %s: %w", m.name, err))
}
} else if err := os.Remove(current); err != nil && !errors.Is(err, os.ErrNotExist) {
failures = append(failures, err)
}
}
if len(failures) != 0 {
return fmt.Errorf("launcher replacement failed; rollback incomplete (backups in %s): %w", transaction, errors.Join(append([]error{cause}, failures...)...))
}
_ = os.RemoveAll(transaction)
return fmt.Errorf("launcher replacement failed; previous version restored: %w", cause)
}
for _, f := range files {
current := filepath.Join(target, f.Name)
temporary, err := os.CreateTemp(target, ".launcher-*.new")
if err != nil {
return undo(err)
}
name := temporary.Name()
if err := temporary.Close(); err != nil {
_ = os.Remove(name)
return undo(err)
}
if err := copyFile(filepath.Join(staging, f.Name), name); err != nil {
_ = os.Remove(name)
return undo(err)
}
if !release.Matches(name, f) {
_ = os.Remove(name)
return undo(fmt.Errorf("launcher %s changed during installation", f.Name))
}
m := move{name: f.Name}
info, err := os.Lstat(current)
if err == nil {
if !info.Mode().IsRegular() {
_ = os.Remove(name)
return undo(fmt.Errorf("launcher target %s is not a regular file", current))
}
m.backup = filepath.Join(transaction, f.Name)
if err := os.Rename(current, m.backup); err != nil {
_ = os.Remove(name)
return undo(err)
}
} else if !errors.Is(err, os.ErrNotExist) {
_ = os.Remove(name)
return undo(err)
}
done = append(done, m)
if err := commonconfig.ReplaceFile(name, current); err != nil {
_ = os.Remove(name)
return undo(err)
}
}
return nil
}
func copyFile(source, target string) error {
in, err := os.Open(source)
if err != nil {
return err
}
defer func() { _ = in.Close() }()
info, err := in.Stat()
if err != nil {
return err
}
out, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, info.Mode().Perm()|0o600)
if err != nil {
return err
}
if err := out.Chmod(info.Mode().Perm() | 0o600); err != nil {
_ = out.Close()
return err
}
if _, err := io.Copy(out, in); err != nil {
_ = out.Close()
return err
}
if err := out.Sync(); err != nil {
_ = out.Close()
return err
}
return out.Close()
}
func writeResult(target string, result Result) error {
return commonconfig.Save(filepath.Join(target, ".update", resultFile), result, commonconfig.WriteOptions{})
}
// TakeResult returns and clears the outcome of the last launcher switch.
func TakeResult(target string) *Result {
path := filepath.Join(target, ".update", resultFile)
raw, err := os.ReadFile(path)
if err != nil {
return nil
}
_ = os.Remove(path)
var result Result
if json.Unmarshal(raw, &result) != nil {
return nil
}
return &result
}
@@ -0,0 +1,226 @@
package update
import (
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"bd2server/internal/common/release"
)
func writeFixture(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o700); err != nil {
t.Fatal(err)
}
}
func releaseFile(name, content string) release.File {
digest := sha256.Sum256([]byte(content))
return release.File{Name: name, Size: int64(len(content)), SHA256: hex.EncodeToString(digest[:]), URL: "/" + name}
}
func signedFixture(t *testing.T, launcher, plugins *release.Component) ([]byte, []release.TrustedKey) {
t.Helper()
public, private, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
key := release.TrustedKey{ID: release.KeyID(public), PublicKey: base64.StdEncoding.EncodeToString(public)}
manifest := release.Manifest{Schema: release.SchemaVersion, Channel: release.BuiltinChannel().Name, PublishedAt: time.Now().UTC(), Commit: strings.Repeat("a", 40), Launcher: launcher, Plugins: plugins}
payload, err := json.Marshal(manifest)
if err != nil {
t.Fatal(err)
}
signature := ed25519.Sign(private, append([]byte("bd2-release-manifest-v1\n"), payload...))
raw, err := json.Marshal(release.Envelope{KeyID: key.ID, Signature: base64.StdEncoding.EncodeToString(signature), Manifest: payload})
if err != nil {
t.Fatal(err)
}
return raw, []release.TrustedKey{key}
}
func assertContent(t *testing.T, path, expected string) {
t.Helper()
raw, err := os.ReadFile(path)
if err != nil || string(raw) != expected {
t.Errorf("%s = %q, %v; want %q", path, raw, err, expected)
}
}
func TestRunHelperWaitsForOldLauncherBeforeReplacementResultAndRestart(t *testing.T) {
root := t.TempDir()
target, staging := filepath.Join(root, "installed"), filepath.Join(root, "staged")
launcherPath := filepath.Join(target, launcherExecutable())
pid, stopLauncher := startWaitingProcess(t, launcherPath)
oldDigest, err := release.HashFile(launcherPath)
if err != nil {
t.Fatal(err)
}
writeFixture(t, filepath.Join(target, "runtime.dat"), "old runtime")
from := "2.36.7+client.0.1.0"
component := &release.Component{Version: "2.36.7+client.0.2.0", Files: []release.File{releaseFile(launcherExecutable(), "new executable"), releaseFile("runtime.dat", "new runtime")}}
raw, keys := signedFixture(t, component, nil)
writeFixture(t, filepath.Join(staging, launcherManifestFile), string(raw))
writeFixture(t, filepath.Join(staging, launcherExecutable()), "new executable")
writeFixture(t, filepath.Join(staging, "runtime.dat"), "new runtime")
started := make(chan string, 1)
start := func(path string, args ...string) error {
if len(args) != 0 {
return fmt.Errorf("unexpected launcher arguments: %v", args)
}
for _, f := range component.Files {
if !release.Matches(filepath.Join(target, f.Name), f) {
return fmt.Errorf("restart preceded replacement of %s", f.Name)
}
}
raw, err := os.ReadFile(filepath.Join(target, ".update", resultFile))
if err != nil {
return fmt.Errorf("restart preceded result recording: %w", err)
}
var result Result
if err := json.Unmarshal(raw, &result); err != nil {
return err
}
if !result.OK || result.From != from || result.To != component.Version || result.At.IsZero() {
return fmt.Errorf("restart saw invalid switch result: %+v", result)
}
started <- path
return nil
}
completed := make(chan struct{})
var helperErr error
go func() {
helperErr = runHelper([]string{staging, target, strconv.Itoa(pid), from, component.Version}, keys, start)
close(completed)
}()
t.Cleanup(func() {
stopLauncher()
select {
case <-completed:
case <-time.After(10 * time.Second):
t.Error("updater did not finish after fixture launcher exit")
}
})
select {
case <-completed:
t.Fatalf("updater finished while the old launcher was still running: %v", helperErr)
case <-time.After(300 * time.Millisecond):
}
if digest, err := release.HashFile(launcherPath); err != nil || digest != oldDigest {
t.Fatalf("running launcher was replaced: digest=%s, error=%v", digest, err)
}
assertContent(t, filepath.Join(target, "runtime.dat"), "old runtime")
if _, err := os.Stat(filepath.Join(target, ".update", resultFile)); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("switch result was recorded while the old launcher was running: %v", err)
}
select {
case path := <-started:
t.Fatalf("launcher restarted before the old process exited: %s", path)
default:
}
stopLauncher()
select {
case <-completed:
if helperErr != nil {
t.Fatal(helperErr)
}
case <-time.After(10 * time.Second):
t.Fatal("updater did not finish after the old launcher exited and was reaped")
}
assertContent(t, launcherPath, "new executable")
assertContent(t, filepath.Join(target, "runtime.dat"), "new runtime")
select {
case path := <-started:
if path != launcherPath {
t.Fatalf("restarted %q; want %q", path, launcherPath)
}
default:
t.Fatal("updated launcher was not restarted")
}
result := TakeResult(target)
if result == nil || !result.OK || result.From != from || result.To != component.Version {
t.Fatalf("persisted switch result = %+v", result)
}
}
func TestSwitchLauncherRejectsTamperedFileDespiteValidManifestSignature(t *testing.T) {
root := t.TempDir()
target, staging := filepath.Join(root, "installed"), filepath.Join(root, "staged")
component := &release.Component{Version: "2.36.7+client.0.2.0", Files: []release.File{releaseFile(launcherExecutable(), "new executable"), releaseFile("runtime.dat", "new runtime")}}
raw, keys := signedFixture(t, component, nil)
writeFixture(t, filepath.Join(staging, launcherManifestFile), string(raw))
writeFixture(t, filepath.Join(staging, launcherExecutable()), "new executable")
writeFixture(t, filepath.Join(staging, "runtime.dat"), "bad runtime")
writeFixture(t, filepath.Join(target, launcherExecutable()), "old executable")
writeFixture(t, filepath.Join(target, "runtime.dat"), "old runtime")
if _, err := release.Verify(raw, keys); err != nil {
t.Fatalf("fixture signature is not valid: %v", err)
}
if err := switchLauncher(staging, target, "2.36.7+client.0.1.0", component.Version, keys); err == nil {
t.Fatal("installed a corrupted staged file")
}
assertContent(t, filepath.Join(target, launcherExecutable()), "old executable")
assertContent(t, filepath.Join(target, "runtime.dat"), "old runtime")
}
func TestSwitchLauncherRestoresEarlierReplacementOnRealFilesystemFailure(t *testing.T) {
root := t.TempDir()
target, staging := filepath.Join(root, "installed"), filepath.Join(root, "staged")
component := &release.Component{Version: "2.36.7+client.0.2.0", Files: []release.File{releaseFile(launcherExecutable(), "new executable"), releaseFile("runtime.dat", "new runtime")}}
raw, keys := signedFixture(t, component, nil)
writeFixture(t, filepath.Join(staging, launcherManifestFile), string(raw))
writeFixture(t, filepath.Join(staging, launcherExecutable()), "new executable")
writeFixture(t, filepath.Join(staging, "runtime.dat"), "new runtime")
writeFixture(t, filepath.Join(target, launcherExecutable()), "old executable")
writeFixture(t, filepath.Join(target, "runtime.dat", "player.txt"), "player data")
writeFixture(t, filepath.Join(target, "settings.json"), "player settings")
if err := switchLauncher(staging, target, "2.36.7+client.0.1.0", component.Version, keys); err == nil || !strings.Contains(err.Error(), "previous version restored") {
t.Fatalf("expected rollback after replacing executable, got %v", err)
}
assertContent(t, filepath.Join(target, launcherExecutable()), "old executable")
assertContent(t, filepath.Join(target, "runtime.dat", "player.txt"), "player data")
assertContent(t, filepath.Join(target, "settings.json"), "player settings")
entries, err := filepath.Glob(filepath.Join(target, ".launcher-*.new"))
if err != nil || len(entries) != 0 {
t.Fatalf("temporary replacement files remain: %v, %v", entries, err)
}
}
func TestSwitchLauncherIncludesUnchangedExecutableAndIgnoresUnlistedFiles(t *testing.T) {
root := t.TempDir()
target := filepath.Join(root, "installed")
component := &release.Component{Version: "2.36.7+client.0.2.0", Files: []release.File{releaseFile(launcherExecutable(), "same executable"), releaseFile("runtime.dat", "new runtime")}}
raw, keys := signedFixture(t, component, nil)
m := New(Options{Directory: target})
m.envelope, m.keys = raw, keys
staging := m.launcherStaging(component.Version)
writeFixture(t, filepath.Join(target, launcherExecutable()), "same executable")
writeFixture(t, filepath.Join(target, "runtime.dat"), "old runtime")
writeFixture(t, filepath.Join(target, "settings.json"), "player settings")
writeFixture(t, filepath.Join(staging, "runtime.dat"), "new runtime")
writeFixture(t, filepath.Join(staging, "settings.json"), "unexpected staged settings")
if err := m.prepareLauncher(staging, component); err != nil {
t.Fatal(err)
}
if err := switchLauncher(staging, target, "2.36.7+client.0.1.0", component.Version, keys); err != nil {
t.Fatal(err)
}
assertContent(t, filepath.Join(target, launcherExecutable()), "same executable")
assertContent(t, filepath.Join(target, "runtime.dat"), "new runtime")
assertContent(t, filepath.Join(target, "settings.json"), "player settings")
}
+2 -2
View File
@@ -71,7 +71,7 @@ func Save[T any](path string, value T, options WriteOptions) error {
return err
}
defer func() { _ = os.Remove(temporary) }()
return replaceFile(temporary, path)
return ReplaceFile(temporary, path)
}
// Ensure publishes defaults atomically and never replaces an existing file.
@@ -111,7 +111,7 @@ func WriteFile(path string, raw []byte) error {
return err
}
defer func() { _ = os.Remove(temporary) }()
return replaceFile(temporary, path)
return ReplaceFile(temporary, path)
}
func stageBytes(path string, raw []byte, options WriteOptions) (string, error) {
+2 -1
View File
@@ -4,6 +4,7 @@ package config
import "os"
func replaceFile(source, destination string) error {
// ReplaceFile atomically renames source over destination, replacing it if present.
func ReplaceFile(source, destination string) error {
return os.Rename(source, destination)
}
+2 -1
View File
@@ -10,7 +10,8 @@ import (
var moveFileEx = syscall.NewLazyDLL("kernel32.dll").NewProc("MoveFileExW")
func replaceFile(source, destination string) error {
// ReplaceFile atomically renames source over destination, replacing it if present.
func ReplaceFile(source, destination string) error {
sourcePtr, err := syscall.UTF16PtrFromString(source)
if err != nil {
return err
+108
View File
@@ -0,0 +1,108 @@
// Package i18n resolves translated text the way the plugin SDK's Component
// does: flat per-locale JSON files of key → text, looked up in the requested
// locale, then en_us, then the key itself. Arguments use fmt verbs.
package i18n
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"path"
"slices"
)
// Locales are the game's text languages, in the SDK's order.
var Locales = []string{"en_us", "ko_kr", "ja_jp", "zh_tw", "zh_cn"}
// Fallback is consulted when the requested locale lacks a key.
const Fallback = "en_us"
// Supported reports whether locale is one of Locales.
func Supported(locale string) bool { return slices.Contains(Locales, locale) }
// FromGameLanguage maps Define_LanguageType (KOREA=1, ENGLISH=2, JAPAN=3,
// TAIWAN=4, CHINA=5) to a locale; anything else falls back to en_us.
func FromGameLanguage(language uint64) string {
switch language {
case 1:
return "ko_kr"
case 3:
return "ja_jp"
case 4:
return "zh_tw"
case 5:
return "zh_cn"
}
return Fallback
}
// Text is one string in several locales.
type Text map[string]string
// In picks locale, then en_us, then any available translation.
func (t Text) In(locale string) string {
if s, ok := t[locale]; ok {
return s
}
if s, ok := t[Fallback]; ok {
return s
}
for _, l := range Locales {
if s, ok := t[l]; ok {
return s
}
}
return ""
}
// Catalog holds the translations of one component.
type Catalog struct {
entries map[string]map[string]string
}
// Load reads <dir>/<locale>.json for every supported locale present in fsys.
func Load(fsys fs.FS, dir string) (*Catalog, error) {
c := &Catalog{entries: map[string]map[string]string{}}
for _, locale := range Locales {
raw, err := fs.ReadFile(fsys, path.Join(dir, locale+".json"))
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
continue
}
return nil, fmt.Errorf("i18n: read %s/%s.json: %w", dir, locale, err)
}
var entries map[string]string
if err := json.Unmarshal(raw, &entries); err != nil {
return nil, fmt.Errorf("i18n: %s/%s.json: %w", dir, locale, err)
}
c.entries[locale] = entries
}
if c.entries[Fallback] == nil {
return nil, fmt.Errorf("i18n: %s has no %s.json", dir, Fallback)
}
return c, nil
}
// Translate resolves a key and formats arguments with fmt.Sprintf.
func (c *Catalog) Translate(locale, key string, args ...any) string {
text, ok := c.entries[locale][key]
if !ok {
if text, ok = c.entries[Fallback][key]; !ok {
text = key
}
}
if len(args) == 0 {
return text
}
return fmt.Sprintf(text, args...)
}
// All translates key into every locale the catalog has.
func (c *Catalog) All(key string, args ...any) Text {
out := Text{}
for locale := range c.entries {
out[locale] = c.Translate(locale, key, args...)
}
return out
}
+107
View File
@@ -0,0 +1,107 @@
package i18n
import (
_ "embed"
"encoding/json"
"fmt"
"io"
"io/fs"
"net/http"
"sync"
)
//go:embed web/text.js
var browserScript []byte
func ServeBrowserScript(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
_, _ = w.Write(browserScript)
}
type TextRequest struct {
Locale string `json:"locale"`
Messages []TextMessage `json:"messages"`
}
type TextMessage struct {
Key string `json:"key"`
Args []any `json:"args"`
}
func TextHandler(fsys fs.FS, directory string) http.HandlerFunc {
load := sync.OnceValues(func() (*Catalog, error) { return Load(fsys, directory) })
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
decoder.UseNumber()
var request TextRequest
if err := decoder.Decode(&request); err != nil {
http.Error(w, "invalid text request", http.StatusBadRequest)
return
}
if err := decoder.Decode(new(any)); err != io.EOF || !Supported(request.Locale) || len(request.Messages) == 0 || len(request.Messages) > 256 {
http.Error(w, "invalid text request", http.StatusBadRequest)
return
}
catalog, err := load()
if err != nil {
http.Error(w, "translation catalog unavailable", http.StatusInternalServerError)
return
}
texts := make([]string, len(request.Messages))
for index, message := range request.Messages {
if len(message.Key) > 256 || len(message.Args) > 64 {
http.Error(w, "invalid text message", http.StatusBadRequest)
return
}
_, selected := catalog.entries[request.Locale][message.Key]
_, fallback := catalog.entries[Fallback][message.Key]
if !selected && !fallback {
texts[index] = message.Key
continue
}
for i, value := range message.Args {
argument, err := nativeArgument(value)
if err != nil {
http.Error(w, "invalid text argument", http.StatusBadRequest)
return
}
message.Args[i] = argument
}
texts[index] = catalog.Translate(request.Locale, message.Key, message.Args...)
if len(texts[index]) > 64<<10 {
http.Error(w, "formatted text is too long", http.StatusBadRequest)
return
}
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
_ = json.NewEncoder(w).Encode(struct {
Texts []string `json:"texts"`
}{Texts: texts})
}
}
func nativeArgument(value any) (any, error) {
switch value := value.(type) {
case string:
if len(value) > 8192 {
return nil, fmt.Errorf("i18n: text argument is too long")
}
return value, nil
case nil, bool:
return value, nil
case json.Number:
if integer, err := value.Int64(); err == nil {
return integer, nil
}
return value.Float64()
default:
return nil, fmt.Errorf("i18n: argument must be a JSON primitive")
}
}
+58
View File
@@ -0,0 +1,58 @@
package i18n
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"testing/fstest"
)
func TestTextAPIFormatsActualArgumentsUsingNativeGoRules(t *testing.T) {
pattern := "%[2]s / %[1]08d / %.[3]*[4]f / %[2]q / %%"
raw, err := json.Marshal(map[string]string{"message": pattern, "english.only": "Fallback %[1]s"})
if err != nil {
t.Fatal(err)
}
handler := TextHandler(fstest.MapFS{"lang/en_us.json": &fstest.MapFile{Data: raw}}, "lang")
arguments := []any{int64(23), "{0} %[1]s", int64(2), 1.2345}
body, err := json.Marshal(TextRequest{Locale: "ja_jp", Messages: []TextMessage{{Key: "message", Args: arguments}, {Key: "english.only", Args: []any{"日本語"}}, {Key: "%999999s", Args: []any{"untrusted"}}}})
if err != nil {
t.Fatal(err)
}
response := httptest.NewRecorder()
handler(response, httptest.NewRequest(http.MethodPost, "/text/format", bytes.NewReader(body)))
if response.Code != http.StatusOK {
t.Fatalf("format request failed: %d %s", response.Code, response.Body)
}
var result struct{ Texts []string }
if err := json.Unmarshal(response.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
want := []string{fmt.Sprintf(pattern, arguments...), "Fallback 日本語", "%999999s"}
if len(result.Texts) != len(want) {
t.Fatalf("response messages = %v", result.Texts)
}
for i, text := range want {
if result.Texts[i] != text {
t.Errorf("text %d = %q; native Go format requires %q", i, result.Texts[i], text)
}
}
}
func TestTextAPIRejectsUnsupportedLanguagesAndNonPrimitiveArguments(t *testing.T) {
handler := TextHandler(fstest.MapFS{"lang/en_us.json": &fstest.MapFile{Data: []byte(`{"message":"%[1]s"}`)}}, "lang")
for _, body := range []string{
`{"locale":"de_de","messages":[{"key":"message","args":["hello"]}]}`,
`{"locale":"en_us","messages":[{"key":"message","args":[{"key":"anything"}]}]}`,
`{"locale":"en_us","messages":[{"key":"message","args":["hello"]}]} {}`,
} {
response := httptest.NewRecorder()
handler(response, httptest.NewRequest(http.MethodPost, "/text/format", bytes.NewBufferString(body)))
if response.Code != http.StatusBadRequest {
t.Errorf("invalid request was accepted: %s -> %d", body, response.Code)
}
}
}
+69
View File
@@ -0,0 +1,69 @@
'use strict';
(() => {
let lookup = key => key, locale = () => 'en_us', formatURL = '';
const cache = new Map(), pending = new Map();
const CACHE_LIMIT = 2048, BATCH_LIMIT = 128;
let scheduled = false;
async function flush() {
scheduled = false;
const groups = new Map();
for (const request of pending.values()) {
if (request.started) continue;
request.started = true;
const group = groups.get(request.locale) || [];
group.push(request); groups.set(request.locale, group);
}
await Promise.all([...groups].flatMap(([language, requests]) => {
const batches = [];
for (let start = 0; start < requests.length; start += BATCH_LIMIT) {
const batch = requests.slice(start, start + BATCH_LIMIT);
batches.push((async () => {
try {
const response = await fetch(formatURL, {
method: 'POST', credentials: 'same-origin', signal: AbortSignal.timeout(15000), headers: {'Content-Type': 'application/json'},
body: JSON.stringify({locale: language, messages: batch.map(r => ({key: r.key, args: r.args}))}),
});
if (!response.ok) throw new Error('Text formatting failed (HTTP ' + response.status + ')');
const value = await response.json();
if (!Array.isArray(value.texts) || value.texts.length !== batch.length || value.texts.some(text => typeof text !== 'string')) throw new Error('Invalid text formatting response');
batch.forEach((request, index) => {
cache.set(request.id, value.texts[index]);
while (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value);
request.resolve(value.texts[index]);
});
} catch (error) { batch.forEach(request => request.reject(error)); }
finally { batch.forEach(request => pending.delete(request.id)); }
})());
}
return batches;
}));
}
function requestFormattedText(language, key, args) {
const id = JSON.stringify([language, key, args]);
if (cache.has(id)) { const text = cache.get(id); cache.delete(id); cache.set(id, text); return Promise.resolve(text); }
if (pending.has(id)) return pending.get(id).promise;
const request = {id, locale: language, key, args};
request.promise = new Promise((resolve, reject) => { request.resolve = resolve; request.reject = reject; });
pending.set(id, request);
if (!scheduled) { scheduled = true; queueMicrotask(flush); }
return request.promise;
}
class Component {
#content; #args;
constructor(content, args) { this.#content = content; this.#args = args; }
static configure(options) { lookup = options.lookup; locale = options.locale; formatURL = options.formatURL; cache.clear(); }
static literal(text) { if (text == null) throw new TypeError('text is required'); return new Component(String(text), null); }
static translatable(key, ...args) { if (key == null) throw new TypeError('key is required'); return new Component(String(key), args); }
async getString() {
if (this.#args === null) return this.#content;
if (!this.#args.length) return lookup(this.#content) ?? this.#content;
for (;;) {
const language = locale();
const args = await Promise.all(this.#args.map(value => value && typeof value.getString === 'function' ? value.getString() : value));
const text = await requestFormattedText(language, this.#content, args);
if (language === locale()) return text;
}
}
}
window.BD2Text = {Component};
})();
+416
View File
@@ -0,0 +1,416 @@
package release
import (
"bufio"
"bytes"
"fmt"
"hash/fnv"
"regexp"
"strconv"
"strings"
"time"
"bd2server/internal/common/i18n"
)
// Changelog components.
const (
ComponentServer = "server"
ComponentClient = "client"
)
// Notice types, named after the client's Define_NoticeType values.
const (
NoticeNotice = "notice"
NoticeEvent = "event"
NoticeUpdate = "update"
NoticeEmergency = "emergency"
NoticeDeveloperNote = "developer_note"
)
// ChangelogZone dates changelog entries; a notice starts at local midnight.
var ChangelogZone = time.FixedZone("UTC+8", 8*60*60)
// Entry is one CHANGELOG.md release section. It carries everything both the
// in-game notice and the release manifest need, so a release is described
// once, in every language it is translated into.
type Entry struct {
Component string
Version string
Date time.Time
Type string
Pinned bool
Days int
URL string
Thumbnail string
Migration string
Backup bool
// Text is keyed by locale; en_us is always present.
Text map[string]Localized
}
// Localized is one language's title and markdown body.
type Localized struct {
Title string
Body string
}
// Block is one notice paragraph: TextMeshPro rich text or an image URL.
type Block struct {
Image bool
Value string
}
var (
headingPattern = regexp.MustCompile(`^##\s+(\S+)\s+(\S+)\s+[·•\-–—]\s+(\d{4}-\d{2}-\d{2})\s*$`)
languagePattern = regexp.MustCompile(`^###\s+([a-z]{2}_[a-z]{2})\s*[::]\s*(.*?)\s*$`)
metaPattern = regexp.MustCompile(`^>\s*([^::]+?)\s*[::]\s*(.*?)\s*$`)
imagePattern = regexp.MustCompile(`^!\[[^\]]*\]\((\S+?)\)$`)
linkPattern = regexp.MustCompile(`\[([^\]]+)\]\(([^)\s]+)\)`)
boldPattern = regexp.MustCompile(`\*\*([^*]+)\*\*`)
codePattern = regexp.MustCompile("`([^`]+)`")
)
var componentNames = map[string]string{"服务端": ComponentServer, "server": ComponentServer, "客户端": ComponentClient, "client": ComponentClient}
var noticeTypes = map[string]string{
"更新": NoticeUpdate, "公告": NoticeNotice, "活动": NoticeEvent, "紧急": NoticeEmergency, "开发者笔记": NoticeDeveloperNote,
NoticeUpdate: NoticeUpdate, NoticeNotice: NoticeNotice, NoticeEvent: NoticeEvent, NoticeEmergency: NoticeEmergency, NoticeDeveloperNote: NoticeDeveloperNote,
}
var migrationKinds = map[string]string{
"无": MigrationNone, "可回滚": MigrationReversible, "不可回滚": MigrationIrreversible,
MigrationNone: MigrationNone, MigrationReversible: MigrationReversible, MigrationIrreversible: MigrationIrreversible,
}
// defaultTitles name an untitled language block: "Server 0.3.0 update".
var defaultTitles = map[string]map[string]string{
ComponentServer: {"en_us": "Server %s update", "ko_kr": "서버 %s 업데이트", "ja_jp": "サーバー %s アップデート", "zh_tw": "伺服器 %s 更新", "zh_cn": "服务端 %s 更新"},
ComponentClient: {"en_us": "Client %s update", "ko_kr": "클라이언트 %s 업데이트", "ja_jp": "クライアント %s アップデート", "zh_tw": "用戶端 %s 更新", "zh_cn": "客户端 %s 更新"},
}
type changelogParser struct {
entries []Entry
current *Entry
locale string
body []string
inMeta bool
// fenced is set inside a ``` code block, whose lines are never headings.
fenced bool
}
// ParseChangelog reads every release section. Text before the first section
// heading is the file's own introduction and is ignored.
func ParseChangelog(raw []byte) ([]Entry, error) {
p := &changelogParser{}
scanner := bufio.NewScanner(bytes.NewReader(raw))
scanner.Buffer(make([]byte, 64<<10), 1<<20)
for line := 1; scanner.Scan(); line++ {
if err := p.line(strings.TrimRight(scanner.Text(), " \t\r")); err != nil {
return nil, fmt.Errorf("changelog line %d: %w", line, err)
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
if err := p.finishEntry(); err != nil {
return nil, fmt.Errorf("changelog: %w", err)
}
seen := map[string]bool{}
for _, e := range p.entries {
key := e.Component + " " + e.Version
if seen[key] {
return nil, fmt.Errorf("changelog: %s appears twice", key)
}
seen[key] = true
}
return p.entries, nil
}
func (p *changelogParser) line(text string) error {
if strings.HasPrefix(strings.TrimSpace(text), "```") {
p.fenced = !p.fenced
} else if p.fenced {
if p.locale != "" {
p.body = append(p.body, text)
}
return nil
}
if strings.HasPrefix(text, "## ") {
if err := p.finishEntry(); err != nil {
return err
}
entry, err := parseHeading(text)
if err != nil {
return err
}
p.current, p.locale, p.body, p.inMeta = &entry, "", nil, true
return nil
}
if p.current == nil {
return nil
}
if match := languagePattern.FindStringSubmatch(text); match != nil {
if err := p.finishLanguage(); err != nil {
return err
}
if !i18n.Supported(match[1]) {
return fmt.Errorf("unsupported language %q; use %s", match[1], strings.Join(i18n.Locales, ", "))
}
if _, exists := p.current.Text[match[1]]; exists {
return fmt.Errorf("%s %s has two %s blocks", p.current.Component, p.current.Version, match[1])
}
p.locale, p.inMeta = match[1], false
p.current.Text[p.locale] = Localized{Title: match[2]}
return nil
}
if p.inMeta {
if text == "" {
return nil
}
if match := metaPattern.FindStringSubmatch(text); match != nil {
return p.current.setMeta(match[1], match[2])
}
p.inMeta = false
}
if p.locale == "" {
if strings.TrimSpace(text) == "" {
return nil
}
return fmt.Errorf("%s %s: text must follow a \"### <locale>: <title>\" line", p.current.Component, p.current.Version)
}
if t := strings.TrimSpace(text); t == "-" || t == "*" {
return fmt.Errorf("%s %s still has an empty template item", p.current.Component, p.current.Version)
}
p.body = append(p.body, text)
return nil
}
func (p *changelogParser) finishLanguage() error {
if p.locale == "" {
return nil
}
text := p.current.Text[p.locale]
text.Body = strings.TrimSpace(strings.Join(p.body, "\n"))
if text.Body == "" {
return fmt.Errorf("%s %s %s has no content", p.current.Component, p.current.Version, p.locale)
}
if text.Title == "" {
v, _ := ParseVersion(p.current.Version)
text.Title = fmt.Sprintf(defaultTitles[p.current.Component][p.locale], v.Short())
}
p.current.Text[p.locale] = text
p.locale, p.body = "", nil
return nil
}
func (p *changelogParser) finishEntry() error {
if p.current == nil {
return nil
}
if err := p.finishLanguage(); err != nil {
return err
}
if _, ok := p.current.Text[i18n.Fallback]; !ok {
return fmt.Errorf("%s %s needs an %s block, the fallback for other languages", p.current.Component, p.current.Version, i18n.Fallback)
}
p.entries = append(p.entries, *p.current)
p.current = nil
return nil
}
func parseHeading(text string) (Entry, error) {
match := headingPattern.FindStringSubmatch(text)
if match == nil {
return Entry{}, fmt.Errorf("release heading must be \"## server|client <version> · YYYY-MM-DD\": %q", text)
}
component, ok := componentNames[strings.ToLower(match[1])]
if !ok {
return Entry{}, fmt.Errorf("unknown component %q; use server or client", match[1])
}
v, err := ParseVersion(match[2])
if err != nil {
return Entry{}, err
}
if v.Kind != component {
return Entry{}, fmt.Errorf("%s needs a %s release version, not %q", match[1], component, match[2])
}
date, err := time.ParseInLocation("2006-01-02", match[3], ChangelogZone)
if err != nil {
return Entry{}, err
}
return Entry{Component: component, Version: match[2], Date: date, Type: NoticeUpdate, Days: 30, Migration: MigrationNone, Text: map[string]Localized{}}, nil
}
func (e *Entry) setMeta(key, value string) error {
switch key {
case "类型", "type":
kind, ok := noticeTypes[value]
if !ok {
return fmt.Errorf("unknown notice type %q; use update, notice, event, emergency or developer_note", value)
}
e.Type = kind
case "置顶", "pin":
flag, err := parseFlag(value)
if err != nil {
return err
}
e.Pinned = flag
case "展示天数", "days":
days, err := strconv.Atoi(value)
if err != nil || days < 1 || days > 365 {
return fmt.Errorf("days must be 1-365, got %q", value)
}
e.Days = days
case "链接", "url":
e.URL = value
case "缩略图", "thumbnail":
e.Thumbnail = value
case "迁移", "migration":
kind, ok := migrationKinds[value]
if !ok {
return fmt.Errorf("unknown migration %q; use none, reversible or irreversible", value)
}
e.Migration = kind
if kind != MigrationNone {
e.Backup = true
}
case "备份", "backup":
flag, err := parseFlag(value)
if err != nil {
return err
}
e.Backup = flag
default:
return fmt.Errorf("unknown changelog field %q", key)
}
return nil
}
func parseFlag(value string) (bool, error) {
switch strings.ToLower(value) {
case "是", "yes", "true":
return true, nil
case "否", "no", "false":
return false, nil
}
return false, fmt.Errorf("expected yes or no, got %q", value)
}
// StartsAt and EndsAt bound when the entry is shown as an in-game notice.
func (e Entry) StartsAt() time.Time { return e.Date }
func (e Entry) EndsAt() time.Time { return e.Date.AddDate(0, 0, e.Days) }
// NoticeID is stable for a component version, so the client's read marks
// survive restarts and changelog refreshes.
func (e Entry) NoticeID() int32 {
h := fnv.New32a()
_, _ = h.Write([]byte(e.Component + " " + e.Version))
return int32(h.Sum32()&0x3fffffff) + 1
}
// Locales lists the languages the entry is written in.
func (e Entry) Locales() []string {
var out []string
for _, l := range i18n.Locales {
if _, ok := e.Text[l]; ok {
out = append(out, l)
}
}
return out
}
// Titles returns the title in every written language.
func (e Entry) Titles() i18n.Text {
out := i18n.Text{}
for locale, text := range e.Text {
out[locale] = text.Title
}
return out
}
// Blocks renders one language's body for the client's TextMeshPro notice
// view: each paragraph becomes one text block and every standalone image
// line one image.
func (e Entry) Blocks(locale string) []Block {
var blocks []Block
var paragraph []string
flush := func() {
if len(paragraph) != 0 {
blocks = append(blocks, Block{Value: strings.Join(paragraph, "\n")})
paragraph = nil
}
}
for line := range strings.SplitSeq(e.Text[locale].Body, "\n") {
trimmed := strings.TrimSpace(line)
switch {
case trimmed == "":
flush()
case imagePattern.MatchString(trimmed):
flush()
blocks = append(blocks, Block{Image: true, Value: imagePattern.FindStringSubmatch(trimmed)[1]})
case strings.HasPrefix(trimmed, "#"):
flush()
paragraph = append(paragraph, "<b>"+inline(strings.TrimSpace(strings.TrimLeft(trimmed, "#")))+"</b>")
case strings.HasPrefix(trimmed, "- ") || strings.HasPrefix(trimmed, "* "):
paragraph = append(paragraph, "• "+inline(trimmed[2:]))
default:
paragraph = append(paragraph, inline(trimmed))
}
}
flush()
return blocks
}
func inline(text string) string {
text = linkPattern.ReplaceAllString(text, "$1")
text = boldPattern.ReplaceAllString(text, "<b>$1</b>")
return codePattern.ReplaceAllString(text, "$1")
}
// Notes is the body as plain text in every written language, for the
// launcher and the console.
func (e Entry) Notes() i18n.Text {
out := i18n.Text{}
for _, locale := range e.Locales() {
var lines []string
for _, block := range e.Blocks(locale) {
if !block.Image {
lines = append(lines, strings.NewReplacer("<b>", "", "</b>", "").Replace(block.Value))
}
}
out[locale] = strings.Join(lines, "\n\n")
}
return out
}
// Find returns the entry for component and version.
func Find(entries []Entry, component, version string) (Entry, bool) {
for _, e := range entries {
if e.Component == component && e.Version == version {
return e, true
}
}
return Entry{}, false
}
// ChangelogTemplate is the section `bd2w release changelog` inserts: an
// English block (required) and a Simplified Chinese block; other languages
// may be added and fall back to English when absent.
func ChangelogTemplate(component, version string, date time.Time) string {
var b strings.Builder
fmt.Fprintf(&b, "## %s %s · %s\n\n", component, version, date.In(ChangelogZone).Format("2006-01-02"))
b.WriteString("> type: update\n")
if component == ComponentServer {
b.WriteString("> migration: none\n")
}
v, _ := ParseVersion(version)
sections := map[string][3]string{"en_us": {"Added", "Changed", "Fixed"}, "zh_cn": {"新增", "调整", "修复"}}
for _, locale := range []string{"en_us", "zh_cn"} {
fmt.Fprintf(&b, "\n### %s: %s\n", locale, fmt.Sprintf(defaultTitles[component][locale], v.Short()))
for _, heading := range sections[locale] {
fmt.Fprintf(&b, "\n#### %s\n\n- \n", heading)
}
}
return b.String()
}
+14
View File
@@ -0,0 +1,14 @@
{
"name": "stable",
"manifest_url": "https://bd2-test.45.76.195.129.sslip.io/releases/stable/release.json",
"changelog_urls": [
"https://raw.githubusercontent.com/Flechazo098/bd2/main/CHANGELOG.md",
"https://git.sighs.cc/Flechazo/bd2/raw/branch/main/CHANGELOG.md"
],
"trusted_keys": [
{
"id": "6ba6c06138973875",
"public_key": "BX3YFAFg0VxcJaGA4bR9OFKQrSllIO7p6z+f3LvStmY="
}
]
}
@@ -0,0 +1,42 @@
package release
type ClientIdentity struct {
Version string `json:"client_version"`
Plugins map[string]string `json:"plugins"`
GameVersion string `json:"game_version"`
BundleVersion string `json:"bundle_version"`
GameDataVersion string `json:"game_data_version"`
Fingerprint string `json:"fingerprint"`
ResourceFingerprint string `json:"resource_fingerprint"`
}
func AtLeast(current, minimum string) bool {
a, err := ParseVersion(current)
if err != nil {
return false
}
b, err := ParseVersion(minimum)
return err == nil && a.Kind == b.Kind && a.HasGame == b.HasGame && a.Compare(b) >= 0
}
func (f Fingerprint) Accepts(client ClientIdentity) bool {
if f.RequireClientUpdate {
if !AtLeast(client.Version, f.ClientVersion) {
return false
}
for id, version := range f.MinimumPlugins {
if !AtLeast(client.Plugins[id], version) {
return false
}
}
}
if f.RequireGameUpdate {
if f.Game == nil || client.ResourceFingerprint != f.GameFingerprint {
return false
}
if client.GameVersion != f.Game.GameVersion || client.BundleVersion != f.Game.BundleVersion || client.GameDataVersion != f.Game.GameDataVersion {
return false
}
}
return true
}
+268
View File
@@ -0,0 +1,268 @@
package release
import (
"archive/zip"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"time"
commonconfig "bd2server/internal/common/config"
)
const (
maxManifestBytes = 32 << 20
maxChangelogBytes = 2 << 20
)
// DefaultClient bounds connection setup; downloads are bounded by context.
var DefaultClient = &http.Client{Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSHandshakeTimeout: 15 * time.Second,
ResponseHeaderTimeout: 30 * time.Second,
IdleConnTimeout: 60 * time.Second,
}}
func get(ctx context.Context, client *http.Client, address string) (*http.Response, error) {
if client == nil {
client = DefaultClient
}
request, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil)
if err != nil {
return nil, err
}
request.Header.Set("Cache-Control", "no-cache")
response, err := client.Do(request)
if err != nil {
return nil, err
}
if response.StatusCode != http.StatusOK {
_ = response.Body.Close()
return nil, fmt.Errorf("GET %s: HTTP %d", request.URL.Redacted(), response.StatusCode)
}
return response, nil
}
func readLimited(ctx context.Context, client *http.Client, address string, limit int64) ([]byte, error) {
response, err := get(ctx, client, address)
if err != nil {
return nil, err
}
defer func() { _ = response.Body.Close() }()
raw, err := io.ReadAll(io.LimitReader(response.Body, limit+1))
if err != nil {
return nil, err
}
if int64(len(raw)) > limit {
return nil, fmt.Errorf("GET %s: response exceeds %d bytes", address, limit)
}
return raw, nil
}
// FetchManifest downloads and verifies the signed manifest at address.
func FetchManifest(ctx context.Context, client *http.Client, address string, keys []TrustedKey) (Manifest, []byte, error) {
if address == "" {
return Manifest{}, nil, errors.New("release: no manifest URL is configured")
}
if _, err := Resolve(address, address); err != nil {
return Manifest{}, nil, err
}
raw, err := readLimited(ctx, client, address, maxManifestBytes)
if err != nil {
return Manifest{}, nil, err
}
manifest, err := Verify(raw, keys)
if err != nil {
return Manifest{}, nil, err
}
if manifest.Channel != BuiltinChannel().Name {
return Manifest{}, nil, errors.New("release: manifest belongs to a different release channel")
}
return manifest, raw, nil
}
// Progress receives the bytes written so far for one file.
type Progress func(name string, done, total int64)
// Download fetches file into directory unless a verified copy already exists,
// and returns its path. The file appears under its final name only after its
// size and SHA-256 matched, so a partial download is never mistaken for one.
func Download(ctx context.Context, client *http.Client, manifestURL string, file File, directory string, progress Progress) (string, error) {
target := filepath.Join(directory, file.Name)
if Matches(target, file) {
return target, nil
}
address, err := Resolve(manifestURL, file.URL)
if err != nil {
return "", err
}
if err := os.MkdirAll(directory, 0o755); err != nil {
return "", err
}
response, err := get(ctx, client, address)
if err != nil {
return "", err
}
defer func() { _ = response.Body.Close() }()
temporary, err := os.CreateTemp(directory, "."+file.Name+"-*.part")
if err != nil {
return "", err
}
defer func() { _ = os.Remove(temporary.Name()) }()
digest := sha256.New()
writer := io.MultiWriter(temporary, digest)
var written int64
buffer := make([]byte, 256<<10)
for {
n, readErr := response.Body.Read(buffer)
if n > 0 {
if written+int64(n) > file.Size {
_ = temporary.Close()
return "", fmt.Errorf("release: %s is larger than the manifest states", file.Name)
}
if _, err := writer.Write(buffer[:n]); err != nil {
_ = temporary.Close()
return "", err
}
written += int64(n)
if progress != nil {
progress(file.Name, written, file.Size)
}
}
if errors.Is(readErr, io.EOF) {
break
}
if readErr != nil {
_ = temporary.Close()
return "", readErr
}
}
if err := temporary.Sync(); err != nil {
_ = temporary.Close()
return "", err
}
if err := temporary.Close(); err != nil {
return "", err
}
if written != file.Size || hex.EncodeToString(digest.Sum(nil)) != file.SHA256 {
return "", fmt.Errorf("release: %s failed verification; the download was discarded", file.Name)
}
if err := commonconfig.ReplaceFile(temporary.Name(), target); err != nil {
return "", err
}
return target, nil
}
// Matches reports whether path exists with file's size and digest.
func Matches(path string, file File) bool {
info, err := os.Stat(path)
if err != nil || !info.Mode().IsRegular() || info.Size() != file.Size {
return false
}
sum, err := HashFile(path)
return err == nil && sum == file.SHA256
}
func HashFile(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer func() { _ = f.Close() }()
digest := sha256.New()
if _, err := io.Copy(digest, f); err != nil {
return "", err
}
return hex.EncodeToString(digest.Sum(nil)), nil
}
// Extract unpacks a verified zip archive into an empty directory, refusing
// entries that would escape it.
func Extract(archive, directory string) error {
reader, err := zip.OpenReader(archive)
if err != nil {
return err
}
defer func() { _ = reader.Close() }()
root, err := filepath.Abs(directory)
if err != nil {
return err
}
for _, entry := range reader.File {
name := filepath.FromSlash(entry.Name)
target := filepath.Join(root, name)
if !strings.HasPrefix(target, root+string(filepath.Separator)) || filepath.IsAbs(name) {
return fmt.Errorf("release: archive entry %q escapes the target", entry.Name)
}
if entry.FileInfo().IsDir() {
if err := os.MkdirAll(target, 0o755); err != nil {
return err
}
continue
}
if !entry.Mode().IsRegular() {
return fmt.Errorf("release: archive entry %q is not a regular file", entry.Name)
}
if err := extractFile(entry, target); err != nil {
return err
}
}
return nil
}
func extractFile(entry *zip.File, target string) error {
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
return err
}
source, err := entry.Open()
if err != nil {
return err
}
defer func() { _ = source.Close() }()
mode := os.FileMode(0o644)
if entry.Mode()&0o111 != 0 {
mode = 0o755
}
out, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode)
if err != nil {
return err
}
if _, err = io.Copy(out, io.LimitReader(source, int64(entry.UncompressedSize64)+1)); err != nil {
_ = out.Close()
return err
}
return out.Close()
}
// FetchSigned returns a changelog and its detached signature from the first
// mirror that serves both.
func FetchSigned(ctx context.Context, client *http.Client, addresses []string, keys []TrustedKey) ([]byte, []byte, string, error) {
var failures []error
for _, address := range addresses {
if _, err := Resolve(address, address); err != nil {
failures = append(failures, err)
continue
}
raw, err := readLimited(ctx, client, address, maxChangelogBytes)
if err == nil {
var signature []byte
if signature, err = readLimited(ctx, client, address+".sig", 4<<10); err == nil {
if err = VerifyChangelog(raw, signature, keys); err == nil {
return raw, signature, address, nil
}
}
}
failures = append(failures, err)
}
if len(failures) == 0 {
return nil, nil, "", errors.New("release: no changelog source configured")
}
return nil, nil, "", errors.Join(failures...)
}
+290
View File
@@ -0,0 +1,290 @@
package release
import (
"bytes"
"crypto/ed25519"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"path"
"strings"
"bd2server/internal/common/versionconfig"
)
const FingerprintFileName = "UPDATE_FINGERPRINT.json"
const fingerprintDomain = "bd2-update-fingerprint-v1\n"
func (g GameResources) ResourceID() string {
raw, _ := canonicalJSON(g.ResourceFiles)
sum := sha256.Sum256(raw)
return hex.EncodeToString(sum[:])
}
func (g GameResources) ContentID() string {
raw, _ := canonicalJSON(g)
sum := sha256.Sum256(raw)
return hex.EncodeToString(sum[:])
}
type Fingerprint struct {
ID string `json:"id"`
ServerVersion string `json:"server_version"`
ClientVersion string `json:"client_version"`
RequireClientUpdate bool `json:"require_client_update"`
RequireGameUpdate bool `json:"require_game_update"`
GameFingerprint string `json:"game_fingerprint,omitempty"`
MinimumPlugins map[string]string `json:"minimum_plugins"`
Game *GameResources `json:"game,omitempty"`
}
type GameResources struct {
GameVersion string `json:"game_version"`
GameDataVersion string `json:"game_data_version"`
BundleVersion string `json:"bundle_version"`
Platform string `json:"platform"`
ServerOrigin string `json:"server_origin"`
BuildOrigins []string `json:"build_origins"`
ResourceOrigins []string `json:"resource_origins"`
GamePath string `json:"game_path"`
GameSHA256 string `json:"game_sha256"`
GameBytes int64 `json:"game_bytes"`
DataSHA256 string `json:"data_sha256"`
DataBytes int64 `json:"data_bytes"`
CatalogSHA256 string `json:"catalog_sha256"`
CatalogBytes int64 `json:"catalog_bytes"`
CatalogHash string `json:"catalog_hash"`
ResourceFiles []ResourceFile `json:"resource_files,omitempty"`
}
type ResourceFile struct {
Path string `json:"path"`
Size int64 `json:"size"`
SHA256 string `json:"sha256"`
}
func (g GameResources) Validate() error {
gameVersion, err := ParseVersion(g.GameVersion)
if err != nil || gameVersion.HasGame {
return errors.New("release: invalid game version")
}
if len(g.BundleVersion) != 14 || len(g.GameDataVersion) != 14 || strings.Trim(g.BundleVersion+g.GameDataVersion, "0123456789") != "" {
return errors.New("release: invalid resource versions")
}
if g.Platform != "StandaloneWindows64" || !strings.HasPrefix(g.GamePath, "/Build/") || path.Clean(g.GamePath) != g.GamePath || strings.ContainsAny(g.GamePath, "\\?#") {
return errors.New("release: unsupported game download path or platform")
}
for _, f := range []struct {
sum string
size int64
}{{g.GameSHA256, g.GameBytes}, {g.DataSHA256, g.DataBytes}, {g.CatalogSHA256, g.CatalogBytes}} {
if !digestPattern.MatchString(f.sum) || f.size <= 0 {
return errors.New("release: game resources require pinned SHA-256 and positive sizes")
}
}
if len(g.CatalogHash) != 32 || strings.Trim(strings.ToLower(g.CatalogHash), "0123456789abcdef") != "" {
return errors.New("release: invalid catalog hash")
}
if len(g.BuildOrigins) == 0 || len(g.ResourceOrigins) == 0 {
return errors.New("release: game resources have no download origins")
}
for _, origin := range append(append([]string{}, g.BuildOrigins...), g.ResourceOrigins...) {
u, err := url.Parse(origin)
if err != nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
return errors.New("release: invalid game resource origin")
}
if _, err := Resolve(origin, origin); err != nil {
return err
}
}
if len(g.ResourceFiles) == 0 || len(g.ResourceFiles) > 100000 {
return errors.New("release: game resources require a bounded file inventory")
}
seen := map[string]bool{}
pins := map[string]ResourceFile{}
for _, f := range g.ResourceFiles {
allowed := strings.HasPrefix(f.Path, "ServerData/"+g.Platform+"/HD/"+g.BundleVersion+"/") || strings.HasPrefix(f.Path, "GameData/"+g.GameDataVersion+"/")
key := strings.ToLower(f.Path)
if !allowed || path.Clean(f.Path) != f.Path || strings.ContainsAny(f.Path, "\\:\x00") || f.Size < 0 || !digestPattern.MatchString(f.SHA256) || seen[key] {
return fmt.Errorf("release: invalid resource inventory entry %q", f.Path)
}
seen[key] = true
for part := range strings.SplitSeq(f.Path, "/") {
if strings.TrimRight(part, ". ") != part {
return fmt.Errorf("release: unsafe resource path %q", f.Path)
}
}
pins[f.Path] = f
}
base := "ServerData/" + g.Platform + "/HD/" + g.BundleVersion + "/"
data := "GameData/" + g.GameDataVersion + "/"
for _, name := range []string{base + "catalog_alpha.hash", data + "design.version", data + "release/common-dbdata.info"} {
if _, ok := pins[name]; !ok {
return fmt.Errorf("release: missing required resource %s", name)
}
}
for _, expected := range []ResourceFile{{Path: base + "catalog_alpha.json", Size: g.CatalogBytes, SHA256: g.CatalogSHA256}, {Path: data + "release/common-dbdata.bin", Size: g.DataBytes, SHA256: g.DataSHA256}} {
if pins[expected.Path] != expected {
return fmt.Errorf("release: conflicting signed resource %s", expected.Path)
}
}
return nil
}
func (f Fingerprint) Validate() error {
server, err := ParseVersion(f.ServerVersion)
if err != nil || server.Kind != "server" {
return errors.New("release: invalid fingerprint server version")
}
client, err := ParseVersion(f.ClientVersion)
if err != nil || client.Kind != "client" {
return errors.New("release: invalid fingerprint client version")
}
if server.Game != client.Game {
return errors.New("release: fingerprint client and server game versions differ")
}
if f.Game != nil && f.Game.GameVersion != client.GameVersion() {
return errors.New("release: fingerprint game version differs from components")
}
for id, version := range f.MinimumPlugins {
v, e := ParseVersion(version)
if e != nil || !knownPlayerPlugin(id) || v.HasGame {
return errors.New("release: invalid fingerprint plugin version")
}
}
if f.RequireClientUpdate && len(f.MinimumPlugins) == 0 {
return errors.New("release: required client update has no plugin requirements")
}
if f.RequireGameUpdate && f.Game == nil {
return errors.New("release: required game update has no resources")
}
if f.Game != nil {
if err := f.Game.Validate(); err != nil {
return err
}
if f.GameFingerprint != f.Game.ContentID() {
return errors.New("release: game fingerprint differs from signed resource content")
}
}
digest, err := f.digest()
if err != nil {
return err
}
if f.ID != digest {
return errors.New("release: fingerprint identity does not match its content")
}
return nil
}
func knownPlayerPlugin(id string) bool {
switch id {
case "local_identity", "login_ui", "cash_shop", "fchat":
return true
default:
return false
}
}
func (f Fingerprint) digest() (string, error) {
raw, err := json.Marshal(f)
if err != nil {
return "", err
}
var fields map[string]json.RawMessage
if err = json.Unmarshal(raw, &fields); err != nil {
return "", err
}
delete(fields, "id")
raw, err = canonicalJSON(fields)
if err != nil {
return "", err
}
sum := sha256.Sum256(raw)
return hex.EncodeToString(sum[:]), nil
}
func canonicalJSON(value any) ([]byte, error) {
raw, err := json.Marshal(value)
if err != nil {
return nil, err
}
var fields any
d := json.NewDecoder(bytes.NewReader(raw))
d.UseNumber()
if err = d.Decode(&fields); err != nil {
return nil, err
}
return json.Marshal(fields)
}
func (f Fingerprint) MatchesVersions(v versionconfig.Config) error {
if f.ServerVersion != v.ServerVersion || f.ClientVersion != v.ClientVersion {
return errors.New("release: fingerprint does not match installed component versions")
}
if f.Game != nil && (f.Game.GameVersion != v.GameVersion || f.Game.BundleVersion != v.BundleVersion || f.Game.GameDataVersion != v.GameDataVersion) {
return errors.New("release: fingerprint does not match installed game resource versions")
}
for id, version := range f.MinimumPlugins {
if v.Plugins.ByID()[id] != version {
return fmt.Errorf("release: fingerprint plugin %s does not match installed version", id)
}
}
return nil
}
func VerifyFingerprint(raw []byte, keys []TrustedKey) (Fingerprint, error) {
var envelope struct {
KeyID string `json:"key_id"`
Signature string `json:"signature"`
Fingerprint json.RawMessage `json:"fingerprint"`
}
if err := decodeStrict(raw, &envelope); err != nil {
return Fingerprint{}, err
}
public, err := trusted(envelope.KeyID, keys)
if err != nil {
return Fingerprint{}, err
}
sig, err := base64.StdEncoding.DecodeString(envelope.Signature)
if err != nil || !ed25519.Verify(public, append([]byte(fingerprintDomain), envelope.Fingerprint...), sig) {
return Fingerprint{}, errors.New("release: update fingerprint signature is invalid")
}
var fingerprint Fingerprint
if err := decodeStrict(envelope.Fingerprint, &fingerprint); err != nil {
return Fingerprint{}, err
}
if err := fingerprint.Validate(); err != nil {
return Fingerprint{}, err
}
return fingerprint, nil
}
func LoadFingerprint(file string, keys []TrustedKey) (*Fingerprint, error) {
raw, err := os.ReadFile(file)
if err != nil {
return nil, err
}
f, err := VerifyFingerprint(raw, keys)
if err != nil {
return nil, err
}
return &f, nil
}
func decodeStrict(raw []byte, value any) error {
d := json.NewDecoder(bytes.NewReader(raw))
d.DisallowUnknownFields()
if err := d.Decode(value); err != nil {
return err
}
if err := d.Decode(new(any)); err != io.EOF {
return errors.New("release: trailing JSON content")
}
return nil
}
@@ -0,0 +1,78 @@
package release_test
import (
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"testing"
"bd2server/internal/common/release"
)
func TestUpdateRequirementsCannotBeChangedWithoutPublisherSignature(t *testing.T) {
public, private, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
payload := map[string]any{"server_version": "2.36.7+server.0.2.0", "client_version": "2.36.7+client.0.2.0", "require_client_update": true, "require_game_update": false, "minimum_plugins": map[string]string{"login_ui": "0.3.0"}}
content, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
id := sha256.Sum256(content)
payload["id"] = hex.EncodeToString(id[:])
content, err = json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
signature := ed25519.Sign(private, append([]byte("bd2-update-fingerprint-v1\n"), content...))
envelope := map[string]any{"key_id": release.KeyID(public), "signature": base64.StdEncoding.EncodeToString(signature), "fingerprint": json.RawMessage(content)}
raw, err := json.Marshal(envelope)
if err != nil {
t.Fatal(err)
}
trust := []release.TrustedKey{{ID: release.KeyID(public), PublicKey: base64.StdEncoding.EncodeToString(public)}}
verified, err := release.VerifyFingerprint(raw, trust)
if err != nil {
t.Fatal(err)
}
old := release.ClientIdentity{Version: "2.36.7+client.0.1.0", Plugins: map[string]string{"login_ui": "0.2.0"}}
if verified.Accepts(old) {
t.Fatal("publisher's mandatory update did not exclude an old client")
}
payload["require_client_update"] = false
delete(payload, "id")
content, err = json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
changedID := sha256.Sum256(content)
payload["id"] = hex.EncodeToString(changedID[:])
content, err = json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
envelope["fingerprint"] = json.RawMessage(content)
raw, err = json.Marshal(envelope)
if err != nil {
t.Fatal(err)
}
if _, err := release.VerifyFingerprint(raw, trust); err == nil {
t.Fatal("modified requirement was accepted with the publisher's old signature")
}
envelope["signature"] = base64.StdEncoding.EncodeToString(ed25519.Sign(private, append([]byte("bd2-update-fingerprint-v1\n"), content...)))
raw, err = json.Marshal(envelope)
if err != nil {
t.Fatal(err)
}
modified, err := release.VerifyFingerprint(raw, trust)
if err != nil {
t.Fatalf("publisher cannot sign the valid modified contract: %v", err)
}
if !modified.Accepts(old) {
t.Fatal("publisher-signed removal of the requirement did not admit the old client")
}
}
+186
View File
@@ -0,0 +1,186 @@
// Package release defines the signed release manifest shared by the build
// tool, the launcher and the server: what each component's current version is,
// where its files are, their sizes and SHA-256 digests, and what an install
// requires. Components are compared and downloaded independently.
package release
import (
"errors"
"fmt"
"net/url"
"path"
"regexp"
"runtime"
"slices"
"strings"
"time"
"bd2server/internal/common/i18n"
)
const SchemaVersion = 1
// Migration kinds a server release may declare.
const (
MigrationNone = "none"
MigrationReversible = "reversible"
MigrationIrreversible = "irreversible"
)
type Manifest struct {
Schema int `json:"schema"`
Channel string `json:"channel"`
PublishedAt time.Time `json:"published_at"`
Commit string `json:"commit"`
Launcher *Component `json:"launcher,omitempty"`
Plugins *Component `json:"plugins,omitempty"`
Server *Component `json:"server,omitempty"`
Fingerprint *Fingerprint `json:"fingerprint,omitempty"`
}
type Component struct {
Version string `json:"version"`
Date string `json:"date"`
Notes i18n.Text `json:"notes"`
Files []File `json:"files"`
// Server-only fields.
Image string `json:"image,omitempty"`
Migration *Migration `json:"migration,omitempty"`
MinimumPlugins map[string]string `json:"minimum_plugins,omitempty"`
}
// File is one downloadable unit. Platform is GOOS-GOARCH, or empty for files
// that are identical on every platform (plugins). Version is set for plugin
// DLLs that carry their own number.
type File struct {
Name string `json:"name"`
ID string `json:"id,omitempty"`
Platform string `json:"platform,omitempty"`
Version string `json:"version,omitempty"`
Size int64 `json:"size"`
SHA256 string `json:"sha256"`
URL string `json:"url"`
}
type Migration struct {
Kind string `json:"kind"`
Backup bool `json:"backup"`
Note i18n.Text `json:"note,omitempty"`
}
var (
digestPattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
commitPattern = regexp.MustCompile(`^[0-9a-f]{40}$`)
)
func Platform() string { return runtime.GOOS + "-" + runtime.GOARCH }
func (m Manifest) Validate() error {
if m.Schema != SchemaVersion {
return fmt.Errorf("release: unsupported manifest schema %d", m.Schema)
}
if m.Channel == "" || m.PublishedAt.IsZero() {
return errors.New("release: manifest needs a channel and publication time")
}
if !commitPattern.MatchString(m.Commit) {
return errors.New("release: manifest commit must be a full Git commit hash")
}
if m.Launcher == nil && m.Plugins == nil && m.Server == nil {
return errors.New("release: manifest has no components")
}
for name, c := range map[string]*Component{"launcher": m.Launcher, "plugins": m.Plugins, "server": m.Server} {
if c == nil {
continue
}
if err := c.validate(name); err != nil {
return err
}
}
if m.Fingerprint != nil {
if err := m.Fingerprint.Validate(); err != nil {
return err
}
if m.Server != nil && m.Server.Version != m.Fingerprint.ServerVersion {
return errors.New("release: server and fingerprint versions differ")
}
if m.Launcher != nil && m.Launcher.Version != m.Fingerprint.ClientVersion {
return errors.New("release: launcher and fingerprint versions differ")
}
}
return nil
}
func (c *Component) validate(name string) error {
kind := map[string]string{"launcher": "client", "plugins": "client", "server": "server"}[name]
v, err := ParseVersion(c.Version)
if err != nil || v.Kind != kind {
return fmt.Errorf("release: %s version %q must be a %s release version", name, c.Version, kind)
}
if len(c.Files) == 0 && c.Image == "" {
return fmt.Errorf("release: %s has nothing to download", name)
}
seen := map[string]bool{}
for _, f := range c.Files {
if f.Name == "" || path.Base(f.Name) != f.Name || strings.ContainsAny(f.Name, `\:`) {
return fmt.Errorf("release: %s file name %q is invalid", name, f.Name)
}
key := f.Platform + "/" + f.Name
if seen[key] {
return fmt.Errorf("release: %s lists %s twice", name, key)
}
seen[key] = true
if f.Size <= 0 || !digestPattern.MatchString(f.SHA256) || f.URL == "" {
return fmt.Errorf("release: %s file %s needs a size, a lowercase SHA-256 and a URL", name, f.Name)
}
if f.Version != "" {
if _, err := ParseVersion(f.Version); err != nil {
return err
}
}
}
if name == "server" {
if c.Migration == nil || !slices.Contains([]string{MigrationNone, MigrationReversible, MigrationIrreversible}, c.Migration.Kind) {
return errors.New("release: server must declare its migration kind")
}
for id, minimum := range c.MinimumPlugins {
if _, err := ParseVersion(minimum); err != nil || id == "" {
return fmt.Errorf("release: invalid minimum plugin %s=%q", id, minimum)
}
}
}
return nil
}
// FilesFor returns the files a host of platform needs: platform-specific files
// plus the shared ones.
func (c *Component) FilesFor(platform string) []File {
var out []File
for _, f := range c.Files {
if f.Platform == "" || f.Platform == platform {
out = append(out, f)
}
}
return out
}
// Resolve turns a file URL into an absolute HTTPS URL; relative URLs are
// relative to the manifest, so moving files to a CDN only changes the base.
func Resolve(manifestURL, fileURL string) (string, error) {
base, err := url.Parse(manifestURL)
if err != nil {
return "", err
}
ref, err := url.Parse(fileURL)
if err != nil {
return "", err
}
out := base.ResolveReference(ref)
if out.Scheme != "https" && !loopback(out.Hostname()) {
return "", fmt.Errorf("release: %s must use HTTPS", out.Redacted())
}
return out.String(), nil
}
func loopback(host string) bool {
return host == "localhost" || host == "127.0.0.1" || host == "::1"
}
+309
View File
@@ -0,0 +1,309 @@
package release
import (
"bytes"
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
)
func testManifest() Manifest {
return Manifest{
Schema: SchemaVersion, Channel: "stable", PublishedAt: time.Date(2026, 10, 15, 8, 0, 0, 0, time.UTC),
Commit: strings.Repeat("a", 40),
Server: &Component{Version: "2.36.7+server.0.2.0", Migration: &Migration{Kind: MigrationNone},
Files: []File{{Name: "bd2server.zip", Platform: "linux-amd64", Size: 3, SHA256: strings.Repeat("0", 64), URL: "../files/x/bd2server.zip"}}},
}
}
func TestVerifyAcceptsOnlyTheTrustedSignerAndExactBytes(t *testing.T) {
seed, key, err := testSigner()
if err != nil {
t.Fatal(err)
}
signed, err := signManifest(testManifest(), seed)
if err != nil {
t.Fatal(err)
}
got, err := Verify(signed, []TrustedKey{key})
if err != nil {
t.Fatalf("Verify(signed) = %v", err)
}
if got.Server.Version != "2.36.7+server.0.2.0" {
t.Fatalf("verified manifest server version = %q", got.Server.Version)
}
_, other, err := testSigner()
if err != nil {
t.Fatal(err)
}
if _, err := Verify(signed, []TrustedKey{other}); err == nil {
t.Fatal("a manifest signed by a key the build does not trust was accepted")
}
// Raising the version inside the signed bytes must break the signature.
tampered := bytes.Replace(signed, []byte("server.0.2.0"), []byte("server.9.2.0"), 1)
if bytes.Equal(tampered, signed) {
t.Fatal("test setup: version not found in envelope")
}
if _, err := Verify(tampered, []TrustedKey{key}); err == nil {
t.Fatal("a manifest edited after signing was accepted")
}
}
func TestNewerRanksTheGameVersionAboveTheComponentNumber(t *testing.T) {
for _, c := range []struct {
current, candidate string
want bool
}{
{"2.36.7+server.0.2.0", "2.36.7+server.0.2.1", true},
{"2.36.7+server.0.10.0", "2.36.7+server.0.9.9", false},
{"2.36.7+server.3.0.0", "2.37.0+server.0.1.0", true},
{"2.36.7+server.0.2.0", "2.36.7+server.0.2.0", false},
} {
got, err := Newer(c.current, c.candidate)
if err != nil || got != c.want {
t.Errorf("Newer(%q, %q) = %v, %v; want %v", c.current, c.candidate, got, err, c.want)
}
}
if _, err := Newer("2.36.7+server.0.2.0", "2.36.7+client.0.3.0"); err == nil {
t.Error("comparing a server release with a client release did not fail")
}
}
const sampleChangelog = "# Changelog\n\nIntroduction text belongs to no release.\n\n```markdown\n## server 9.9.9+server.9.9.9 · 2026-01-01\n```\n\n" +
"## server 2.36.7+server.0.3.0 · 2026-10-20\n\n" +
"> type: emergency\n> pin: yes\n> days: 7\n> migration: irreversible\n\n" +
"### en_us: Save layout change\n\n#### Changed\n\n- **Guild** data moves to a new table\n- See [notes](https://example.com/a)\n\n![chart](https://example.com/a.png)\n\n" +
"### zh_cn: 存档结构调整\n\n#### 调整\n\n- **公会**数据迁移到新表\n\n" +
"## client 2.36.7+client.0.2.0 · 2026-10-15\n\n" +
"### en_us:\n\n- Fixed the login screen\n"
func parseSample(t *testing.T) (server, client Entry) {
t.Helper()
entries, err := ParseChangelog([]byte(sampleChangelog))
if err != nil {
t.Fatal(err)
}
if len(entries) != 2 {
t.Fatalf("parsed %d entries, want 2 (a heading inside a code block is not a release)", len(entries))
}
return entries[0], entries[1]
}
func TestChangelogMetadataSetsNoticeFieldsAndMigration(t *testing.T) {
server, _ := parseSample(t)
if server.Type != NoticeEmergency || !server.Pinned || server.Days != 7 {
t.Errorf("server metadata = %+v", server)
}
if server.Migration != MigrationIrreversible || !server.Backup {
t.Errorf("an irreversible migration must require a backup: %+v", server)
}
if want := time.Date(2026, 10, 20, 0, 0, 0, 0, ChangelogZone); !server.StartsAt().Equal(want) || !server.EndsAt().Equal(want.AddDate(0, 0, 7)) {
t.Errorf("notice window = %v..%v", server.StartsAt(), server.EndsAt())
}
if server.NoticeID() <= 0 {
t.Errorf("notice ID %d must be positive", server.NoticeID())
}
}
func TestChangelogKeepsEachLanguageSeparately(t *testing.T) {
server, client := parseSample(t)
titles := server.Titles()
if titles["en_us"] != "Save layout change" || titles["zh_cn"] != "存档结构调整" {
t.Errorf("titles = %v", titles)
}
if notes := server.Notes(); !strings.Contains(notes["zh_cn"], "公会") || strings.Contains(notes["en_us"], "公会") {
t.Errorf("notes mixed languages: %v", notes)
}
if _, ok := client.Text["zh_cn"]; ok || client.Titles()["en_us"] == "" {
t.Errorf("an untitled English-only section must get a default English title and no other language: %+v", client.Text)
}
if server.NoticeID() == client.NoticeID() {
t.Error("two releases share a notice ID")
}
}
func TestChangelogRequiresTheEnglishFallback(t *testing.T) {
raw := "## server 2.36.7+server.0.3.0 · 2026-10-20\n\n### zh_cn: 仅中文\n\n- 内容\n"
if _, err := ParseChangelog([]byte(raw)); err == nil || !strings.Contains(err.Error(), "en_us") {
t.Fatalf("a section without en_us = %v; want an error naming en_us", err)
}
raw = "## server 2.36.7+server.0.3.0 · 2026-10-20\n\n### en_us: Update\n\n- Valid fallback\n\n### de_de: Nur Deutsch\n\n- Inhalt\n"
if _, err := ParseChangelog([]byte(raw)); err == nil || !strings.Contains(err.Error(), "de_de") {
t.Fatal("a language the game does not support was accepted")
}
}
func TestChangelogBodyBecomesRichTextAndImageBlocks(t *testing.T) {
server, _ := parseSample(t)
var text, images []string
for _, block := range server.Blocks("en_us") {
if block.Image {
images = append(images, block.Value)
} else {
text = append(text, block.Value)
}
}
if len(images) != 1 || images[0] != "https://example.com/a.png" {
t.Errorf("image blocks = %q; want the standalone image URL", images)
}
joined := strings.Join(text, "\n")
for _, raw := range []string{"**", "](", "###", "![", "\n- "} {
if strings.Contains(joined, raw) {
t.Errorf("text blocks still contain markdown %q: %q", raw, joined)
}
}
for _, want := range []string{"<b>Changed</b>", "<b>Guild</b>", "notes"} {
if !strings.Contains(joined, want) {
t.Errorf("text blocks lack %q: %q", want, joined)
}
}
}
func TestChangelogRejectsAnUnfilledTemplate(t *testing.T) {
template := ChangelogTemplate(ComponentServer, "2.36.7+server.0.3.0", time.Date(2026, 10, 20, 12, 0, 0, 0, time.UTC))
_, err := ParseChangelog([]byte(template))
if err == nil || !strings.Contains(err.Error(), "empty template item") {
t.Fatalf("unfilled template error = %v; want the empty template item error", err)
}
placeholder := regexp.MustCompile(`(?m)^- $`)
if !placeholder.MatchString(template) {
t.Fatal("test setup: the template has no placeholder items")
}
if _, err := ParseChangelog([]byte(placeholder.ReplaceAllString(template, "- filled"))); err != nil {
t.Fatalf("filled template: %v", err)
}
}
// Official notices are shown only when the release key signed exactly the
// changelog served, so a forged or edited changelog is not published.
func TestChangelogSignatureBindsTheExactContent(t *testing.T) {
seed, key, err := testSigner()
if err != nil {
t.Fatal(err)
}
signature, err := signChangelog([]byte(sampleChangelog), seed)
if err != nil {
t.Fatal(err)
}
if err := VerifyChangelog([]byte(sampleChangelog), signature, []TrustedKey{key}); err != nil {
t.Fatalf("genuine changelog rejected: %v", err)
}
forged := strings.Replace(sampleChangelog, "Save layout change", "Free diamonds", 1)
if err := VerifyChangelog([]byte(forged), signature, []TrustedKey{key}); err == nil {
t.Fatal("an edited changelog was accepted with the original signature")
}
otherSeed, _, err := testSigner()
if err != nil {
t.Fatal(err)
}
selfSigned, err := signChangelog([]byte(forged), otherSeed)
if err != nil {
t.Fatal(err)
}
if err := VerifyChangelog([]byte(forged), selfSigned, []TrustedKey{key}); err == nil {
t.Fatal("a changelog signed by an untrusted key was accepted")
}
manifest, err := signManifest(testManifest(), seed)
if err != nil {
t.Fatal(err)
}
var envelope Envelope
if err := json.Unmarshal(manifest, &envelope); err != nil {
t.Fatal(err)
}
reused, _ := json.Marshal(Detached{KeyID: envelope.KeyID, Signature: envelope.Signature})
if err := VerifyChangelog(envelope.Manifest, reused, []TrustedKey{key}); err == nil {
t.Fatal("a manifest signature was accepted as a changelog signature")
}
}
// The repository's CHANGELOG.md is served to every server as notices, so it
// must always parse.
func TestRepositoryChangelogParses(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("..", "..", "..", "..", "CHANGELOG.md"))
if err != nil {
t.Fatal(err)
}
if _, err := ParseChangelog(raw); err != nil {
t.Fatal(err)
}
}
func testSigner() (testSigningFunc, TrustedKey, error) {
public, private, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, TrustedKey{}, err
}
key := TrustedKey{ID: KeyID(public), PublicKey: base64.StdEncoding.EncodeToString(public)}
return func(message []byte) (Detached, error) {
return Detached{KeyID: key.ID, Signature: base64.StdEncoding.EncodeToString(ed25519.Sign(private, message))}, nil
}, key, nil
}
func TestSignedChangelogFallsBackWhenTheFirstMirrorWasTamperedWith(t *testing.T) {
signer, key, err := testSigner()
if err != nil {
t.Fatal(err)
}
signature, err := signChangelog([]byte(sampleChangelog), signer)
if err != nil {
t.Fatal(err)
}
var fallbackReads int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/bad.md":
_, _ = w.Write([]byte(strings.Replace(sampleChangelog, "Save layout change", "Forged notice", 1)))
case "/good.md":
fallbackReads++
_, _ = w.Write([]byte(sampleChangelog))
case "/bad.md.sig", "/good.md.sig":
_, _ = w.Write(signature)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
raw, _, source, err := FetchSigned(context.Background(), server.Client(), []string{server.URL + "/bad.md", server.URL + "/good.md"}, []TrustedKey{key})
if err != nil || source != server.URL+"/good.md" || string(raw) != sampleChangelog || fallbackReads != 1 {
t.Fatalf("a forged first mirror prevented the authentic fallback: source=%q fallback_reads=%d error=%v", source, fallbackReads, err)
}
}
type testSigningFunc func([]byte) (Detached, error)
func signManifest(manifest Manifest, signer testSigningFunc) ([]byte, error) {
if err := manifest.Validate(); err != nil {
return nil, err
}
payload, err := json.MarshalIndent(manifest, " ", " ")
if err != nil {
return nil, err
}
signature, err := signer(append([]byte(signingDomain), payload...))
if err != nil {
return nil, err
}
return json.MarshalIndent(Envelope{KeyID: signature.KeyID, Signature: signature.Signature, Manifest: payload}, "", " ")
}
func signChangelog(raw []byte, signer testSigningFunc) ([]byte, error) {
signature, err := signer(append([]byte(changelogDomain), raw...))
if err != nil {
return nil, err
}
return json.Marshal(signature)
}
+152
View File
@@ -0,0 +1,152 @@
package release
import (
"bytes"
"crypto/ed25519"
"crypto/sha256"
_ "embed"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"sync"
)
// Signing domains keep a manifest signature from validating a changelog and
// the reverse.
const (
signingDomain = "bd2-release-manifest-v1\n"
changelogDomain = "bd2-changelog-v1\n"
)
// ChangelogSignatureName is the detached signature published beside
// CHANGELOG.md; only notices it vouches for are shown as official.
const ChangelogSignatureName = "CHANGELOG.md.sig"
// Envelope is the published file. Manifest holds the exact signed bytes so
// that re-encoding can never change what was verified.
type Envelope struct {
KeyID string `json:"key_id"`
Signature string `json:"signature"`
Manifest json.RawMessage `json:"manifest"`
}
// Channel is the built-in release source: where manifests and changelogs are
// published and which keys may sign a manifest.
type Channel struct {
Name string `json:"name"`
ManifestURL string `json:"manifest_url"`
ChangelogURLs []string `json:"changelog_urls"`
TrustedKeys []TrustedKey `json:"trusted_keys"`
}
type TrustedKey struct {
ID string `json:"id"`
PublicKey string `json:"public_key"`
}
//go:embed channel.json
var channelJSON []byte
var builtin = sync.OnceValues(func() (Channel, error) {
var c Channel
decoder := json.NewDecoder(bytes.NewReader(channelJSON))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&c); err != nil {
return Channel{}, fmt.Errorf("release: built-in channel: %w", err)
}
for _, key := range c.TrustedKeys {
if _, err := decodePublicKey(key); err != nil {
return Channel{}, err
}
}
return c, nil
})
// BuiltinChannel is the channel compiled into this binary.
func BuiltinChannel() Channel {
c, err := builtin()
if err != nil {
panic(err)
}
return c
}
func decodePublicKey(key TrustedKey) (ed25519.PublicKey, error) {
raw, err := base64.StdEncoding.DecodeString(key.PublicKey)
if err != nil || len(raw) != ed25519.PublicKeySize || key.ID != KeyID(raw) {
return nil, fmt.Errorf("release: trusted key %q is invalid", key.ID)
}
return ed25519.PublicKey(raw), nil
}
// KeyID names a public key by the first 16 hex digits of its SHA-256.
func KeyID(public []byte) string {
sum := sha256.Sum256(public)
return hex.EncodeToString(sum[:8])
}
// Detached is a signature over a file published separately, such as the
// changelog served from Git hosting.
type Detached struct {
KeyID string `json:"key_id"`
Signature string `json:"signature"`
}
// VerifyChangelog accepts raw only with a signature from a trusted key.
func VerifyChangelog(raw, signature []byte, keys []TrustedKey) error {
var detached Detached
if err := json.Unmarshal(signature, &detached); err != nil {
return fmt.Errorf("release: changelog signature: %w", err)
}
public, err := trusted(detached.KeyID, keys)
if err != nil {
return err
}
sig, err := base64.StdEncoding.DecodeString(detached.Signature)
if err != nil || !ed25519.Verify(public, append([]byte(changelogDomain), raw...), sig) {
return errors.New("release: changelog signature does not match its content")
}
return nil
}
func trusted(id string, keys []TrustedKey) (ed25519.PublicKey, error) {
for _, key := range keys {
if key.ID == id {
return decodePublicKey(key)
}
}
if len(keys) == 0 {
return nil, errors.New("release: this build trusts no release key")
}
return nil, fmt.Errorf("release: signed by untrusted key %q", id)
}
// Verify checks raw against keys and returns the validated manifest.
func Verify(raw []byte, keys []TrustedKey) (Manifest, error) {
var envelope Envelope
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&envelope); err != nil {
return Manifest{}, fmt.Errorf("release: manifest envelope: %w", err)
}
public, err := trusted(envelope.KeyID, keys)
if err != nil {
return Manifest{}, err
}
signature, err := base64.StdEncoding.DecodeString(envelope.Signature)
if err != nil || !ed25519.Verify(public, append([]byte(signingDomain), envelope.Manifest...), signature) {
return Manifest{}, errors.New("release: manifest signature is invalid")
}
var manifest Manifest
decoder = json.NewDecoder(bytes.NewReader(envelope.Manifest))
decoder.DisallowUnknownFields()
if err := decoder.Decode(&manifest); err != nil {
return Manifest{}, fmt.Errorf("release: manifest: %w", err)
}
if err := manifest.Validate(); err != nil {
return Manifest{}, err
}
return manifest, nil
}
+98
View File
@@ -0,0 +1,98 @@
package release
import (
"fmt"
"regexp"
"strconv"
"strings"
)
var versionPattern = regexp.MustCompile(`^(?:([0-9]+\.[0-9]+\.[0-9]+)\+(client|server)\.)?([0-9]+\.[0-9]+\.[0-9]+)$`)
// Version is either a plain X.Y.Z plugin version or a component release such
// as 2.36.7+server.0.1.0, where the game version is compared first.
type Version struct {
Game [3]int
HasGame bool
Kind string
Component [3]int
raw string
}
func ParseVersion(raw string) (Version, error) {
match := versionPattern.FindStringSubmatch(raw)
if match == nil {
return Version{}, fmt.Errorf("release: invalid version %q", raw)
}
v := Version{Kind: match[2], raw: raw}
if match[1] != "" {
v.HasGame = true
v.Game = triple(match[1])
}
v.Component = triple(match[3])
return v, nil
}
func triple(raw string) [3]int {
var out [3]int
for i, part := range strings.SplitN(raw, ".", 3) {
out[i], _ = strconv.Atoi(part)
}
return out
}
func (v Version) String() string { return v.raw }
// Short drops the game prefix: 2.36.7+server.0.1.0 displays as 0.1.0.
func (v Version) Short() string {
if !v.HasGame {
return v.raw
}
return fmt.Sprintf("%d.%d.%d", v.Component[0], v.Component[1], v.Component[2])
}
// GameVersion returns the X.Y.Z game prefix, or "" for plain versions.
func (v Version) GameVersion() string {
if !v.HasGame {
return ""
}
return fmt.Sprintf("%d.%d.%d", v.Game[0], v.Game[1], v.Game[2])
}
// Compare orders versions of the same kind; a game update outranks any
// component number.
func (v Version) Compare(other Version) int {
if c := compareTriple(v.Game, other.Game); c != 0 {
return c
}
return compareTriple(v.Component, other.Component)
}
func compareTriple(a, b [3]int) int {
for i := range a {
if a[i] != b[i] {
if a[i] < b[i] {
return -1
}
return 1
}
}
return 0
}
// Newer reports whether candidate is a strictly newer release than current.
// Both must parse and be of the same kind.
func Newer(current, candidate string) (bool, error) {
a, err := ParseVersion(current)
if err != nil {
return false, err
}
b, err := ParseVersion(candidate)
if err != nil {
return false, err
}
if a.Kind != b.Kind || a.HasGame != b.HasGame {
return false, fmt.Errorf("release: cannot compare %q with %q", current, candidate)
}
return b.Compare(a) > 0, nil
}
+38 -1
View File
@@ -34,7 +34,10 @@ type Config struct {
BundleVersion string `json:"bundle_version"`
SeedDirectory string `json:"seed_directory"`
Plugins PluginVersions `json:"plugins"`
SourcePath string `json:"-"`
// MinimumPlugins is the oldest plugin build this server still works
// with; raise an entry only when a server change breaks older plugins.
MinimumPlugins PluginVersions `json:"minimum_plugins"`
SourcePath string `json:"-"`
}
type PluginVersions struct {
@@ -81,6 +84,11 @@ func (c Config) Validate() error {
return fmt.Errorf("%s must be a numeric three-part version", name)
}
}
for id, pair := range c.Plugins.pairs(c.MinimumPlugins) {
if !semanticVersion.MatchString(pair[1]) || compareSemantic(pair[1], pair[0]) > 0 {
return fmt.Errorf("minimum_plugins.%s must be a numeric three-part version no newer than plugins.%s", id, id)
}
}
if err := validateReleaseVersion("client_version", c.ClientVersion, c.GameVersion, "client"); err != nil {
return err
}
@@ -104,6 +112,35 @@ func (c Config) Validate() error {
return nil
}
// ByID lists the plugin versions under their versions.json keys.
func (p PluginVersions) ByID() map[string]string {
return map[string]string{"local_identity": p.LocalIdentity, "capture_environment": p.CaptureEnvironment, "login_ui": p.LoginUI, "cash_shop": p.CashShop, "fchat": p.FChat}
}
func (p PluginVersions) pairs(minimum PluginVersions) map[string][2]string {
current, lowest := p.ByID(), minimum.ByID()
out := map[string][2]string{}
for id, version := range current {
out[id] = [2]string{version, lowest[id]}
}
return out
}
func compareSemantic(a, b string) int {
var x, y [3]int
_, _ = fmt.Sscanf(a, "%d.%d.%d", &x[0], &x[1], &x[2])
_, _ = fmt.Sscanf(b, "%d.%d.%d", &y[0], &y[1], &y[2])
for i := range x {
if x[i] != y[i] {
if x[i] < y[i] {
return -1
}
return 1
}
}
return 0
}
func validateReleaseVersion(name, value, game, component string) error {
match := releaseVersion.FindStringSubmatch(value)
if len(match) != 4 || match[1] != game || match[2] != component {
+5
View File
@@ -4,6 +4,7 @@
package admin
import (
"bd2server/internal/common/i18n"
"context"
"crypto/subtle"
"embed"
@@ -91,6 +92,7 @@ type Console struct {
mu sync.Mutex
pending map[string]*pendingLogin
links map[string]time.Time
updates Updates
}
type pendingLogin struct {
@@ -137,6 +139,8 @@ func (c *Console) Handler() http.Handler {
mux := http.NewServeMux()
static, _ := fs.Sub(webFiles, "web")
files := http.FileServerFS(static)
mux.HandleFunc("GET /admin/assets/text.js", i18n.ServeBrowserScript)
mux.HandleFunc("POST /admin/api/text/format", i18n.TextHandler(webFiles, "web/assets/lang"))
mux.HandleFunc("GET /admin", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/admin/", http.StatusMovedPermanently)
})
@@ -161,6 +165,7 @@ func (c *Console) Handler() http.Handler {
mux.HandleFunc("GET /admin/api/server", c.require(owner, func(w http.ResponseWriter, r *http.Request, _ session) {
writeJSON(w, http.StatusOK, c.options.Server())
}))
c.registerUpdates(mux, owner)
mux.Handle("/admin/api/config/", c.require(func(s session) bool { return s.canReadConfiguration(c.options.Configuration) }, func(w http.ResponseWriter, r *http.Request, current session) {
http.StripPrefix("/admin/api/config", c.config).ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), sessionKey{}, current)))
}))
+90
View File
@@ -0,0 +1,90 @@
package admin
import (
"errors"
"log/slog"
"net/http"
"time"
"bd2server/internal/server/platform/updates"
)
// Updates is the server's release service as the console uses it.
type Updates interface {
Status() updates.Status
CheckNow()
Schedule(delay time.Duration, confirmIrreversible bool, by string) error
Cancel(by string) error
}
// AttachUpdates enables the owner's update page.
func (c *Console) AttachUpdates(service Updates) {
c.mu.Lock()
c.updates = service
c.mu.Unlock()
}
func (c *Console) updateService(w http.ResponseWriter) (Updates, bool) {
c.mu.Lock()
service := c.updates
c.mu.Unlock()
if service == nil {
fail(w, http.StatusNotFound, "unsupported", "update service unavailable")
}
return service, service != nil
}
func (c *Console) registerUpdates(mux *http.ServeMux, owner func(session) bool) {
mux.HandleFunc("GET /admin/api/updates", c.require(owner, func(w http.ResponseWriter, _ *http.Request, _ session) {
if service, ok := c.updateService(w); ok {
writeJSON(w, http.StatusOK, service.Status())
}
}))
mux.HandleFunc("POST /admin/api/updates/check", c.require(owner, func(w http.ResponseWriter, _ *http.Request, _ session) {
if service, ok := c.updateService(w); ok {
service.CheckNow()
writeJSON(w, http.StatusAccepted, map[string]bool{"ok": true})
}
}))
mux.HandleFunc("POST /admin/api/updates/apply", c.require(owner, func(w http.ResponseWriter, r *http.Request, current session) {
service, ok := c.updateService(w)
if !ok {
return
}
var request struct {
DelayMinutes int `json:"delay_minutes"`
ConfirmIrreversible bool `json:"confirm_irreversible"`
}
if !decode(w, r, &request) {
return
}
by := "console:" + current.AccountID
if err := service.Schedule(time.Duration(request.DelayMinutes)*time.Minute, request.ConfirmIrreversible, by); err != nil {
rejected(w, err)
return
}
slog.Info("update scheduled from console", "delay_minutes", request.DelayMinutes, "by", by)
writeJSON(w, http.StatusAccepted, service.Status())
}))
mux.HandleFunc("POST /admin/api/updates/cancel", c.require(owner, func(w http.ResponseWriter, _ *http.Request, current session) {
service, ok := c.updateService(w)
if !ok {
return
}
if err := service.Cancel("console:" + current.AccountID); err != nil {
rejected(w, err)
return
}
writeJSON(w, http.StatusOK, service.Status())
}))
}
// rejected answers with the rejection's code so the console can translate it.
func rejected(w http.ResponseWriter, err error) {
var rejection *updates.Rejection
if errors.As(err, &rejection) {
fail(w, http.StatusConflict, rejection.Code, rejection.Message)
return
}
fail(w, http.StatusInternalServerError, "unavailable", err.Error())
}
+13 -2
View File
@@ -6,6 +6,10 @@
--mono:ui-monospace,"Cascadia Mono","SF Mono",Consolas,monospace;
color-scheme:light dark;
}
:root:lang(ja){--sans:system-ui,-apple-system,"Segoe UI","Hiragino Sans","Yu Gothic UI","Meiryo UI","Noto Sans JP",sans-serif}
:root:lang(ko){--sans:system-ui,-apple-system,"Segoe UI","Apple SD Gothic Neo","Malgun Gothic","Noto Sans KR",sans-serif}
:root:lang(zh-TW){--sans:system-ui,-apple-system,"Segoe UI","PingFang TC","Microsoft JhengHei UI","Microsoft JhengHei","Noto Sans TC",sans-serif}
:lang(en) .send{letter-spacing:.08em}
@media (prefers-color-scheme:dark){:root{
--paper:#1a1916;--sheet:#22211d;--ink:#ebe6da;--ink-2:#bcb5a5;--muted:#8a8475;--line:#312f29;--line-2:#45413a;
--seal:#d26a50;--seal-ink:#1a1916;--seal-soft:#3b2620;--moss:#93b48a;--moss-soft:#24301f;--air:#7d9cbb;--amber:#d9b263;--amber-soft:#332a17;
@@ -36,6 +40,7 @@ h2{font-size:16px;font-weight:600;margin:0;letter-spacing:.06em}
.account .user::before{content:"";display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--moss);margin-right:8px;vertical-align:2px}
.account button{border:0;background:none;padding:0;color:var(--muted);cursor:pointer}
.account button:hover{color:var(--seal)}
.locale{margin-left:auto;font-size:13px;padding:4px 8px;color:var(--ink-2);background:transparent;border-color:var(--line)}
.desk{max-width:1200px;margin:0 auto;padding:12px 28px 96px}
.card{background:var(--sheet);border:1px solid var(--line);border-radius:14px}
@@ -152,8 +157,8 @@ mark{background:color-mix(in srgb,var(--seal) 22%,transparent);color:inherit;bor
.letter{margin-top:16px;border-top:1px solid var(--line);padding-top:10px}
.letter summary{cursor:pointer;list-style:none;display:flex;gap:10px;align-items:baseline;font-size:12.5px;color:var(--ink-2)}
.letter summary::-webkit-details-marker{display:none}
.letter summary::after{content:"展开";margin-left:auto;color:var(--muted);font-size:12px}
.letter[open] summary::after{content:"收起"}
.letter summary::after{content:attr(data-expand);margin-left:auto;color:var(--muted);font-size:12px}
.letter[open] summary::after{content:attr(data-collapse)}
#letter-peek{color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px}
.letter[open] #letter-peek{visibility:hidden}
.letter label{display:block;font-size:12px;color:var(--muted);margin-top:10px}
@@ -360,3 +365,9 @@ dialog.ask p{margin:0;color:var(--ink-2);font-size:13.5px}
.perm-table td{padding:5px 8px;border-bottom:1px solid var(--line)}
.perm-table .linkish{font-weight:400}
dialog.ask:has(.perm-editor){width:min(560px,calc(100vw - 32px))}
/* 版本更新 */
.updates .update-facts { display: grid; grid-template-columns: max-content 1fr; gap: .35rem 1.2rem; margin: 1rem 0; }
.updates pre.notes { white-space: pre-wrap; font: inherit; background: rgba(0, 0, 0, .03); padding: .8rem 1rem; border-radius: 6px; max-height: 22rem; overflow: auto; }
.updates .update-actions { display: flex; flex-wrap: wrap; align-items: center; gap: .8rem; margin-top: 1rem; }
.updates .update-actions input[type=number] { width: 5.5rem; }
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,502 @@
{
"console.title": "BD2 Console",
"console.brand": "Console",
"console.language": "Language",
"console.loading": "Loading…",
"console.list.separator": ", ",
"console.sentence.separator": "; ",
"console.copy.done": "%[1]s copied",
"console.copy.failed": "Couldn't copy. Please select the text manually.",
"console.dialog.ok": "OK",
"console.dialog.cancel": "Cancel",
"console.error.unauthorized": "Your session has expired. Please sign in again.",
"console.error.forbidden": "You don't have permission to do this.",
"console.error.csrf": "This page has expired. Please reload and try again.",
"console.error.rate_limited": "Too many attempts. Please try again later.",
"console.error.expired": "The sign-in has expired. Please start over.",
"console.error.rejected": "The sign-in was rejected or cancelled.",
"console.error.not_granted": "This game account is not an administrator and cannot enter the console. Ask the server owner for access.",
"console.error.not_found": "The player doesn't exist or has been deactivated.",
"console.error.invalid_permission": "The request contains an invalid permission.",
"console.error.invalid_item": "This item is not in the mailable catalog.",
"console.error.invalid_count": "The quantity must be between 1 and 2,147,483,647.",
"console.error.invalid_text": "The mail title and body cannot be empty.",
"console.error.read_only": "This file is read-only for the server.",
"console.error.unavailable": "The service is temporarily unavailable. Please try again later.",
"console.error.invalid": "Invalid request.",
"console.error.unsupported": "This server uses local authentication. Sign in with the one-time link printed when the server started.",
"console.error.notify_only": "The install method is notify-only, so updates can't be applied from here.",
"console.error.no_update": "No newer server release is available.",
"console.error.already_scheduled": "A maintenance is already scheduled.",
"console.error.irreversible_unconfirmed": "This release contains a save migration that cannot be rolled back. Read the migration note and confirm it first.",
"console.error.invalid_delay": "The countdown must be between 0 and 1,440 minutes (24 hours).",
"console.error.install_not_writable": "The server can't write to its install directory, so the update can't be applied.",
"console.error.no_maintenance": "No maintenance is scheduled.",
"console.error.maintenance_closing": "The maintenance is already draining and can no longer be cancelled.",
"console.error.http": "Request failed (%[1]s).",
"console.nav.mail": "Mail",
"console.nav.players": "Players",
"console.nav.config": "Server settings",
"console.nav.updates": "Updates",
"console.logout": "Sign out",
"console.role.owner": "Owner",
"console.role.admin": "Administrator",
"console.account.as_owner": "%[1]s (owner)",
"console.account.as_admin": "%[1]s (administrator)",
"console.logout.confirm.title": "Discard unsaved settings?",
"console.logout.confirm.body": "Signing out discards configuration changes that haven't been saved.",
"console.logout.confirm.ok": "Sign out",
"console.leave.title": "Save settings before leaving?",
"console.leave.body": "You have unsaved configuration changes. They stay on this page until you reload or sign out.",
"console.leave.ok": "Leave anyway",
"console.signin.title": "Enter the console",
"console.signin.loading": "Reading server information…",
"console.signin.local": "This server uses local authentication. Open the one-time sign-in link printed in the server console at startup.",
"console.signin.oauth": "Sign in with your game account. Only the server owner and administrators they appoint can enter.",
"console.signin.provider": "Sign in with %[1]s",
"console.signin.opening": "Opening the sign-in page…",
"console.signin.continue_in_popup": "Finish signing in in the new window. You'll be taken in here automatically.",
"console.signin.popup_blocked": "The browser blocked the new window. Click here: %[1]s",
"console.signin.open_page": "Open the sign-in page",
"console.signin.success": "Signed in.",
"console.signin.no_permissions": "The server owner hasn't given you any permissions yet.",
"console.mail.recipient": "Recipient",
"console.mail.copy_uid": "Click to copy the UID",
"console.mail.switch_player": "Switch player",
"console.mail.recipient.none": "No player can receive mail yet. Players appear here after they first sign in to the game.",
"console.mail.catalog": "Item catalog",
"console.mail.search.placeholder": "Name, ID, category or alias; separate words with spaces",
"console.mail.search.label": "Search items",
"console.mail.filter_label": "Filter by category",
"console.mail.recent": "Recently sent",
"console.mail.items_label": "Items",
"console.mail.catalog_loading": "Loading the item catalog…",
"console.mail.keys.search": "Search",
"console.mail.keys.pick": "Choose",
"console.mail.keys.add": "Add to slip",
"console.mail.keys.clear": "Clear",
"console.mail.category_all": "All",
"console.mail.category.currency": "Currency (credited directly)",
"console.mail.category.resource": "Resources",
"console.mail.category.food": "Dishes",
"console.mail.category.cooking": "Recipes",
"console.mail.category.random_box": "Random boxes",
"console.mail.category.quest_item": "Quest items",
"console.mail.category.use_item": "Usable items",
"console.mail.category.collection": "Collectibles",
"console.mail.category.my_room": "My Room items",
"console.mail.category.instant_use": "Instant-use items",
"console.mail.count.all": "%[1]s items",
"console.mail.count.matched": "%[1]s of %[2]s items",
"console.mail.count.showing": "showing the first %[1]s",
"console.mail.items.none": "No matching items",
"console.mail.items.none_in_category": "Only “%[1]s” is shown. Try switching back to “All”.",
"console.mail.aliases": "Also known as %[1]s",
"console.mail.detail.currency": "Added straight to the account balance when the mail is claimed; no inventory item is created.",
"console.mail.detail.direct": "Sends this item directly (no box to open)",
"console.mail.detail.original_name": "Original resource name: %[1]s",
"console.mail.detail.box_name": "Fixed box name: %[1]s",
"console.mail.detail.product_name": "Product name: %[1]s",
"console.mail.detail.boxes": "Fixed box mapping: %[1]s",
"console.mail.detail.boxes_more": "%[1]s, … (%[2]s in total)",
"console.mail.slip": "Parcel slip",
"console.mail.slip.to": "To UID",
"console.mail.parcel.empty": "Pick an item from the catalog to put it here",
"console.mail.parcel.search_hint": "or press %[1]s to search",
"console.mail.parcel.meta": "Type %[1]s · ID %[2]s",
"console.mail.parcel.remove": "Remove from slip",
"console.mail.quantity": "Quantity",
"console.mail.quantity.hint": "Accepts 5k, 2m",
"console.mail.quantity.positive": "Enter a positive whole number",
"console.mail.quantity.too_large": "Cannot exceed %[1]s",
"console.mail.presets.title": "Click to set this quantity; Shift-click to add it",
"console.mail.presets.thousand": "1k",
"console.mail.presets.ten_thousand": "10k",
"console.mail.letter": "Letter",
"console.mail.letter.expand": "Expand",
"console.mail.letter.collapse": "Collapse",
"console.mail.letter.title": "Mail title",
"console.mail.letter.body": "Body",
"console.mail.letter.default_title": "Test items",
"console.mail.letter.default_body": "Sent from the console.",
"console.mail.letter.untitled": "(untitled)",
"console.mail.send": "Send",
"console.mail.send.done": "Sent",
"console.mail.pick_first": "Pick an item to send from the catalog first.",
"console.mail.sent": "Sent to UID %[1]s. The player can claim it after refreshing the in-game mailbox; no server restart needed.",
"console.mail.lock.loading_player": "Loading player settings…",
"console.mail.lock.no_player": "No player can receive mail",
"console.inventory.unlimited": "Unlimited inventory capacity",
"console.mail.inventory.hint": "Affects only this player and takes effect the next time they sign in to the game; no server restart needed. Turning it off restores the player's original capacity.",
"console.mail.inventory.no_permission": "You don't have permission to change inventory capacity",
"console.mail.inventory.items": "Items",
"console.mail.inventory.equipment": "Equipment",
"console.mail.inventory.normal": "Normal capacity",
"console.mail.inventory.unlimited": "Unlimited mode",
"console.mail.inventory.saved": "Saved the setting for UID %[1]s. It takes effect after the player signs in to the game again.",
"console.mail.log.title": "Sent this session",
"console.mail.log.empty": "Items you send are listed here. Click a grant ID to copy it.",
"console.mail.log.count": "%[1]s sent",
"console.mail.log.meta": "%[1]s · to %[2]s",
"console.mail.log.again": "Send again",
"console.mail.log.again_title": "Put this item and quantity back on the slip",
"console.mail.log.identity": "Grant ID",
"console.mail.log.identity_title": "Click to copy the grant ID",
"console.roster.title": "Players",
"console.roster.lead": "Appoint administrators by game account; they sign in to the console with their own game account. Administrators can send mail and view players by default; the owner grants any other permission one by one.",
"console.roster.search.placeholder": "UID or name",
"console.roster.search.label": "Filter players",
"console.roster.col.uid": "UID",
"console.roster.col.name": "Name",
"console.roster.col.role": "Role",
"console.roster.col.admin": "Administrator",
"console.roster.col.unlimited": "Unlimited inventory",
"console.roster.inactive": "Deactivated",
"console.roster.permissions": "Permissions…",
"console.roster.mail": "Send mail →",
"console.roster.no_match": "No matching players",
"console.roster.empty": "No players yet. Players appear here after they first sign in to the game.",
"console.roster.summary.config_read": "Settings: %[1]s groups (read-only)",
"console.roster.summary.config_write": "Settings: %[1]s groups (%[2]s editable)",
"console.roster.summary.none": "No permissions",
"console.roster.revoke.title": "Revoke administrator?",
"console.roster.revoke.body": "UID %[1]s will be signed out of the console immediately and must be appointed again to return.",
"console.roster.revoke.ok": "Revoke",
"console.roster.appointed": "UID %[1]s is now an administrator (can send mail and view players by default)",
"console.roster.revoked": "Revoked administrator status from UID %[1]s",
"console.roster.permissions_updated": "Updated permissions for UID %[1]s; effective immediately",
"console.roster.unlimited_on": "Unlimited inventory turned on for UID %[1]s; takes effect at their next game sign-in",
"console.roster.unlimited_off": "Unlimited inventory turned off for UID %[1]s; takes effect at their next game sign-in",
"console.permission.players.view.label": "View players",
"console.permission.players.view.help": "See the player list, UIDs and inventory settings.",
"console.permission.players.view.short": "View players",
"console.permission.mail.send.label": "Send mail",
"console.permission.mail.send.help": "Send items and currency to any player.",
"console.permission.mail.send.short": "Mail",
"console.permission.players.inventory.label": "Adjust inventory capacity",
"console.permission.players.inventory.help": "Turn unlimited inventory capacity on or off for any player.",
"console.permission.players.inventory.short": "Inventory",
"console.permissions.title": "Permissions for UID %[1]s",
"console.permissions.save": "Save permissions",
"console.permissions.abilities": "Basic abilities",
"console.permissions.configuration": "Server settings",
"console.permissions.configuration_help": "Granted per group. Edit includes view; groups without view permission are hidden from this administrator.",
"console.permissions.owner_only": "Appointing and revoking administrators and the server overview are owner-only and cannot be granted.",
"console.permissions.toggle_all": "Toggle all",
"console.permissions.read": "View",
"console.permissions.write": "Edit",
"console.permissions.read_aria": "View %[1]s %[2]s",
"console.permissions.write_aria": "Edit %[1]s %[2]s",
"console.config.documents": "Configuration files",
"console.config.show_diff": "Review changes",
"console.config.discard": "Discard",
"console.config.save": "Save",
"console.config.modified": "Modified %[1]s",
"console.config.read_only": "Read-only",
"console.config.advanced": "Advanced options",
"console.config.locked": "🔒 Locked: %[1]s",
"console.config.on": "On",
"console.config.off": "Off",
"console.config.click_remove": "Click to remove",
"console.config.add_other": "Other scope, press Enter to add",
"console.config.selected": "%[1]s selected",
"console.config.select_all": "Select all",
"console.config.remove": "Remove",
"console.config.add": "+ Add",
"console.config.empty": "(empty)",
"console.config.example.gold": "Topping up %[1]s paid diamonds costs %[2]s gold",
"console.config.example.diamonds": "Topping up %[1]s paid diamonds costs %[2]s regular diamonds",
"console.config.example.free": "Topping up %[1]s paid diamonds: %[2]s",
"console.config.example.free_value": "free",
"console.config.example.ban": "Paid diamond top-ups: %[1]s",
"console.config.example.ban_value": "disabled",
"console.config.banner.pending.title": "Saved; waiting for a restart",
"console.config.banner.pending.body": "Changes to %[1]s have been written to disk, but the running server still uses the old settings. They take effect after the server process restarts.",
"console.config.banner.readonly.body": "The server can't write this file (for example, it is mounted read-only), so it can only be viewed here.",
"console.config.banner.broken.title": "The file on disk is currently invalid",
"console.config.banner.broken.body": "The file was changed outside the console to something the server can't load, so the next restart will fail. Fix the problems below and save.",
"console.config.banner.unchecked": "Couldn't validate",
"console.config.problem.at": "%[1]s: %[2]s",
"console.config.badge.unsaved": "Unsaved",
"console.config.badge.pending": "Restart pending",
"console.config.bar.problems": "%[1]s problems to fix",
"console.config.bar.changes": "%[1]s unsaved changes",
"console.config.bar.changes_files": "%[1]s unsaved changes (%[2]s files)",
"console.config.unset": "(not set)",
"console.config.diff.title": "Unsaved changes",
"console.config.diff.body": "After saving, the server must be restarted for changes to take effect.",
"console.config.diff.ok": "Got it",
"console.config.discard.title": "Discard all changes?",
"console.config.discard.body": "Unsaved configuration changes will be lost.",
"console.config.discard.ok": "Discard",
"console.config.save.title": "Save settings?",
"console.config.save.body": "This writes %[1]s. Changes take effect after the server restarts; make sure the settings are right before restarting.",
"console.config.save.ok": "Save",
"console.config.saved": "%[1]s saved; takes effect after the server restarts",
"console.config.conflict.title": "The file has changed",
"console.config.conflict.body": "%[1]s was changed by someone or something else while you were editing. Loading the latest version discards your changes to this file.",
"console.config.conflict.ok": "Load latest version",
"console.config.fix_needed": "Some settings need fixing",
"console.config.save_failed": "%[1]s: %[2]s",
"console.overview.title": "Server overview",
"console.overview.server_version": "Server version",
"console.overview.game_version": "Game version",
"console.overview.game_data_version": "GameData",
"console.overview.bundle_version": "Resource bundle",
"console.overview.auth_mode": "Authentication",
"console.overview.auth.oauth": "OAuth (online)",
"console.overview.auth.local": "Local single-player",
"console.overview.listen": "Listen address",
"console.overview.started_at": "Started",
"console.overview.data_dir": "Data directory",
"console.overview.mail_spool": "Mail queue",
"console.overview.dev_tools": "Development overrides",
"config.problem.item": "Item %[1]s: %[2]s",
"config.problem.enum": "This value isn't allowed",
"config.problem.enum_options": "Choose one of: %[1]s",
"config.problem.enum_key": "This entry isn't supported",
"config.problem.range": "Out of the allowed range",
"config.problem.range_between": "Must be a whole number from %[1]s to %[2]s",
"config.problem.required": "Required",
"config.problem.unique": "Contains duplicates",
"config.problem.format": "Invalid value: %[1]s",
"config.problem.conflict": "Conflicts with another setting",
"config.problem.locked": "Locked",
"config.problem.locked_reason": "Locked: %[1]s",
"config.problem.decode": "Invalid format: %[1]s",
"config.problem.custom": "Invalid: %[1]s",
"config.problem.forbidden": "You don't have permission to change this group",
"config.problem.environment": "The environment variable %[1]s isn't set in the running server process. Set it in the server environment before restarting after you save.",
"config.problem.environment_key": "The environment variable %[1]s in the running server process isn't a valid base64-encoded 32-byte key; the server will refuse to start after a restart.",
"config.problem.missing_file": "The server can't currently read this file: %[1]s",
"config.problem.message.bare_host": "Enter only the host name, without scheme, path or port",
"config.problem.message.host_port": "Use host:port, for example 0.0.0.0:8444",
"config.problem.message.plaintext_listen_loopback": "Plaintext mode can only listen on a loopback address",
"config.problem.message.plaintext_host_loopback": "In plaintext mode the public address must be a loopback IP",
"config.problem.message.tls_required": "Required unless local plaintext mode is enabled",
"config.problem.message.nonempty_path": "The path can't be empty",
"config.problem.message.required_by_provider": "Required when third-party moderation is enabled",
"config.problem.message.required_by_azure": "Required for Azure",
"config.problem.message.lowercase_identifier": "Use only lowercase letters, digits and underscores, starting with a letter",
"config.problem.message.local_no_oauth": "Can't be set in local mode",
"config.problem.message.required_oauth": "Required in OAuth mode",
"config.problem.message.oauth_provider": "Enable at least one sign-in provider",
"config.problem.message.absolute_origin": "Use a root address without a path, for example https://game.example.com",
"config.problem.message.https_origin": "Must use HTTPS except on localhost",
"config.problem.message.positive_duration": "Must be a positive duration, for example 15m or 720h",
"config.problem.message.official_origin": "Official mode can only use the official address",
"config.problem.message.required_server_mode": "Required when using a self-hosted resource source",
"config.problem.message.absolute_url": "Use a full HTTP(S) address without credentials, query or fragment",
"config.problem.message.no_trailing_slash": "Must not end with a slash",
"config.problem.message.https_url": "Must use HTTPS except for loopback addresses",
"config.problem.message.list": "Must be a list",
"config.problem.message.object": "Must be an object",
"config.problem.message.present": "Must be written explicitly in the file",
"config.problem.message.hidden_section": "A group you can't access has a problem. Ask the server owner to fix it.",
"config.game.title": "Game rules",
"config.game.summary": "Server-wide gameplay rules. Changes take effect after the server restarts.",
"config.game.section.story.title": "Opening chapter",
"config.game.section.story.help": "Stored permanently in the server state after the first successful initialization and can't be changed afterwards; deleting the database doesn't switch the opening.",
"config.game.field.story.start_pack_id.label": "Starting chapter",
"config.game.field.story.start_pack_id.option.21.label": "Shopkeeper story",
"config.game.field.story.start_pack_id.option.21.help": "The current client's default opening, using that story's quests and tutorial flow.",
"config.game.field.story.start_pack_id.option.1.label": "Old main story, chapter 1",
"config.game.field.story.start_pack_id.option.1.help": "Uses that chapter's opening story, starting quests and card-purchase rewards from the current GameData.",
"config.game.lock.story.start_pack_id": "Stored permanently in the server state after the first initialization; can no longer be changed",
"config.game.section.gacha.title": "Gacha",
"config.game.field.gacha.include_collaboration_ur_weapons.label": "Add collab signature weapons to guaranteed UR equipment tickets",
"config.game.field.gacha.include_collaboration_ur_weapons.help": "Adds 14 collaboration characters' UR signature weapons (equipment 943200–943213) to the original pool, each with the existing per-item weight for its rarity. Only changes the ticket's candidate pool; no equipment is granted directly.",
"config.game.section.purchases.title": "Paid diamond top-ups",
"config.game.section.purchases.help": "Regular cash products always cost paid diamonds, priced from GameData; this only sets how paid diamond top-ups themselves are exchanged.",
"config.game.field.purchases.diamond_recharge.currency.label": "Top-up method",
"config.game.field.purchases.diamond_recharge.currency.option.free.label": "Free",
"config.game.field.purchases.diamond_recharge.currency.option.free.help": "Charges no currency and grants the selected top-up product's original reward directly.",
"config.game.field.purchases.diamond_recharge.currency.option.gold.label": "Exchange for gold",
"config.game.field.purchases.diamond_recharge.currency.option.gold.help": "Each regular paid diamond costs the configured amount of gold.",
"config.game.field.purchases.diamond_recharge.currency.option.diamonds.label": "Exchange for regular diamonds",
"config.game.field.purchases.diamond_recharge.currency.option.diamonds.help": "Each regular paid diamond costs the configured amount of regular diamonds.",
"config.game.field.purchases.diamond_recharge.currency.option.ban.label": "Disable top-ups",
"config.game.field.purchases.diamond_recharge.currency.option.ban.help": "Blocks buying paid diamond top-up products; paid diamonds players already own are unaffected.",
"config.game.field.purchases.diamond_recharge.currency.option..label": "Disable top-ups (empty string)",
"config.game.field.purchases.diamond_recharge.currency.option..help": "Legacy spelling equivalent to ban.",
"config.game.field.purchases.diamond_recharge.gold_per_paid_diamond.label": "Gold per paid diamond",
"config.game.field.purchases.diamond_recharge.gold_per_paid_diamond.help": "Cost of each regular paid diamond when exchanging for gold. Must be valid even when not selected.",
"config.game.field.purchases.diamond_recharge.diamonds_per_paid_diamond.label": "Regular diamonds per paid diamond",
"config.game.field.purchases.diamond_recharge.diamonds_per_paid_diamond.help": "Cost of each regular paid diamond when exchanging for regular diamonds. Must be valid even when not selected.",
"config.game.section.realtime.title": "Real-time multiplayer",
"config.game.section.realtime.help": "Native TCP/UDP connections used by action minigames, online fishing and random defense. When off, no real-time ports are opened, which affects the player experience.",
"config.game.field.realtime.enabled.label": "Enable real-time multiplayer",
"config.game.field.realtime.public_host.label": "Public host name",
"config.game.field.realtime.public_host.help": "The host name players can reach, without scheme, path or port.",
"config.game.field.realtime.tcp_port.label": "Public TCP port",
"config.game.field.realtime.udp_port.label": "Public UDP port",
"config.game.field.realtime.tcp_listen.label": "TCP listen address",
"config.game.field.realtime.tcp_listen.help": "The public port may differ from the listen port, for port forwarding.",
"config.game.field.realtime.udp_listen.label": "UDP listen address",
"config.game.field.realtime.tls_cert_file.label": "TLS certificate",
"config.game.field.realtime.tls_cert_file.help": "A certificate matching the public host name and trusted by the client. Relative paths are resolved from the directory containing game.json; new handshakes pick up updates automatically.",
"config.game.field.realtime.tls_key_file.label": "TLS private key",
"config.game.field.realtime.tls_key_file.help": "The private key stays on the server and must be readable by the server process.",
"config.game.field.realtime.development_plain_loopback.label": "Local development plaintext mode",
"config.game.field.realtime.development_plain_loopback.help": "Local development only: both the listen and public addresses must be loopback IPs, and no certificate is needed.",
"config.game.section.text_moderation.title": "Text moderation",
"config.game.section.text_moderation.help": "Local rules run first; the third-party service is called only if they pass. Existing nicknames and bios aren't re-checked at sign-in.",
"config.game.field.text_moderation.rule_files.label": "Local word list files",
"config.game.field.text_moderation.rule_files.help": "UTF-8 .txt (one word per line, substring match) or .json (match mode and scope per entry), up to 4 MiB per file. Relative paths are resolved from the directory containing game.json.",
"config.game.field.text_moderation.provider.type.label": "Third-party moderation",
"config.game.field.text_moderation.provider.type.option.off.label": "Off",
"config.game.field.text_moderation.provider.type.option.http_json.label": "Generic HTTP JSON",
"config.game.field.text_moderation.provider.type.option.http_json.help": "Connects a self-hosted moderation service or a third-party adapter gateway.",
"config.game.field.text_moderation.provider.type.option.azure_content_safety.label": "Azure AI Content Safety",
"config.game.field.text_moderation.provider.endpoint.label": "Moderation endpoint",
"config.game.field.text_moderation.provider.endpoint.help": "Use HTTPS; HTTP is allowed only for loopback addresses, and redirects aren't followed. For Azure, enter the resource's root address.",
"config.game.field.text_moderation.provider.api_key_env.label": "API key environment variable",
"config.game.field.text_moderation.provider.api_key_env.help": "The server reads the key from this environment variable; the key itself is never stored in the configuration file.",
"config.game.field.text_moderation.provider.api_key_header.label": "API key header",
"config.game.field.text_moderation.provider.api_key_header.help": "The Authorization header sends Bearer <key>; any other header name passes the key as is.",
"config.game.field.text_moderation.provider.scopes.label": "Moderation scopes",
"config.game.field.text_moderation.provider.scopes.help": "The third party only checks the input sources listed explicitly.",
"config.game.field.text_moderation.provider.scopes.option.nickname.label": "Player nickname",
"config.game.field.text_moderation.provider.scopes.option.greeting.label": "Profile bio",
"config.game.field.text_moderation.provider.scopes.option.master_title.label": "Protagonist title",
"config.game.field.text_moderation.provider.scopes.option.preset_name.label": "Team preset name",
"config.game.field.text_moderation.provider.scopes.option.equipment_preset_name.label": "Equipment preset name",
"config.game.field.text_moderation.provider.scopes.option.equipment_mark.label": "Equipment mark",
"config.game.field.text_moderation.provider.scopes.option.monster_hunt_preset_name.label": "Monster hunt preset name",
"config.game.field.text_moderation.provider.scopes.option.guild_raid_preset_name.label": "Guild raid preset name",
"config.game.field.text_moderation.provider.scopes.option.colosseum_preset_name.label": "Colosseum preset name",
"config.game.field.text_moderation.provider.scopes.option.guild_name.label": "Guild name",
"config.game.field.text_moderation.provider.scopes.option.guild_message.label": "Guild description",
"config.game.field.text_moderation.provider.scopes.option.guild_notice.label": "Guild notice",
"config.game.field.text_moderation.provider.scopes.option.room_name.label": "Room name",
"config.game.field.text_moderation.provider.scopes.option.chat.label": "Online chat",
"config.game.field.text_moderation.provider.timeout_ms.label": "Timeout (ms)",
"config.game.field.text_moderation.provider.failure_policy.label": "When the service fails",
"config.game.field.text_moderation.provider.failure_policy.option.deny.label": "Reject changes for now",
"config.game.field.text_moderation.provider.failure_policy.option.deny.help": "The client reports that moderation is temporarily unavailable.",
"config.game.field.text_moderation.provider.failure_policy.option.allow.label": "Allow",
"config.game.field.text_moderation.provider.failure_policy.option.allow.help": "Lets through text that passed the local rules; explicit rejections are never let through.",
"config.game.field.text_moderation.provider.severity_threshold.label": "Azure rejection threshold",
"config.game.field.text_moderation.provider.severity_threshold.help": "Text is rejected when any category reaches this severity; 0 rejects even results with severity 0.",
"config.game.section.format.title": "Format",
"config.game.field.schema_version.label": "Format version",
"config.authentication.title": "Sign-in and authentication",
"config.authentication.summary": "How players sign in. Changes take effect after the server restarts; secrets are read only from environment variables and never written to this file.",
"config.authentication.section.mode.title": "Authentication mode",
"config.authentication.field.mode.label": "Mode",
"config.authentication.field.mode.option.local.label": "Local single-player",
"config.authentication.field.mode.option.local.help": "No sign-in; there is a single local player.",
"config.authentication.field.mode.option.oauth.label": "OAuth (online)",
"config.authentication.field.mode.option.oauth.help": "Players sign in with Discord or Google, and the server can host many players.",
"config.authentication.field.public_url.label": "Public URL",
"config.authentication.field.public_url.help": "The root address used by players and OAuth callbacks, without a path; must use HTTPS except on localhost.",
"config.authentication.field.master_key_env.label": "Master key environment variable",
"config.authentication.field.master_key_env.help": "This environment variable must hold a base64-encoded 32-byte key used to encrypt sign-in data.",
"config.authentication.section.providers.title": "Sign-in providers",
"config.authentication.section.providers.help": "The callback URL is <public URL>/auth/<provider>/callback.",
"config.authentication.field.providers.label": "Enabled providers",
"config.authentication.field.providers.*.client_id.label": "Client ID",
"config.authentication.field.providers.*.client_secret_env.label": "Client secret environment variable",
"config.authentication.section.session.title": "Session lifetimes",
"config.authentication.section.session.help": "Use Go duration format, for example 15m or 720h. Leave empty to use the default.",
"config.authentication.field.session.access_ttl.label": "Access token lifetime",
"config.authentication.field.session.refresh_ttl.label": "Refresh token lifetime",
"config.authentication.field.session.device_transaction_ttl.label": "Sign-in transaction lifetime",
"config.resources.title": "Client resources",
"config.resources.summary": "Where the client downloads ServerData and GameData. Changes take effect after the server restarts; version numbers come from versions.json and aren't set here.",
"config.resources.section.source.title": "Resource source",
"config.resources.field.mode.label": "Mode",
"config.resources.field.mode.option.official.label": "Official CDN",
"config.resources.field.mode.option.official.help": "Uses the official resource addresses for the current version.",
"config.resources.field.mode.option.server.label": "Self-hosted source",
"config.resources.field.mode.option.server.help": "Downloads from a static CDN or caching reverse proxy provided by the server owner.",
"config.resources.field.server_data_url.label": "ServerData URL",
"config.resources.field.server_data_url.help": "An absolute HTTP(S) address without a trailing slash; must use HTTPS except for loopback addresses.",
"config.resources.field.game_data_url.label": "GameData URL",
"config.resources.field.game_data_url.help": "An absolute HTTP(S) address without a trailing slash; must use HTTPS except for loopback addresses.",
"config.updates.title": "Updates",
"config.updates.summary": "How new releases are checked, pre-downloaded and installed during maintenance. Checking and downloading don't affect the game; applying an update must be confirmed in the console or on the command line. Changes take effect after the server restarts.",
"config.updates.section.check.title": "Checking and downloading",
"config.updates.field.check.label": "Check for new releases automatically",
"config.updates.field.check.help": "Checks the release manifest at startup and then at the configured interval, with a random offset.",
"config.updates.field.check_interval.label": "Check interval",
"config.updates.field.download.label": "Download in advance",
"config.updates.field.download.help": "Downloads and verifies a new release in the background so applying the update doesn't have to wait.",
"config.updates.field.manifest_url.label": "Release manifest URL",
"config.updates.field.manifest_url.help": "Leave empty to use the built-in address; the manifest signature must verify against the built-in public key.",
"config.updates.field.changelog_urls.label": "Changelog URLs",
"config.updates.field.changelog_urls.help": "Tried in order; leave empty to use the built-in GitHub and Gitea addresses.",
"config.updates.field.changelog.notices.label": "Post changelogs as in-game notices",
"config.updates.section.install.title": "Installation",
"config.updates.field.method.label": "Install method",
"config.updates.field.method.option.native.label": "Native (systemd)",
"config.updates.field.method.option.native.help": "Replaces the program files and exits so systemd restarts the new version; automatically switches back to the previous program if that fails.",
"config.updates.field.method.option.docker.label": "Docker",
"config.updates.field.method.option.docker.help": "Drains, saves and exits; a host script then switches to the image named in the manifest.",
"config.updates.field.method.option.none.label": "Notify only",
"config.updates.field.method.option.none.help": "Only checks and displays releases; updates can't be applied.",
"config.updates.field.countdown_minutes.label": "Default countdown (minutes)",
"config.updates.field.maintenance_minutes.label": "Expected maintenance length (minutes)",
"config.updates.field.webhook_url_env.label": "Webhook environment variable",
"config.updates.field.webhook_url_env.help": "When a new release is found, POSTs JSON once to the address held in this environment variable; leave empty to send nothing.",
"console.updates.title": "Updates",
"console.updates.lead": "The server checks the signed release manifest at an interval and can download and verify releases ahead of time. Applying an update first notifies online players, closes new sign-ins, drains requests and saves, then switches to the new version.",
"console.updates.check": "Check now",
"console.updates.fact.current_version": "Current version",
"console.updates.fact.method": "Install method",
"console.updates.fact.auto_check": "Automatic checks",
"console.updates.fact.last_check": "Last checked",
"console.updates.fact.check_error": "Check failed",
"console.updates.fact.last_switch": "Last switch",
"console.updates.enabled": "On",
"console.updates.disabled": "Off",
"console.updates.never_checked": "Not checked yet",
"console.updates.method.native": "Native (systemd)",
"console.updates.method.docker": "Docker",
"console.updates.method.none": "Notify only",
"console.updates.phase.preparing": "Preparing (download, verification and preflight)",
"console.updates.phase.countdown": "Counting down",
"console.updates.phase.closing": "Draining and switching",
"console.updates.outcome.succeeded": "Succeeded",
"console.updates.outcome.rolled_back": "Rolled back to the previous program",
"console.updates.outcome.needs_operator": "Needs manual attention",
"console.updates.outcome.awaiting_host": "Waiting for the host",
"console.updates.outcome.host_timed_out": "The host didn't switch",
"console.updates.outcome.switch_failed": "Switch failed",
"console.updates.outcome.cancelled": "Cancelled",
"console.updates.migration.none": "No save migration",
"console.updates.migration.reversible": "Save migration (reversible)",
"console.updates.migration.irreversible": "Save migration (irreversible)",
"console.updates.last_switch_value": "%[1]s → %[2]s: %[3]s",
"console.updates.last_switch_message": "%[1]s → %[2]s: %[3]s, %[4]s",
"console.updates.up_to_date": "You're on the latest version.",
"console.updates.available": "Version %[1]s available",
"console.updates.published": "Released %[1]s",
"console.updates.downloaded": "Downloaded and verified",
"console.updates.download_failed": "Download failed: %[1]s",
"console.updates.not_downloaded": "Not downloaded yet",
"console.updates.maintenance": "Maintenance: %[1]s → %[2]s (%[3]s)",
"console.updates.maintenance_at": "Maintenance: %[1]s → %[2]s, starting %[3]s (%[4]s)",
"console.updates.cancel": "Cancel maintenance",
"console.updates.delay": "Countdown (minutes)",
"console.updates.confirm_irreversible": "I have read the migration note and understand it can't be rolled back",
"console.updates.apply": "Apply update",
"console.updates.apply.title": "Apply the server update?",
"console.updates.apply.body_countdown": "Once preparation finishes, a %[1]s-minute countdown starts: online players see a maintenance notice, new sign-ins close in the last minute, then the server drains, saves and switches to %[2]s.",
"console.updates.apply.body_now": "Once preparation finishes, the server immediately closes new sign-ins, drains, saves and switches to %[1]s.",
"console.updates.scheduled": "Maintenance scheduled.",
"console.updates.cancelled": "Maintenance cancelled.",
"console.updates.checking": "Checking…"
}
@@ -0,0 +1,490 @@
{
"console.title": "BD2 コンソール",
"console.brand": "コンソール",
"console.language": "言語",
"console.loading": "読み込み中…",
"console.list.separator": "、 ",
"console.sentence.separator": "; ",
"console.copy.done": "%[1]s をコピーしました",
"console.copy.failed": "コピーできませんでした。テキストを手動で選択してください。",
"console.dialog.ok": "OK",
"console.dialog.cancel": "キャンセル",
"console.error.unauthorized": "セッションの有効期限が切れました。もう一度ログインしてください。",
"console.error.forbidden": "この操作を行う権限がありません。",
"console.error.csrf": "このページの有効期限が切れました。再読み込みしてから、もう一度お試しください。",
"console.error.rate_limited": "試行回数が多すぎます。しばらくしてから、もう一度お試しください。",
"console.error.expired": "ログインの有効期限が切れました。最初からやり直してください。",
"console.error.rejected": "ログインが拒否またはキャンセルされました。",
"console.error.not_granted": "このゲームアカウントには管理者権限がないため、コンソールに入れません。サーバー所有者にアクセス権を申請してください。",
"console.error.not_found": "プレイヤーが存在しないか、無効化されています。",
"console.error.invalid_permission": "リクエストに無効な権限が含まれています。",
"console.error.invalid_item": "このアイテムはメールで送れる一覧に含まれていません。",
"console.error.invalid_count": "数量は 1~2,147,483,647 の範囲で指定してください。",
"console.error.invalid_text": "メールの件名と本文は空にできません。",
"console.error.read_only": "サーバーはこのファイルに書き込めません。",
"console.error.unavailable": "サービスを一時的に利用できません。しばらくしてから、もう一度お試しください。",
"console.error.invalid": "無効なリクエストです。",
"console.error.unsupported": "このサーバーはローカル認証を使用しています。サーバー起動時に表示された使い捨てリンクからログインしてください。",
"console.error.notify_only": "インストール方法が「通知のみ」のため、ここからアップデートを適用できません。",
"console.error.no_update": "新しいサーバーリリースはありません。",
"console.error.already_scheduled": "すでにメンテナンスが予定されています。",
"console.error.irreversible_unconfirmed": "このリリースには元に戻せないセーブデータの移行が含まれています。先に移行に関する注意事項を読み、確認してください。",
"console.error.invalid_delay": "カウントダウンは 0~1,440 分(24 時間)の範囲で指定してください。",
"console.error.install_not_writable": "サーバーのインストール先に書き込めないため、アップデートを適用できません。",
"console.error.no_maintenance": "予定されているメンテナンスはありません。",
"console.error.maintenance_closing": "すでに処理の終了待ちに入っているため、メンテナンスをキャンセルできません。",
"console.error.http": "リクエストに失敗しました(%[1]s)。",
"console.nav.mail": "メール",
"console.nav.players": "プレイヤー",
"console.nav.config": "サーバー設定",
"console.nav.updates": "アップデート",
"console.logout": "ログアウト",
"console.role.owner": "所有者",
"console.role.admin": "管理者",
"console.account.as_owner": "%[1]s(所有者)",
"console.account.as_admin": "%[1]s(管理者)",
"console.logout.confirm.title": "未保存の設定を破棄しますか?",
"console.logout.confirm.body": "ログアウトすると、未保存の設定変更は失われます。",
"console.logout.confirm.ok": "ログアウト",
"console.leave.title": "移動する前に設定を保存しますか?",
"console.leave.body": "未保存の設定変更があります。ページを再読み込みするかログアウトするまでは、このページに保持されます。",
"console.leave.ok": "保存せずに移動",
"console.signin.title": "コンソールにログイン",
"console.signin.loading": "サーバー情報を読み込み中…",
"console.signin.local": "このサーバーはローカル認証を使用しています。起動時にサーバーコンソールに表示された使い捨てログインリンクを開いてください。",
"console.signin.oauth": "ゲームアカウントでログインしてください。サーバー所有者と、所有者が任命した管理者のみが利用できます。",
"console.signin.provider": "%[1]s でログイン",
"console.signin.opening": "ログインページを開いています…",
"console.signin.continue_in_popup": "新しいウィンドウでログインを完了してください。完了すると自動的にこちらに入れます。",
"console.signin.popup_blocked": "ブラウザーが新しいウィンドウをブロックしました。こちらをクリックしてください: %[1]s",
"console.signin.open_page": "ログインページを開く",
"console.signin.success": "ログインしました。",
"console.signin.no_permissions": "サーバー所有者からまだ権限が付与されていません。",
"console.mail.recipient": "宛先",
"console.mail.copy_uid": "クリックして UID をコピー",
"console.mail.switch_player": "プレイヤーを切り替え",
"console.mail.recipient.none": "まだメールを受け取れるプレイヤーがいません。初めてゲームにログインすると、ここに表示されます。",
"console.mail.catalog": "アイテム一覧",
"console.mail.search.placeholder": "名前、ID、カテゴリ、別名。複数の語句はスペースで区切ってください",
"console.mail.search.label": "アイテムを検索",
"console.mail.filter_label": "カテゴリで絞り込み",
"console.mail.recent": "最近送ったアイテム",
"console.mail.items_label": "アイテム",
"console.mail.catalog_loading": "アイテム一覧を読み込み中…",
"console.mail.keys.search": "検索",
"console.mail.keys.pick": "選択",
"console.mail.keys.add": "発送リストに追加",
"console.mail.keys.clear": "クリア",
"console.mail.category_all": "すべて",
"console.mail.category.currency": "通貨(残高に直接加算)",
"console.mail.category.resource": "素材",
"console.mail.category.food": "料理",
"console.mail.category.cooking": "レシピ",
"console.mail.category.random_box": "ランダムボックス",
"console.mail.category.quest_item": "クエストアイテム",
"console.mail.category.use_item": "使用可能アイテム",
"console.mail.category.collection": "収集品",
"console.mail.category.my_room": "マイルームアイテム",
"console.mail.category.instant_use": "即時使用アイテム",
"console.mail.count.all": "%[1]s 件",
"console.mail.count.matched": "%[2]s 件中 %[1]s 件",
"console.mail.count.showing": "先頭 %[1]s 件を表示",
"console.mail.items.none": "一致するアイテムがありません",
"console.mail.items.none_in_category": "「%[1]s」のみ表示しています。「すべて」に切り替えてみてください。",
"console.mail.aliases": "別名: %[1]s",
"console.mail.detail.currency": "メール受け取り時にアカウント残高へ直接加算されます。所持品にはアイテムを追加しません。",
"console.mail.detail.direct": "このアイテムを直接送ります(開封用の箱はありません)",
"console.mail.detail.original_name": "リソース内の元の名前: %[1]s",
"console.mail.detail.box_name": "固定報酬ボックス名: %[1]s",
"console.mail.detail.product_name": "商品名: %[1]s",
"console.mail.detail.boxes": "固定報酬ボックスの対応: %[1]s",
"console.mail.detail.boxes_more": "%[1]s、…(全 %[2]s 件)",
"console.mail.slip": "発送リスト",
"console.mail.slip.to": "宛先 UID",
"console.mail.parcel.empty": "一覧からアイテムを選ぶと、ここに追加されます",
"console.mail.parcel.search_hint": "または %[1]s を押して検索",
"console.mail.parcel.meta": "種類 %[1]s · ID %[2]s",
"console.mail.parcel.remove": "発送リストから削除",
"console.mail.quantity": "数量",
"console.mail.quantity.hint": "5k、2m なども入力できます",
"console.mail.quantity.positive": "正の整数を入力してください",
"console.mail.quantity.too_large": "%[1]s を超える値は指定できません",
"console.mail.presets.title": "クリックでこの数量を設定、Shift を押しながらクリックで加算",
"console.mail.presets.thousand": "1k",
"console.mail.presets.ten_thousand": "10k",
"console.mail.letter": "手紙",
"console.mail.letter.expand": "展開",
"console.mail.letter.collapse": "折りたたむ",
"console.mail.letter.title": "メールの件名",
"console.mail.letter.body": "本文",
"console.mail.letter.default_title": "テストアイテム",
"console.mail.letter.default_body": "コンソールから送信しました。",
"console.mail.letter.untitled": "(件名なし)",
"console.mail.send": "送信",
"console.mail.send.done": "送信済み",
"console.mail.pick_first": "まず一覧から送るアイテムを選んでください。",
"console.mail.sent": "UID %[1]s に送信しました。ゲーム内のメールボックスを更新すると受け取れます。サーバーの再起動は不要です。",
"console.mail.lock.loading_player": "プレイヤー設定を読み込み中…",
"console.mail.lock.no_player": "メールを受け取れるプレイヤーがいません",
"console.inventory.unlimited": "所持品の容量を無制限にする",
"console.mail.inventory.hint": "このプレイヤーのみに適用され、次回ゲームにログインしたときに反映されます。サーバーの再起動は不要です。無効にすると元の容量に戻ります。",
"console.mail.inventory.no_permission": "所持品の容量を変更する権限がありません",
"console.mail.inventory.items": "アイテム",
"console.mail.inventory.equipment": "装備",
"console.mail.inventory.normal": "通常の容量",
"console.mail.inventory.unlimited": "無制限モード",
"console.mail.inventory.saved": "UID %[1]s の設定を保存しました。プレイヤーがゲームに再ログインすると反映されます。",
"console.mail.log.title": "今回のセッションで送ったアイテム",
"console.mail.log.empty": "送ったアイテムはここに表示されます。付与 ID をクリックするとコピーできます。",
"console.mail.log.count": "%[1]s 件送信済み",
"console.mail.log.meta": "%[1]s · 宛先 %[2]s",
"console.mail.log.again": "もう一度送る",
"console.mail.log.again_title": "このアイテムと数量を発送リストに戻す",
"console.mail.log.identity": "付与 ID",
"console.mail.log.identity_title": "クリックして付与 ID をコピー",
"console.roster.title": "プレイヤー",
"console.roster.lead": "ゲームアカウントを指定して管理者を任命します。管理者は自分のゲームアカウントでコンソールにログインします。初期状態ではメールの送信とプレイヤーの閲覧ができ、その他の権限は所有者が個別に付与します。",
"console.roster.search.placeholder": "UID または名前",
"console.roster.search.label": "プレイヤーを絞り込み",
"console.roster.col.uid": "UID",
"console.roster.col.name": "名前",
"console.roster.col.role": "役割",
"console.roster.col.admin": "管理者",
"console.roster.col.unlimited": "所持品の容量無制限",
"console.roster.inactive": "無効化済み",
"console.roster.permissions": "権限…",
"console.roster.mail": "メールを送る →",
"console.roster.no_match": "一致するプレイヤーがいません",
"console.roster.empty": "まだプレイヤーがいません。初めてゲームにログインすると、ここに表示されます。",
"console.roster.summary.config_read": "設定: %[1]s グループ(読み取り専用)",
"console.roster.summary.config_write": "設定: %[1]s グループ(%[2]s グループを編集可能)",
"console.roster.summary.none": "権限なし",
"console.roster.revoke.title": "管理者の任命を取り消しますか?",
"console.roster.revoke.body": "UID %[1]s はコンソールから即座にログアウトされます。再び入るには、管理者として再任命する必要があります。",
"console.roster.revoke.ok": "任命を取り消す",
"console.roster.appointed": "UID %[1]s を管理者に任命しました(初期状態でメールの送信とプレイヤーの閲覧が可能)",
"console.roster.revoked": "UID %[1]s の管理者の任命を取り消しました",
"console.roster.permissions_updated": "UID %[1]s の権限を更新しました。すぐに反映されます",
"console.roster.unlimited_on": "UID %[1]s の所持品の容量制限を解除しました。次回のゲームログイン時に反映されます",
"console.roster.unlimited_off": "UID %[1]s の所持品の容量制限を有効にしました。次回のゲームログイン時に反映されます",
"console.permission.players.view.label": "プレイヤーを閲覧",
"console.permission.players.view.help": "プレイヤー一覧、UID、所持品の設定を確認できます。",
"console.permission.players.view.short": "プレイヤー閲覧",
"console.permission.mail.send.label": "メールを送信",
"console.permission.mail.send.help": "任意のプレイヤーにアイテムや通貨を送れます。",
"console.permission.mail.send.short": "メール",
"console.permission.players.inventory.label": "所持品の容量を変更",
"console.permission.players.inventory.help": "任意のプレイヤーの所持品の容量制限を切り替えられます。",
"console.permission.players.inventory.short": "所持品",
"console.permissions.title": "UID %[1]s の権限",
"console.permissions.save": "権限を保存",
"console.permissions.abilities": "基本権限",
"console.permissions.configuration": "サーバー設定",
"console.permissions.configuration_help": "グループ単位で付与します。編集権限には閲覧権限も含まれます。閲覧権限のないグループは、この管理者には表示されません。",
"console.permissions.owner_only": "管理者の任命・取り消しとサーバー概要の閲覧は所有者専用で、他の管理者には付与できません。",
"console.permissions.toggle_all": "すべて切り替え",
"console.permissions.read": "閲覧",
"console.permissions.write": "編集",
"console.permissions.read_aria": "%[1]s %[2]s を閲覧",
"console.permissions.write_aria": "%[1]s %[2]s を編集",
"console.config.documents": "設定ファイル",
"console.config.show_diff": "変更内容を確認",
"console.config.discard": "破棄",
"console.config.save": "保存",
"console.config.modified": "変更済み: %[1]s",
"console.config.read_only": "読み取り専用",
"console.config.advanced": "詳細オプション",
"console.config.locked": "🔒 ロック中: %[1]s",
"console.config.on": "オン",
"console.config.off": "オフ",
"console.config.click_remove": "クリックして削除",
"console.config.add_other": "他の対象を入力し、Enter キーで追加",
"console.config.selected": "%[1]s 件選択中",
"console.config.select_all": "すべて選択",
"console.config.remove": "削除",
"console.config.add": "+ 追加",
"console.config.empty": "(空)",
"console.config.example.gold": "有償ダイヤ %[1]s 個のチャージに %[2]s ゴールド必要",
"console.config.example.diamonds": "有償ダイヤ %[1]s 個のチャージに通常ダイヤ %[2]s 個必要",
"console.config.example.free": "有償ダイヤ %[1]s 個のチャージ: %[2]s",
"console.config.example.free_value": "無料",
"console.config.example.ban": "有償ダイヤのチャージ: %[1]s",
"console.config.example.ban_value": "無効",
"console.config.banner.pending.title": "保存済み・再起動待ち",
"console.config.banner.pending.body": "%[1]s の変更をディスクに保存しました。実行中のサーバーは以前の設定を使用しています。サーバープロセスを再起動すると反映されます。",
"console.config.banner.readonly.body": "サーバーがこのファイルに書き込めないため、ここでは閲覧のみ可能です(読み取り専用でマウントされている場合など)。",
"console.config.banner.broken.title": "ディスク上のファイルが無効です",
"console.config.banner.broken.body": "コンソール以外からファイルが変更され、サーバーが読み込めない状態です。このままでは次の再起動に失敗します。以下の問題を修正して保存してください。",
"console.config.banner.unchecked": "検証できませんでした",
"console.config.problem.at": "%[1]s: %[2]s",
"console.config.badge.unsaved": "未保存",
"console.config.badge.pending": "再起動待ち",
"console.config.bar.problems": "修正が必要な問題: %[1]s 件",
"console.config.bar.changes": "未保存の変更: %[1]s 件",
"console.config.bar.changes_files": "未保存の変更: %[1]s 件(%[2]s ファイル)",
"console.config.unset": "(未設定)",
"console.config.diff.title": "未保存の変更",
"console.config.diff.body": "保存後、変更を反映するにはサーバーの再起動が必要です。",
"console.config.diff.ok": "確認",
"console.config.discard.title": "すべての変更を破棄しますか?",
"console.config.discard.body": "未保存の設定変更は失われます。",
"console.config.discard.ok": "破棄",
"console.config.save.title": "設定を保存しますか?",
"console.config.save.body": "%[1]s に書き込みます。変更はサーバーの再起動後に反映されます。再起動前に設定が正しいか確認してください。",
"console.config.save.ok": "保存",
"console.config.saved": "%[1]s を保存しました。サーバーの再起動後に反映されます",
"console.config.conflict.title": "ファイルが変更されています",
"console.config.conflict.body": "編集中に %[1]s が別の操作やプログラムによって変更されました。最新版を読み込むと、このファイルへの編集内容は失われます。",
"console.config.conflict.ok": "最新版を読み込む",
"console.config.fix_needed": "修正が必要な設定があります",
"console.config.save_failed": "%[1]s: %[2]s",
"console.overview.title": "サーバー概要",
"console.overview.server_version": "サーバーバージョン",
"console.overview.game_version": "ゲームバージョン",
"console.overview.game_data_version": "GameData",
"console.overview.bundle_version": "リソースバンドル",
"console.overview.auth_mode": "認証方式",
"console.overview.auth.oauth": "OAuth(オンライン)",
"console.overview.auth.local": "ローカル・シングルプレイ",
"console.overview.listen": "待ち受けアドレス",
"console.overview.started_at": "起動日時",
"console.overview.data_dir": "データディレクトリ",
"console.overview.mail_spool": "メールキュー",
"console.overview.dev_tools": "開発用の上書き設定",
"config.problem.item": "項目 %[1]s: %[2]s",
"config.problem.enum": "この値は使用できません",
"config.problem.enum_options": "次から選択してください: %[1]s",
"config.problem.enum_key": "この項目には対応していません",
"config.problem.range": "許容範囲外です",
"config.problem.range_between": "%[1]s~%[2]s の整数を指定してください",
"config.problem.required": "必須です",
"config.problem.unique": "重複があります",
"config.problem.format": "無効な値: %[1]s",
"config.problem.conflict": "他の設定と競合しています",
"config.problem.locked": "ロック中",
"config.problem.locked_reason": "ロック中: %[1]s",
"config.problem.decode": "無効な形式: %[1]s",
"config.problem.custom": "無効: %[1]s",
"config.problem.forbidden": "このグループを変更する権限がありません",
"config.problem.environment": "実行中のサーバープロセスに環境変数 %[1]s が設定されていません。保存後に再起動する前に、サーバー環境で設定してください。",
"config.problem.environment_key": "実行中のサーバープロセスの環境変数 %[1]s が、有効な base64 エンコード済み 32 バイトキーではありません。このまま再起動すると、サーバーは起動を拒否します。",
"config.problem.missing_file": "現在サーバーがこのファイルを読み込めません: %[1]s",
"config.problem.message.bare_host": "ホスト名のみを入力してください。スキーム、パス、ポートは含めないでください",
"config.problem.message.host_port": "host:port 形式で指定してください(例: 0.0.0.0:8444)",
"config.problem.message.plaintext_listen_loopback": "平文モードではループバックアドレスのみで待ち受けできます",
"config.problem.message.plaintext_host_loopback": "平文モードでは公開アドレスにループバック IP を指定してください",
"config.problem.message.tls_required": "ローカル平文モード以外では必須です",
"config.problem.message.nonempty_path": "パスは空にできません",
"config.problem.message.required_by_provider": "外部のテキスト審査を有効にする場合は必須です",
"config.problem.message.required_by_azure": "Azure では必須です",
"config.problem.message.lowercase_identifier": "小文字、数字、アンダースコアのみを使用し、先頭は英字にしてください",
"config.problem.message.local_no_oauth": "ローカルモードでは設定できません",
"config.problem.message.required_oauth": "OAuth モードでは必須です",
"config.problem.message.oauth_provider": "ログインプロバイダーを少なくとも 1 つ有効にしてください",
"config.problem.message.absolute_origin": "パスを含まないルートアドレスを指定してください(例: https://game.example.com)",
"config.problem.message.https_origin": "localhost 以外では HTTPS が必須です",
"config.problem.message.positive_duration": "正の期間を指定してください(例: 15m、720h)",
"config.problem.message.official_origin": "公式モードでは公式アドレスのみ使用できます",
"config.problem.message.required_server_mode": "独自のリソース配信元を使用する場合は必須です",
"config.problem.message.absolute_url": "認証情報、クエリ、フラグメントを含まない完全な HTTP(S) アドレスを指定してください",
"config.problem.message.no_trailing_slash": "末尾にスラッシュは付けられません",
"config.problem.message.https_url": "ループバックアドレス以外では HTTPS が必須です",
"config.problem.message.list": "リストで指定してください",
"config.problem.message.object": "オブジェクトで指定してください",
"config.problem.message.present": "ファイルに明示的に記述してください",
"config.problem.message.hidden_section": "アクセスできないグループに問題があります。サーバー所有者に修正を依頼してください。",
"config.game.title": "ゲームルール",
"config.game.summary": "サーバー全体のゲームルールです。変更はサーバーの再起動後に反映されます。",
"config.game.section.story.title": "開始チャプター",
"config.game.section.story.help": "初回の初期化に成功するとサーバー状態に永続保存され、以降は変更できません。データベースを削除しても開始チャプターは変わりません。",
"config.game.field.story.start_pack_id.label": "開始チャプター",
"config.game.field.story.start_pack_id.option.21.label": "店主の物語",
"config.game.field.story.start_pack_id.option.21.help": "現在のクライアントの標準の導入です。この物語のクエストとチュートリアルの流れを使用します。",
"config.game.field.story.start_pack_id.option.1.label": "旧メインストーリー第 1 章",
"config.game.field.story.start_pack_id.option.1.help": "現在の GameData にある、この章の導入ストーリー、開始クエスト、カセット購入報酬を使用します。",
"config.game.lock.story.start_pack_id": "初回の初期化後にサーバー状態へ永続保存されるため、変更できません",
"config.game.section.gacha.title": "ガチャ",
"config.game.field.gacha.include_collaboration_ur_weapons.label": "UR 装備確定チケットにコラボ専用武器を追加",
"config.game.field.gacha.include_collaboration_ur_weapons.help": "コラボキャラクター 14 人の UR 専用武器(装備 943200~943213)を元の抽選対象に追加します。各武器の抽選重みには、同レアリティの既存アイテムの重みを使用します。チケットの抽選対象のみを変更し、装備を直接付与することはありません。",
"config.game.section.purchases.title": "有償ダイヤのチャージ",
"config.game.section.purchases.help": "通常の課金商品は常に有償ダイヤで購入し、価格は GameData に従います。ここでは有償ダイヤ自体のチャージ時の交換方法だけを設定します。",
"config.game.field.purchases.diamond_recharge.currency.label": "チャージ方法",
"config.game.field.purchases.diamond_recharge.currency.option.free.label": "無料",
"config.game.field.purchases.diamond_recharge.currency.option.free.help": "通貨を消費せず、選択したチャージ商品の元の報酬をそのまま付与します。",
"config.game.field.purchases.diamond_recharge.currency.option.gold.label": "ゴールドで交換",
"config.game.field.purchases.diamond_recharge.currency.option.gold.help": "通常分の有償ダイヤ 1 個につき、設定した量のゴールドを消費します。",
"config.game.field.purchases.diamond_recharge.currency.option.diamonds.label": "通常ダイヤで交換",
"config.game.field.purchases.diamond_recharge.currency.option.diamonds.help": "通常分の有償ダイヤ 1 個につき、設定した数の通常ダイヤを消費します。",
"config.game.field.purchases.diamond_recharge.currency.option.ban.label": "チャージを無効化",
"config.game.field.purchases.diamond_recharge.currency.option.ban.help": "有償ダイヤのチャージ商品の購入を禁止します。プレイヤーがすでに所持している有償ダイヤには影響しません。",
"config.game.field.purchases.diamond_recharge.currency.option..label": "チャージを無効化(空文字列)",
"config.game.field.purchases.diamond_recharge.currency.option..help": "ban と同じ意味の旧表記です。",
"config.game.field.purchases.diamond_recharge.gold_per_paid_diamond.label": "有償ダイヤ 1 個あたりのゴールド",
"config.game.field.purchases.diamond_recharge.gold_per_paid_diamond.help": "ゴールド交換時の、通常分の有償ダイヤ 1 個あたりの費用です。この方法を選択していない場合も有効な値が必要です。",
"config.game.field.purchases.diamond_recharge.diamonds_per_paid_diamond.label": "有償ダイヤ 1 個あたりの通常ダイヤ",
"config.game.field.purchases.diamond_recharge.diamonds_per_paid_diamond.help": "通常ダイヤ交換時の、通常分の有償ダイヤ 1 個あたりの費用です。この方法を選択していない場合も有効な値が必要です。",
"config.game.section.realtime.title": "リアルタイムマルチプレイ",
"config.game.section.realtime.help": "アクションミニゲーム、オンライン釣り、ランダムディフェンスで使用するネイティブ TCP/UDP 接続です。無効にするとリアルタイム用のポートを開かなくなり、プレイ体験に影響します。",
"config.game.field.realtime.enabled.label": "リアルタイムマルチプレイを有効化",
"config.game.field.realtime.public_host.label": "公開ホスト名",
"config.game.field.realtime.public_host.help": "プレイヤーが接続できるホスト名です。スキーム、パス、ポートは含めないでください。",
"config.game.field.realtime.tcp_port.label": "公開 TCP ポート",
"config.game.field.realtime.udp_port.label": "公開 UDP ポート",
"config.game.field.realtime.tcp_listen.label": "TCP 待ち受けアドレス",
"config.game.field.realtime.tcp_listen.help": "ポート転送を使用する場合、公開ポートと待ち受けポートが異なっていてもかまいません。",
"config.game.field.realtime.udp_listen.label": "UDP 待ち受けアドレス",
"config.game.field.realtime.tls_cert_file.label": "TLS 証明書",
"config.game.field.realtime.tls_cert_file.help": "公開ホスト名と一致し、クライアントが信頼する証明書です。相対パスは game.json のあるディレクトリを基準に解決されます。更新は新しいハンドシェイク時に自動で反映されます。",
"config.game.field.realtime.tls_key_file.label": "TLS 秘密鍵",
"config.game.field.realtime.tls_key_file.help": "秘密鍵はサーバー内に保持され、サーバープロセスから読み取れる必要があります。",
"config.game.field.realtime.development_plain_loopback.label": "ローカル開発用の平文モード",
"config.game.field.realtime.development_plain_loopback.help": "ローカル開発専用です。待ち受けアドレスと公開アドレスの両方にループバック IP が必要です。証明書は不要です。",
"config.game.section.text_moderation.title": "テキスト審査",
"config.game.section.text_moderation.help": "最初にローカルルールを実行し、通過した場合にのみ外部サービスに問い合わせます。既存のニックネームや自己紹介はログイン時に再審査しません。",
"config.game.field.text_moderation.rule_files.label": "ローカルの単語リストファイル",
"config.game.field.text_moderation.rule_files.help": "UTF-8 の .txt(1 行 1 語、部分一致)または .json(項目ごとに一致方式と対象を指定)に対応し、1 ファイルにつき最大 4 MiB です。相対パスは game.json のあるディレクトリを基準に解決されます。",
"config.game.field.text_moderation.provider.type.label": "外部のテキスト審査",
"config.game.field.text_moderation.provider.type.option.off.label": "オフ",
"config.game.field.text_moderation.provider.type.option.http_json.label": "汎用 HTTP JSON",
"config.game.field.text_moderation.provider.type.option.http_json.help": "独自の審査サービスや、外部サービスへの接続用ゲートウェイに接続します。",
"config.game.field.text_moderation.provider.type.option.azure_content_safety.label": "Azure AI Content Safety",
"config.game.field.text_moderation.provider.endpoint.label": "審査エンドポイント",
"config.game.field.text_moderation.provider.endpoint.help": "HTTPS を使用してください。HTTP はループバックアドレスのみ許可され、リダイレクトには従いません。Azure ではリソースのルートアドレスを入力してください。",
"config.game.field.text_moderation.provider.api_key_env.label": "API キーの環境変数",
"config.game.field.text_moderation.provider.api_key_env.help": "この環境変数からキーを読み取ります。キー自体が設定ファイルに保存されることはありません。",
"config.game.field.text_moderation.provider.api_key_header.label": "API キーヘッダー",
"config.game.field.text_moderation.provider.api_key_header.help": "Authorization ヘッダーには Bearer <key> を送信します。それ以外のヘッダー名ではキーをそのまま渡します。",
"config.game.field.text_moderation.provider.scopes.label": "審査対象",
"config.game.field.text_moderation.provider.scopes.help": "明示的に指定された入力元のみを外部サービスで審査します。",
"config.game.field.text_moderation.provider.scopes.option.nickname.label": "プレイヤーのニックネーム",
"config.game.field.text_moderation.provider.scopes.option.greeting.label": "プロフィールの自己紹介",
"config.game.field.text_moderation.provider.scopes.option.master_title.label": "主人公の称号",
"config.game.field.text_moderation.provider.scopes.option.preset_name.label": "チームプリセット名",
"config.game.field.text_moderation.provider.scopes.option.equipment_preset_name.label": "装備プリセット名",
"config.game.field.text_moderation.provider.scopes.option.equipment_mark.label": "装備のマーク",
"config.game.field.text_moderation.provider.scopes.option.monster_hunt_preset_name.label": "魔物追跡プリセット名",
"config.game.field.text_moderation.provider.scopes.option.guild_raid_preset_name.label": "ギルドレイドプリセット名",
"config.game.field.text_moderation.provider.scopes.option.colosseum_preset_name.label": "コロシアムプリセット名",
"config.game.field.text_moderation.provider.scopes.option.guild_name.label": "ギルド名",
"config.game.field.text_moderation.provider.scopes.option.guild_message.label": "ギルド紹介",
"config.game.field.text_moderation.provider.scopes.option.guild_notice.label": "ギルドのお知らせ",
"config.game.field.text_moderation.provider.scopes.option.room_name.label": "ルーム名",
"config.game.field.text_moderation.provider.scopes.option.chat.label": "オンラインチャット",
"config.game.field.text_moderation.provider.timeout_ms.label": "タイムアウト(ms)",
"config.game.field.text_moderation.provider.failure_policy.label": "サービス障害時の動作",
"config.game.field.text_moderation.provider.failure_policy.option.deny.label": "変更を一時的に拒否",
"config.game.field.text_moderation.provider.failure_policy.option.deny.help": "審査サービスが一時的に利用できないことをクライアントに通知します。",
"config.game.field.text_moderation.provider.failure_policy.option.allow.label": "許可",
"config.game.field.text_moderation.provider.failure_policy.option.allow.help": "ローカルルールを通過したテキストを許可します。明示的に拒否されたテキストは常に拒否します。",
"config.game.field.text_moderation.provider.severity_threshold.label": "Azure の拒否しきい値",
"config.game.field.text_moderation.provider.severity_threshold.help": "いずれかのカテゴリがこの重大度に達するとテキストを拒否します。0 を指定すると、重大度 0 の結果も拒否します。",
"config.game.section.format.title": "形式",
"config.game.field.schema_version.label": "形式のバージョン",
"config.authentication.title": "ログインと認証",
"config.authentication.summary": "プレイヤーのログイン方法を設定します。変更はサーバーの再起動後に反映されます。機密情報は環境変数からのみ読み取り、このファイルには保存しません。",
"config.authentication.section.mode.title": "認証モード",
"config.authentication.field.mode.label": "モード",
"config.authentication.field.mode.option.local.label": "ローカル・シングルプレイ",
"config.authentication.field.mode.option.local.help": "ログインは不要です。ローカルプレイヤー 1 人で利用します。",
"config.authentication.field.mode.option.oauth.label": "OAuth(オンライン)",
"config.authentication.field.mode.option.oauth.help": "Discord または Google でログインし、同じサーバーを複数のプレイヤーで利用できます。",
"config.authentication.field.public_url.label": "公開 URL",
"config.authentication.field.public_url.help": "プレイヤーと OAuth コールバックが使用する、パスを含まないルートアドレスです。localhost 以外では HTTPS が必須です。",
"config.authentication.field.master_key_env.label": "マスターキーの環境変数",
"config.authentication.field.master_key_env.help": "ログインデータの暗号化に使用する、base64 エンコード済みの 32 バイトキーをこの環境変数に設定してください。",
"config.authentication.section.providers.title": "ログインプロバイダー",
"config.authentication.section.providers.help": "コールバック URL は <public URL>/auth/<provider>/callback です。",
"config.authentication.field.providers.label": "有効なプロバイダー",
"config.authentication.field.providers.*.client_id.label": "クライアント ID",
"config.authentication.field.providers.*.client_secret_env.label": "クライアントシークレットの環境変数",
"config.authentication.section.session.title": "セッションの有効期間",
"config.authentication.section.session.help": "Go の期間形式で指定してください(例: 15m、720h)。空欄の場合は既定値を使用します。",
"config.authentication.field.session.access_ttl.label": "アクセストークンの有効期間",
"config.authentication.field.session.refresh_ttl.label": "リフレッシュトークンの有効期間",
"config.authentication.field.session.device_transaction_ttl.label": "ログイン処理の有効期間",
"config.resources.title": "クライアントリソース",
"config.resources.summary": "クライアントによる ServerData と GameData のダウンロード元を設定します。変更はサーバーの再起動後に反映されます。バージョン番号は versions.json から読み取り、ここでは設定しません。",
"config.resources.section.source.title": "リソースの取得元",
"config.resources.field.mode.label": "モード",
"config.resources.field.mode.option.official.label": "公式 CDN",
"config.resources.field.mode.option.official.help": "現在のバージョンの公式リソースアドレスを使用します。",
"config.resources.field.mode.option.server.label": "独自の配信元",
"config.resources.field.mode.option.server.help": "サーバー所有者が用意した静的 CDN またはキャッシュ機能付きリバースプロキシからダウンロードします。",
"config.resources.field.server_data_url.label": "ServerData URL",
"config.resources.field.server_data_url.help": "末尾のスラッシュを含まない絶対 HTTP(S) アドレスです。ループバックアドレス以外では HTTPS が必須です。",
"config.resources.field.game_data_url.label": "GameData URL",
"config.resources.field.game_data_url.help": "末尾のスラッシュを含まない絶対 HTTP(S) アドレスです。ループバックアドレス以外では HTTPS が必須です。",
"config.updates.title": "アップデート",
"config.updates.summary": "新リリースの確認、事前ダウンロード、メンテナンス中のインストール方法を設定します。確認とダウンロードはゲームに影響しません。適用にはコンソールまたはコマンドラインでの確認が必要です。設定変更はサーバーの再起動後に反映されます。",
"config.updates.section.check.title": "確認とダウンロード",
"config.updates.field.check.label": "新リリースを自動で確認",
"config.updates.field.check.help": "起動時と、以後は設定した間隔にランダムなずれを加えてリリースマニフェストを確認します。",
"config.updates.field.check_interval.label": "確認間隔",
"config.updates.field.download.label": "事前ダウンロード",
"config.updates.field.download.help": "新リリースをバックグラウンドでダウンロードして検証し、適用時の待ち時間を減らします。",
"config.updates.field.manifest_url.label": "リリースマニフェスト URL",
"config.updates.field.manifest_url.help": "空欄の場合は組み込みアドレスを使用します。マニフェストは組み込み公開鍵に対応する署名が必要です。",
"config.updates.field.changelog_urls.label": "変更履歴 URL",
"config.updates.field.changelog_urls.help": "上から順に試します。空欄の場合は組み込みの GitHub と Gitea のアドレスを使用します。",
"config.updates.field.changelog.notices.label": "変更履歴をゲーム内のお知らせに掲載",
"config.updates.section.install.title": "インストール",
"config.updates.field.method.label": "インストール方法",
"config.updates.field.method.option.native.label": "ネイティブ(systemd)",
"config.updates.field.method.option.native.help": "プログラムファイルを置き換えて終了し、systemd が新バージョンを起動します。失敗した場合は以前のプログラムに自動で戻します。",
"config.updates.field.method.option.docker.label": "Docker",
"config.updates.field.method.option.docker.help": "処理の終了を待ち、保存して終了します。その後、ホストのスクリプトがマニフェストに指定されたイメージに切り替えます。",
"config.updates.field.method.option.none.label": "通知のみ",
"config.updates.field.method.option.none.help": "リリースの確認と表示のみ行います。アップデートは適用できません。",
"config.updates.field.countdown_minutes.label": "既定のカウントダウン(分)",
"config.updates.field.maintenance_minutes.label": "メンテナンス予定時間(分)",
"config.updates.field.webhook_url_env.label": "Webhook の環境変数",
"config.updates.field.webhook_url_env.help": "新リリースを検出すると、この環境変数に設定されたアドレスへ JSON を 1 回 POST します。空欄の場合は送信しません。",
"console.updates.title": "アップデート",
"console.updates.lead": "サーバーは署名付きのリリースマニフェストを定期的に確認し、事前にリリースをダウンロードして検証できます。適用時はまずオンラインのプレイヤーに通知し、新規ログインを停止して処理の終了を待ち、保存してから新バージョンに切り替えます。",
"console.updates.check": "今すぐ確認",
"console.updates.fact.current_version": "現在のバージョン",
"console.updates.fact.method": "インストール方法",
"console.updates.fact.auto_check": "自動確認",
"console.updates.fact.last_check": "最終確認",
"console.updates.fact.check_error": "確認に失敗",
"console.updates.fact.last_switch": "前回の切り替え",
"console.updates.enabled": "オン",
"console.updates.disabled": "オフ",
"console.updates.never_checked": "未確認",
"console.updates.method.native": "ネイティブ(systemd)",
"console.updates.method.docker": "Docker",
"console.updates.method.none": "通知のみ",
"console.updates.phase.preparing": "準備中(ダウンロード・検証・事前確認)",
"console.updates.phase.countdown": "カウントダウン中",
"console.updates.phase.closing": "処理の終了待ち・切り替え中",
"console.updates.outcome.succeeded": "成功",
"console.updates.outcome.rolled_back": "以前のプログラムに戻しました",
"console.updates.outcome.needs_operator": "手動での対応が必要",
"console.updates.outcome.awaiting_host": "ホストの処理待ち",
"console.updates.outcome.host_timed_out": "ホストが切り替えを行いませんでした",
"console.updates.outcome.switch_failed": "切り替えに失敗",
"console.updates.outcome.cancelled": "キャンセル済み",
"console.updates.migration.none": "セーブデータの移行なし",
"console.updates.migration.reversible": "セーブデータの移行(元に戻せます)",
"console.updates.migration.irreversible": "セーブデータの移行(元に戻せません)",
"console.updates.last_switch_value": "%[1]s → %[2]s: %[3]s",
"console.updates.last_switch_message": "%[1]s → %[2]s: %[3]s、%[4]s",
"console.updates.up_to_date": "最新バージョンです。",
"console.updates.available": "バージョン %[1]s が利用可能です",
"console.updates.published": "%[1]s リリース",
"console.updates.downloaded": "ダウンロード・検証済み",
"console.updates.download_failed": "ダウンロード失敗: %[1]s",
"console.updates.not_downloaded": "未ダウンロード",
"console.updates.maintenance": "メンテナンス: %[1]s → %[2]s(%[3]s)",
"console.updates.maintenance_at": "メンテナンス: %[1]s → %[2]s、開始 %[3]s(%[4]s)",
"console.updates.cancel": "メンテナンスをキャンセル",
"console.updates.delay": "カウントダウン(分)",
"console.updates.confirm_irreversible": "移行に関する注意事項を読み、元に戻せないことを理解しました",
"console.updates.apply": "アップデートを適用",
"console.updates.apply.title": "サーバーのアップデートを適用しますか?",
"console.updates.apply.body_countdown": "準備が完了すると %[1]s 分のカウントダウンが始まります。オンラインのプレイヤーにメンテナンス通知を表示し、残り 1 分で新規ログインを停止します。その後、処理の終了を待って保存し、%[2]s に切り替えます。",
"console.updates.apply.body_now": "準備が完了すると、直ちに新規ログインを停止し、処理の終了を待って保存してから %[1]s に切り替えます。",
"console.updates.scheduled": "メンテナンスを予定しました。",
"console.updates.cancelled": "メンテナンスをキャンセルしました。",
"console.updates.checking": "確認中…"
}
@@ -0,0 +1,490 @@
{
"console.title": "BD2 콘솔",
"console.brand": "콘솔",
"console.language": "언어",
"console.loading": "불러오는 중…",
"console.list.separator": ", ",
"console.sentence.separator": "; ",
"console.copy.done": "%[1]s 복사 완료",
"console.copy.failed": "복사하지 못했습니다. 텍스트를 직접 선택해 주세요.",
"console.dialog.ok": "확인",
"console.dialog.cancel": "취소",
"console.error.unauthorized": "세션이 만료되었습니다. 다시 로그인해 주세요.",
"console.error.forbidden": "이 작업을 수행할 권한이 없습니다.",
"console.error.csrf": "페이지가 만료되었습니다. 새로 고침한 뒤 다시 시도해 주세요.",
"console.error.rate_limited": "시도 횟수가 너무 많습니다. 잠시 후 다시 시도해 주세요.",
"console.error.expired": "로그인 요청이 만료되었습니다. 처음부터 다시 진행해 주세요.",
"console.error.rejected": "로그인이 거부되거나 취소되었습니다.",
"console.error.not_granted": "이 게임 계정은 관리자가 아니므로 콘솔에 접속할 수 없습니다. 서버 소유자에게 권한을 요청하세요.",
"console.error.not_found": "플레이어가 존재하지 않거나 비활성화되었습니다.",
"console.error.invalid_permission": "요청에 유효하지 않은 권한이 포함되어 있습니다.",
"console.error.invalid_item": "메일로 보낼 수 없는 아이템입니다.",
"console.error.invalid_count": "수량은 1~2,147,483,647 사이여야 합니다.",
"console.error.invalid_text": "메일 제목과 본문은 비워 둘 수 없습니다.",
"console.error.read_only": "서버에서 이 파일은 읽기 전용입니다.",
"console.error.unavailable": "서비스를 일시적으로 사용할 수 없습니다. 잠시 후 다시 시도해 주세요.",
"console.error.invalid": "유효하지 않은 요청입니다.",
"console.error.unsupported": "이 서버는 로컬 인증을 사용합니다. 서버 시작 시 출력된 일회용 링크로 로그인하세요.",
"console.error.notify_only": "설치 방식이 '알림만'이므로 여기서 업데이트를 적용할 수 없습니다.",
"console.error.no_update": "새 서버 릴리스가 없습니다.",
"console.error.already_scheduled": "이미 점검이 예약되어 있습니다.",
"console.error.irreversible_unconfirmed": "이 릴리스에는 되돌릴 수 없는 저장 데이터 마이그레이션이 포함되어 있습니다. 먼저 마이그레이션 안내를 읽고 확인하세요.",
"console.error.invalid_delay": "카운트다운은 0~1,440분(24시간) 사이여야 합니다.",
"console.error.install_not_writable": "서버 설치 폴더에 쓸 수 없어 업데이트를 적용할 수 없습니다.",
"console.error.no_maintenance": "예약된 점검이 없습니다.",
"console.error.maintenance_closing": "이미 진행 중인 요청을 마무리하고 있어 점검을 취소할 수 없습니다.",
"console.error.http": "요청에 실패했습니다(%[1]s).",
"console.nav.mail": "메일",
"console.nav.players": "플레이어",
"console.nav.config": "서버 설정",
"console.nav.updates": "업데이트",
"console.logout": "로그아웃",
"console.role.owner": "소유자",
"console.role.admin": "관리자",
"console.account.as_owner": "%[1]s (소유자)",
"console.account.as_admin": "%[1]s (관리자)",
"console.logout.confirm.title": "저장하지 않은 설정을 버릴까요?",
"console.logout.confirm.body": "로그아웃하면 저장하지 않은 설정 변경 사항이 사라집니다.",
"console.logout.confirm.ok": "로그아웃",
"console.leave.title": "페이지를 나가기 전에 설정을 저장할까요?",
"console.leave.body": "저장하지 않은 설정 변경 사항이 있습니다. 새로 고침하거나 로그아웃할 때까지 이 페이지에 유지됩니다.",
"console.leave.ok": "그대로 나가기",
"console.signin.title": "콘솔 접속",
"console.signin.loading": "서버 정보를 읽는 중…",
"console.signin.local": "이 서버는 로컬 인증을 사용합니다. 시작 시 서버 콘솔에 출력된 일회용 로그인 링크를 여세요.",
"console.signin.oauth": "게임 계정으로 로그인하세요. 서버 소유자와 소유자가 지정한 관리자만 접속할 수 있습니다.",
"console.signin.provider": "%[1]s(으)로 로그인",
"console.signin.opening": "로그인 페이지를 여는 중…",
"console.signin.continue_in_popup": "새 창에서 로그인을 완료하세요. 완료되면 여기에 자동으로 접속됩니다.",
"console.signin.popup_blocked": "브라우저에서 새 창을 차단했습니다. 여기를 클릭하세요: %[1]s",
"console.signin.open_page": "로그인 페이지 열기",
"console.signin.success": "로그인되었습니다.",
"console.signin.no_permissions": "서버 소유자가 아직 권한을 부여하지 않았습니다.",
"console.mail.recipient": "받는 사람",
"console.mail.copy_uid": "클릭하여 UID 복사",
"console.mail.switch_player": "플레이어 변경",
"console.mail.recipient.none": "아직 메일을 받을 수 있는 플레이어가 없습니다. 게임에 처음 로그인하면 여기에 표시됩니다.",
"console.mail.catalog": "아이템 목록",
"console.mail.search.placeholder": "이름, ID, 분류 또는 별칭. 검색어는 공백으로 구분하세요",
"console.mail.search.label": "아이템 검색",
"console.mail.filter_label": "분류별 필터",
"console.mail.recent": "최근 발송",
"console.mail.items_label": "아이템",
"console.mail.catalog_loading": "아이템 목록을 불러오는 중…",
"console.mail.keys.search": "검색",
"console.mail.keys.pick": "선택",
"console.mail.keys.add": "발송 목록에 추가",
"console.mail.keys.clear": "지우기",
"console.mail.category_all": "전체",
"console.mail.category.currency": "재화 (잔액에 직접 지급)",
"console.mail.category.resource": "재료",
"console.mail.category.food": "요리",
"console.mail.category.cooking": "레시피",
"console.mail.category.random_box": "랜덤 상자",
"console.mail.category.quest_item": "퀘스트 아이템",
"console.mail.category.use_item": "사용 아이템",
"console.mail.category.collection": "수집품",
"console.mail.category.my_room": "마이룸 아이템",
"console.mail.category.instant_use": "즉시 사용 아이템",
"console.mail.count.all": "아이템 %[1]s개",
"console.mail.count.matched": "전체 %[2]s개 중 %[1]s개",
"console.mail.count.showing": "처음 %[1]s개 표시",
"console.mail.items.none": "일치하는 아이템이 없습니다",
"console.mail.items.none_in_category": "'%[1]s'만 표시 중입니다. '전체'로 전환해 보세요.",
"console.mail.aliases": "다른 이름: %[1]s",
"console.mail.detail.currency": "메일 수령 시 계정 잔액에 직접 추가되며 인벤토리 아이템은 생성되지 않습니다.",
"console.mail.detail.direct": "아이템을 직접 보냅니다 (개봉할 상자 없음)",
"console.mail.detail.original_name": "원본 리소스 이름: %[1]s",
"console.mail.detail.box_name": "고정 보상 상자 이름: %[1]s",
"console.mail.detail.product_name": "상품명: %[1]s",
"console.mail.detail.boxes": "고정 보상 상자 매핑: %[1]s",
"console.mail.detail.boxes_more": "%[1]s, … (총 %[2]s개)",
"console.mail.slip": "발송 목록",
"console.mail.slip.to": "받는 UID",
"console.mail.parcel.empty": "목록에서 아이템을 선택하면 여기에 추가됩니다",
"console.mail.parcel.search_hint": "또는 %[1]s 키를 눌러 검색",
"console.mail.parcel.meta": "종류 %[1]s · ID %[2]s",
"console.mail.parcel.remove": "발송 목록에서 제거",
"console.mail.quantity": "수량",
"console.mail.quantity.hint": "5k, 2m 형식 사용 가능",
"console.mail.quantity.positive": "양의 정수를 입력하세요",
"console.mail.quantity.too_large": "%[1]s을(를) 초과할 수 없습니다",
"console.mail.presets.title": "클릭하면 이 수량으로 설정하고 Shift를 누른 채 클릭하면 더합니다",
"console.mail.presets.thousand": "1k",
"console.mail.presets.ten_thousand": "10k",
"console.mail.letter": "편지",
"console.mail.letter.expand": "펼치기",
"console.mail.letter.collapse": "접기",
"console.mail.letter.title": "메일 제목",
"console.mail.letter.body": "본문",
"console.mail.letter.default_title": "테스트 아이템",
"console.mail.letter.default_body": "콘솔에서 보냈습니다.",
"console.mail.letter.untitled": "(제목 없음)",
"console.mail.send": "보내기",
"console.mail.send.done": "발송 완료",
"console.mail.pick_first": "먼저 목록에서 보낼 아이템을 선택하세요.",
"console.mail.sent": "UID %[1]s에 보냈습니다. 게임 내 우편함을 새로 고치면 수령할 수 있으며 서버를 재시작할 필요는 없습니다.",
"console.mail.lock.loading_player": "플레이어 설정을 불러오는 중…",
"console.mail.lock.no_player": "메일을 받을 수 있는 플레이어가 없습니다",
"console.inventory.unlimited": "인벤토리 용량 무제한",
"console.mail.inventory.hint": "이 플레이어에게만 적용되며 다음 게임 로그인 시 반영됩니다. 서버 재시작은 필요하지 않습니다. 끄면 원래 용량으로 돌아갑니다.",
"console.mail.inventory.no_permission": "인벤토리 용량을 변경할 권한이 없습니다",
"console.mail.inventory.items": "아이템",
"console.mail.inventory.equipment": "장비",
"console.mail.inventory.normal": "일반 용량",
"console.mail.inventory.unlimited": "무제한 모드",
"console.mail.inventory.saved": "UID %[1]s의 설정을 저장했습니다. 플레이어가 게임에 다시 로그인하면 적용됩니다.",
"console.mail.log.title": "이번 세션의 발송 내역",
"console.mail.log.empty": "보낸 아이템이 여기에 표시됩니다. 지급 ID를 클릭하면 복사됩니다.",
"console.mail.log.count": "%[1]s건 발송",
"console.mail.log.meta": "%[1]s · 받는 사람 %[2]s",
"console.mail.log.again": "다시 보내기",
"console.mail.log.again_title": "이 아이템과 수량을 발송 목록에 다시 추가",
"console.mail.log.identity": "지급 ID",
"console.mail.log.identity_title": "클릭하여 지급 ID 복사",
"console.roster.title": "플레이어",
"console.roster.lead": "게임 계정별로 관리자를 지정합니다. 관리자는 본인의 게임 계정으로 콘솔에 로그인합니다. 기본적으로 메일 발송과 플레이어 조회가 가능하며, 그 밖의 권한은 소유자가 개별적으로 부여합니다.",
"console.roster.search.placeholder": "UID 또는 이름",
"console.roster.search.label": "플레이어 필터",
"console.roster.col.uid": "UID",
"console.roster.col.name": "이름",
"console.roster.col.role": "역할",
"console.roster.col.admin": "관리자",
"console.roster.col.unlimited": "인벤토리 무제한",
"console.roster.inactive": "비활성화됨",
"console.roster.permissions": "권한…",
"console.roster.mail": "메일 보내기 →",
"console.roster.no_match": "일치하는 플레이어가 없습니다",
"console.roster.empty": "아직 플레이어가 없습니다. 게임에 처음 로그인하면 여기에 표시됩니다.",
"console.roster.summary.config_read": "설정: %[1]s개 그룹 (읽기 전용)",
"console.roster.summary.config_write": "설정: %[1]s개 그룹 (%[2]s개 편집 가능)",
"console.roster.summary.none": "권한 없음",
"console.roster.revoke.title": "관리자 지정을 해제할까요?",
"console.roster.revoke.body": "UID %[1]s은(는) 콘솔에서 즉시 로그아웃되며, 다시 접속하려면 관리자로 다시 지정해야 합니다.",
"console.roster.revoke.ok": "지정 해제",
"console.roster.appointed": "UID %[1]s을(를) 관리자로 지정했습니다 (기본적으로 메일 발송 및 플레이어 조회 가능)",
"console.roster.revoked": "UID %[1]s의 관리자 지정을 해제했습니다",
"console.roster.permissions_updated": "UID %[1]s의 권한을 변경했습니다. 즉시 적용됩니다",
"console.roster.unlimited_on": "UID %[1]s의 인벤토리 무제한을 켰습니다. 다음 게임 로그인 시 적용됩니다",
"console.roster.unlimited_off": "UID %[1]s의 인벤토리 무제한을 껐습니다. 다음 게임 로그인 시 적용됩니다",
"console.permission.players.view.label": "플레이어 조회",
"console.permission.players.view.help": "플레이어 목록, UID 및 인벤토리 설정을 확인합니다.",
"console.permission.players.view.short": "플레이어 조회",
"console.permission.mail.send.label": "메일 발송",
"console.permission.mail.send.help": "모든 플레이어에게 아이템과 재화를 보냅니다.",
"console.permission.mail.send.short": "메일",
"console.permission.players.inventory.label": "인벤토리 용량 조정",
"console.permission.players.inventory.help": "모든 플레이어의 인벤토리 무제한을 켜거나 끕니다.",
"console.permission.players.inventory.short": "인벤토리",
"console.permissions.title": "UID %[1]s의 권한",
"console.permissions.save": "권한 저장",
"console.permissions.abilities": "기본 권한",
"console.permissions.configuration": "서버 설정",
"console.permissions.configuration_help": "그룹별로 부여합니다. 편집 권한에는 조회 권한이 포함되며 조회 권한이 없는 그룹은 이 관리자에게 표시되지 않습니다.",
"console.permissions.owner_only": "관리자 지정 및 해제와 서버 개요 조회는 소유자 전용이며 다른 관리자에게 부여할 수 없습니다.",
"console.permissions.toggle_all": "전체 전환",
"console.permissions.read": "조회",
"console.permissions.write": "편집",
"console.permissions.read_aria": "%[1]s %[2]s 조회",
"console.permissions.write_aria": "%[1]s %[2]s 편집",
"console.config.documents": "설정 파일",
"console.config.show_diff": "변경 내용 검토",
"console.config.discard": "버리기",
"console.config.save": "저장",
"console.config.modified": "변경됨: %[1]s",
"console.config.read_only": "읽기 전용",
"console.config.advanced": "고급 옵션",
"console.config.locked": "🔒 잠김: %[1]s",
"console.config.on": "켜짐",
"console.config.off": "꺼짐",
"console.config.click_remove": "클릭하여 제거",
"console.config.add_other": "다른 검사 범위를 입력한 후 Enter로 추가",
"console.config.selected": "%[1]s개 선택됨",
"console.config.select_all": "전체 선택",
"console.config.remove": "제거",
"console.config.add": "+ 추가",
"console.config.empty": "(비어 있음)",
"console.config.example.gold": "유료 다이아 %[1]s개 충전에 골드 %[2]s 필요",
"console.config.example.diamonds": "유료 다이아 %[1]s개 충전에 일반 다이아 %[2]s개 필요",
"console.config.example.free": "유료 다이아 %[1]s개 충전: %[2]s",
"console.config.example.free_value": "무료",
"console.config.example.ban": "유료 다이아 충전: %[1]s",
"console.config.example.ban_value": "비활성화됨",
"console.config.banner.pending.title": "저장 완료 · 재시작 대기 중",
"console.config.banner.pending.body": "%[1]s의 변경 사항을 디스크에 저장했습니다. 실행 중인 서버는 이전 설정을 사용하며 서버 프로세스를 재시작하면 적용됩니다.",
"console.config.banner.readonly.body": "서버가 이 파일에 쓸 수 없어 여기서는 조회만 가능합니다 (예: 읽기 전용으로 마운트된 경우).",
"console.config.banner.broken.title": "디스크의 파일이 유효하지 않습니다",
"console.config.banner.broken.body": "콘솔 외부에서 파일이 변경되어 서버가 읽을 수 없습니다. 이대로는 다음 재시작이 실패합니다. 아래 문제를 수정하고 저장하세요.",
"console.config.banner.unchecked": "검증하지 못했습니다",
"console.config.problem.at": "%[1]s: %[2]s",
"console.config.badge.unsaved": "저장 안 됨",
"console.config.badge.pending": "재시작 대기",
"console.config.bar.problems": "수정할 문제 %[1]s개",
"console.config.bar.changes": "저장하지 않은 변경 사항 %[1]s개",
"console.config.bar.changes_files": "저장하지 않은 변경 사항 %[1]s개 (파일 %[2]s개)",
"console.config.unset": "(설정 안 됨)",
"console.config.diff.title": "저장하지 않은 변경 사항",
"console.config.diff.body": "저장 후 변경 사항을 적용하려면 서버를 재시작해야 합니다.",
"console.config.diff.ok": "확인",
"console.config.discard.title": "모든 변경 사항을 버릴까요?",
"console.config.discard.body": "저장하지 않은 설정 변경 사항이 사라집니다.",
"console.config.discard.ok": "버리기",
"console.config.save.title": "설정을 저장할까요?",
"console.config.save.body": "%[1]s에 기록합니다. 서버 재시작 후 적용되므로 재시작 전에 설정이 올바른지 확인하세요.",
"console.config.save.ok": "저장",
"console.config.saved": "%[1]s 저장 완료. 서버 재시작 후 적용됩니다",
"console.config.conflict.title": "파일이 변경되었습니다",
"console.config.conflict.body": "편집 중 다른 사용자나 프로그램이 %[1]s을(를) 변경했습니다. 최신 버전을 불러오면 이 파일의 편집 내용이 사라집니다.",
"console.config.conflict.ok": "최신 버전 불러오기",
"console.config.fix_needed": "수정이 필요한 설정이 있습니다",
"console.config.save_failed": "%[1]s: %[2]s",
"console.overview.title": "서버 개요",
"console.overview.server_version": "서버 버전",
"console.overview.game_version": "게임 버전",
"console.overview.game_data_version": "GameData",
"console.overview.bundle_version": "리소스 번들",
"console.overview.auth_mode": "인증 방식",
"console.overview.auth.oauth": "OAuth (온라인)",
"console.overview.auth.local": "로컬 싱글 플레이",
"console.overview.listen": "수신 대기 주소",
"console.overview.started_at": "시작 시각",
"console.overview.data_dir": "데이터 폴더",
"console.overview.mail_spool": "메일 대기열",
"console.overview.dev_tools": "개발용 재정의 설정",
"config.problem.item": "항목 %[1]s: %[2]s",
"config.problem.enum": "허용되지 않는 값입니다",
"config.problem.enum_options": "다음 중에서 선택하세요: %[1]s",
"config.problem.enum_key": "지원하지 않는 항목입니다",
"config.problem.range": "허용 범위를 벗어났습니다",
"config.problem.range_between": "%[1]s~%[2]s 사이의 정수여야 합니다",
"config.problem.required": "필수 항목입니다",
"config.problem.unique": "중복 항목이 있습니다",
"config.problem.format": "유효하지 않은 값: %[1]s",
"config.problem.conflict": "다른 설정과 충돌합니다",
"config.problem.locked": "잠김",
"config.problem.locked_reason": "잠김: %[1]s",
"config.problem.decode": "유효하지 않은 형식: %[1]s",
"config.problem.custom": "유효하지 않음: %[1]s",
"config.problem.forbidden": "이 그룹을 변경할 권한이 없습니다",
"config.problem.environment": "실행 중인 서버 프로세스에 환경 변수 %[1]s이(가) 설정되지 않았습니다. 저장 후 재시작하기 전에 서버 환경에 설정하세요.",
"config.problem.environment_key": "실행 중인 서버 프로세스의 환경 변수 %[1]s이(가) 유효한 base64 인코딩 32바이트 키가 아닙니다. 재시작하면 서버가 시작되지 않습니다.",
"config.problem.missing_file": "서버가 현재 이 파일을 읽을 수 없습니다: %[1]s",
"config.problem.message.bare_host": "호스트 이름만 입력하세요. 스킴, 경로, 포트는 포함하지 마세요",
"config.problem.message.host_port": "host:port 형식을 사용하세요. 예: 0.0.0.0:8444",
"config.problem.message.plaintext_listen_loopback": "평문 모드에서는 루프백 주소에서만 수신 대기할 수 있습니다",
"config.problem.message.plaintext_host_loopback": "평문 모드의 공개 주소는 루프백 IP여야 합니다",
"config.problem.message.tls_required": "로컬 평문 모드를 사용하지 않으면 필수입니다",
"config.problem.message.nonempty_path": "경로는 비워 둘 수 없습니다",
"config.problem.message.required_by_provider": "외부 텍스트 검사를 켜면 필수입니다",
"config.problem.message.required_by_azure": "Azure에서는 필수입니다",
"config.problem.message.lowercase_identifier": "소문자, 숫자, 밑줄만 사용하고 영문자로 시작하세요",
"config.problem.message.local_no_oauth": "로컬 모드에서는 설정할 수 없습니다",
"config.problem.message.required_oauth": "OAuth 모드에서는 필수입니다",
"config.problem.message.oauth_provider": "로그인 제공자를 하나 이상 활성화하세요",
"config.problem.message.absolute_origin": "경로 없는 루트 주소를 입력하세요. 예: https://game.example.com",
"config.problem.message.https_origin": "localhost 이외에는 HTTPS가 필수입니다",
"config.problem.message.positive_duration": "양의 시간 간격을 입력하세요. 예: 15m 또는 720h",
"config.problem.message.official_origin": "공식 모드에서는 공식 주소만 사용할 수 있습니다",
"config.problem.message.required_server_mode": "자체 호스팅 리소스 출처를 사용하면 필수입니다",
"config.problem.message.absolute_url": "인증 정보, 쿼리, 프래그먼트 없는 전체 HTTP(S) 주소를 입력하세요",
"config.problem.message.no_trailing_slash": "슬래시로 끝날 수 없습니다",
"config.problem.message.https_url": "루프백 주소 이외에는 HTTPS가 필수입니다",
"config.problem.message.list": "목록이어야 합니다",
"config.problem.message.object": "객체여야 합니다",
"config.problem.message.present": "파일에 명시적으로 작성해야 합니다",
"config.problem.message.hidden_section": "접근 권한이 없는 그룹에 문제가 있습니다. 서버 소유자에게 수정을 요청하세요.",
"config.game.title": "게임 규칙",
"config.game.summary": "서버 전체의 게임 규칙입니다. 변경 사항은 서버 재시작 후 적용됩니다.",
"config.game.section.story.title": "시작 챕터",
"config.game.section.story.help": "처음 초기화에 성공하면 서버 상태에 영구 저장되며 이후에는 변경할 수 없습니다. 데이터베이스를 삭제해도 시작 챕터는 바뀌지 않습니다.",
"config.game.field.story.start_pack_id.label": "시작 챕터",
"config.game.field.story.start_pack_id.option.21.label": "상점 주인 이야기",
"config.game.field.story.start_pack_id.option.21.help": "현재 클라이언트의 기본 시작 이야기입니다. 해당 이야기의 퀘스트와 튜토리얼 흐름을 사용합니다.",
"config.game.field.story.start_pack_id.option.1.label": "이전 메인 스토리 1장",
"config.game.field.story.start_pack_id.option.1.help": "현재 GameData에 있는 해당 챕터의 시작 이야기, 초기 퀘스트 및 팩 구매 보상을 사용합니다.",
"config.game.lock.story.start_pack_id": "첫 초기화 후 서버 상태에 영구 저장되어 더 이상 변경할 수 없습니다",
"config.game.section.gacha.title": "뽑기",
"config.game.field.gacha.include_collaboration_ur_weapons.label": "UR 장비 확정권에 콜라보 전용 무기 추가",
"config.game.field.gacha.include_collaboration_ur_weapons.help": "기존 추첨 목록에 콜라보 캐릭터 14명의 UR 전용 무기(장비 943200~943213)를 추가합니다. 각 무기의 가중치는 해당 희귀도의 기존 아이템별 가중치를 사용합니다. 확정권의 추첨 대상만 변경하며 장비를 직접 지급하지는 않습니다.",
"config.game.section.purchases.title": "유료 다이아 충전",
"config.game.section.purchases.help": "일반 유료 상품은 항상 유료 다이아로 구매하며 가격은 GameData를 따릅니다. 여기서는 유료 다이아 충전 자체의 교환 방식만 설정합니다.",
"config.game.field.purchases.diamond_recharge.currency.label": "충전 방식",
"config.game.field.purchases.diamond_recharge.currency.option.free.label": "무료",
"config.game.field.purchases.diamond_recharge.currency.option.free.help": "재화를 차감하지 않고 선택한 충전 상품의 원래 보상을 직접 지급합니다.",
"config.game.field.purchases.diamond_recharge.currency.option.gold.label": "골드로 교환",
"config.game.field.purchases.diamond_recharge.currency.option.gold.help": "기본 유료 다이아 1개당 설정된 수량의 골드를 사용합니다.",
"config.game.field.purchases.diamond_recharge.currency.option.diamonds.label": "일반 다이아로 교환",
"config.game.field.purchases.diamond_recharge.currency.option.diamonds.help": "기본 유료 다이아 1개당 설정된 수량의 일반 다이아를 사용합니다.",
"config.game.field.purchases.diamond_recharge.currency.option.ban.label": "충전 비활성화",
"config.game.field.purchases.diamond_recharge.currency.option.ban.help": "유료 다이아 충전 상품의 구매를 차단합니다. 이미 보유한 유료 다이아에는 영향이 없습니다.",
"config.game.field.purchases.diamond_recharge.currency.option..label": "충전 비활성화 (빈 문자열)",
"config.game.field.purchases.diamond_recharge.currency.option..help": "ban과 같은 의미의 이전 표기입니다.",
"config.game.field.purchases.diamond_recharge.gold_per_paid_diamond.label": "유료 다이아 1개당 골드",
"config.game.field.purchases.diamond_recharge.gold_per_paid_diamond.help": "골드로 교환할 때 기본 유료 다이아 1개에 필요한 비용입니다. 이 방식을 선택하지 않아도 유효한 값이어야 합니다.",
"config.game.field.purchases.diamond_recharge.diamonds_per_paid_diamond.label": "유료 다이아 1개당 일반 다이아",
"config.game.field.purchases.diamond_recharge.diamonds_per_paid_diamond.help": "일반 다이아로 교환할 때 기본 유료 다이아 1개에 필요한 비용입니다. 이 방식을 선택하지 않아도 유효한 값이어야 합니다.",
"config.game.section.realtime.title": "실시간 멀티플레이",
"config.game.section.realtime.help": "액션 미니게임, 온라인 낚시, 랜덤 디펜스에서 사용하는 네이티브 TCP/UDP 연결입니다. 끄면 실시간 포트를 열지 않아 플레이 경험에 영향을 줍니다.",
"config.game.field.realtime.enabled.label": "실시간 멀티플레이 활성화",
"config.game.field.realtime.public_host.label": "공개 호스트 이름",
"config.game.field.realtime.public_host.help": "플레이어가 접속할 수 있는 호스트 이름입니다. 스킴, 경로, 포트는 포함하지 마세요.",
"config.game.field.realtime.tcp_port.label": "공개 TCP 포트",
"config.game.field.realtime.udp_port.label": "공개 UDP 포트",
"config.game.field.realtime.tcp_listen.label": "TCP 수신 대기 주소",
"config.game.field.realtime.tcp_listen.help": "포트 포워딩을 위해 공개 포트와 수신 대기 포트가 달라도 됩니다.",
"config.game.field.realtime.udp_listen.label": "UDP 수신 대기 주소",
"config.game.field.realtime.tls_cert_file.label": "TLS 인증서",
"config.game.field.realtime.tls_cert_file.help": "공개 호스트 이름과 일치하며 클라이언트가 신뢰하는 인증서입니다. 상대 경로는 game.json이 있는 폴더를 기준으로 해석하며 새 핸드셰이크부터 갱신된 인증서가 자동 적용됩니다.",
"config.game.field.realtime.tls_key_file.label": "TLS 개인 키",
"config.game.field.realtime.tls_key_file.help": "개인 키는 서버에 보관하며 서버 프로세스에서 읽을 수 있어야 합니다.",
"config.game.field.realtime.development_plain_loopback.label": "로컬 개발용 평문 모드",
"config.game.field.realtime.development_plain_loopback.help": "로컬 개발 전용입니다. 수신 대기 주소와 공개 주소가 모두 루프백 IP여야 하며 인증서는 필요하지 않습니다.",
"config.game.section.text_moderation.title": "텍스트 검사",
"config.game.section.text_moderation.help": "로컬 규칙을 먼저 검사하고 통과한 경우에만 외부 서비스를 호출합니다. 기존 닉네임과 소개글은 로그인 시 다시 검사하지 않습니다.",
"config.game.field.text_moderation.rule_files.label": "로컬 단어 목록 파일",
"config.game.field.text_moderation.rule_files.help": "UTF-8 .txt(한 줄에 한 단어, 부분 문자열 일치) 또는 .json(항목별 일치 방식과 범위 지정)을 사용하며 파일당 최대 4 MiB입니다. 상대 경로는 game.json이 있는 폴더를 기준으로 해석합니다.",
"config.game.field.text_moderation.provider.type.label": "외부 텍스트 검사",
"config.game.field.text_moderation.provider.type.option.off.label": "꺼짐",
"config.game.field.text_moderation.provider.type.option.http_json.label": "범용 HTTP JSON",
"config.game.field.text_moderation.provider.type.option.http_json.help": "자체 호스팅 검사 서비스 또는 외부 연동 게이트웨이에 연결합니다.",
"config.game.field.text_moderation.provider.type.option.azure_content_safety.label": "Azure AI Content Safety",
"config.game.field.text_moderation.provider.endpoint.label": "검사 엔드포인트",
"config.game.field.text_moderation.provider.endpoint.help": "HTTPS를 사용하세요. HTTP는 루프백 주소에서만 허용하며 리디렉션은 따르지 않습니다. Azure는 리소스의 루트 주소를 입력하세요.",
"config.game.field.text_moderation.provider.api_key_env.label": "API 키 환경 변수",
"config.game.field.text_moderation.provider.api_key_env.help": "서버는 이 환경 변수에서 키를 읽으며 키 자체는 설정 파일에 저장하지 않습니다.",
"config.game.field.text_moderation.provider.api_key_header.label": "API 키 헤더",
"config.game.field.text_moderation.provider.api_key_header.help": "Authorization 헤더에는 Bearer <key>를 보내며 다른 헤더 이름에는 키를 그대로 전달합니다.",
"config.game.field.text_moderation.provider.scopes.label": "검사 범위",
"config.game.field.text_moderation.provider.scopes.help": "명시적으로 나열된 입력 출처만 외부 서비스에서 검사합니다.",
"config.game.field.text_moderation.provider.scopes.option.nickname.label": "플레이어 닉네임",
"config.game.field.text_moderation.provider.scopes.option.greeting.label": "프로필 소개글",
"config.game.field.text_moderation.provider.scopes.option.master_title.label": "주인공 칭호",
"config.game.field.text_moderation.provider.scopes.option.preset_name.label": "팀 프리셋 이름",
"config.game.field.text_moderation.provider.scopes.option.equipment_preset_name.label": "장비 프리셋 이름",
"config.game.field.text_moderation.provider.scopes.option.equipment_mark.label": "장비 표시",
"config.game.field.text_moderation.provider.scopes.option.monster_hunt_preset_name.label": "마물 추적 프리셋 이름",
"config.game.field.text_moderation.provider.scopes.option.guild_raid_preset_name.label": "길드 레이드 프리셋 이름",
"config.game.field.text_moderation.provider.scopes.option.colosseum_preset_name.label": "콜로세움 프리셋 이름",
"config.game.field.text_moderation.provider.scopes.option.guild_name.label": "길드 이름",
"config.game.field.text_moderation.provider.scopes.option.guild_message.label": "길드 소개",
"config.game.field.text_moderation.provider.scopes.option.guild_notice.label": "길드 공지",
"config.game.field.text_moderation.provider.scopes.option.room_name.label": "방 이름",
"config.game.field.text_moderation.provider.scopes.option.chat.label": "온라인 채팅",
"config.game.field.text_moderation.provider.timeout_ms.label": "시간 제한 (ms)",
"config.game.field.text_moderation.provider.failure_policy.label": "서비스 실패 시 동작",
"config.game.field.text_moderation.provider.failure_policy.option.deny.label": "변경을 일시적으로 거부",
"config.game.field.text_moderation.provider.failure_policy.option.deny.help": "클라이언트에 텍스트 검사를 일시적으로 사용할 수 없다고 알립니다.",
"config.game.field.text_moderation.provider.failure_policy.option.allow.label": "허용",
"config.game.field.text_moderation.provider.failure_policy.option.allow.help": "로컬 규칙을 통과한 텍스트를 허용합니다. 명시적으로 거부된 텍스트는 허용하지 않습니다.",
"config.game.field.text_moderation.provider.severity_threshold.label": "Azure 거부 기준값",
"config.game.field.text_moderation.provider.severity_threshold.help": "어느 한 범주라도 이 심각도에 도달하면 텍스트를 거부합니다. 0이면 심각도 0인 결과도 거부합니다.",
"config.game.section.format.title": "형식",
"config.game.field.schema_version.label": "형식 버전",
"config.authentication.title": "로그인 및 인증",
"config.authentication.summary": "플레이어의 로그인 방식을 설정합니다. 변경 사항은 서버 재시작 후 적용됩니다. 비밀 정보는 환경 변수에서만 읽으며 이 파일에는 기록하지 않습니다.",
"config.authentication.section.mode.title": "인증 모드",
"config.authentication.field.mode.label": "모드",
"config.authentication.field.mode.option.local.label": "로컬 싱글 플레이",
"config.authentication.field.mode.option.local.help": "로그인 없이 로컬 플레이어 한 명으로 이용합니다.",
"config.authentication.field.mode.option.oauth.label": "OAuth (온라인)",
"config.authentication.field.mode.option.oauth.help": "플레이어가 Discord 또는 Google로 로그인하며 서버에 여러 플레이어를 수용할 수 있습니다.",
"config.authentication.field.public_url.label": "공개 URL",
"config.authentication.field.public_url.help": "플레이어와 OAuth 콜백에서 사용하는 경로 없는 루트 주소입니다. localhost 이외에는 HTTPS가 필수입니다.",
"config.authentication.field.master_key_env.label": "마스터 키 환경 변수",
"config.authentication.field.master_key_env.help": "이 환경 변수에 로그인 데이터를 암호화할 base64 인코딩 32바이트 키를 설정해야 합니다.",
"config.authentication.section.providers.title": "로그인 제공자",
"config.authentication.section.providers.help": "콜백 URL은 <public URL>/auth/<provider>/callback입니다.",
"config.authentication.field.providers.label": "활성화된 제공자",
"config.authentication.field.providers.*.client_id.label": "클라이언트 ID",
"config.authentication.field.providers.*.client_secret_env.label": "클라이언트 시크릿 환경 변수",
"config.authentication.section.session.title": "세션 유효 기간",
"config.authentication.section.session.help": "Go의 시간 간격 형식을 사용하세요. 예: 15m 또는 720h. 비워 두면 기본값을 사용합니다.",
"config.authentication.field.session.access_ttl.label": "액세스 토큰 유효 기간",
"config.authentication.field.session.refresh_ttl.label": "갱신 토큰 유효 기간",
"config.authentication.field.session.device_transaction_ttl.label": "로그인 트랜잭션 유효 기간",
"config.resources.title": "클라이언트 리소스",
"config.resources.summary": "클라이언트가 ServerData와 GameData를 다운로드할 위치입니다. 변경 사항은 서버 재시작 후 적용됩니다. 버전 번호는 versions.json에서 읽으며 여기서 설정하지 않습니다.",
"config.resources.section.source.title": "리소스 출처",
"config.resources.field.mode.label": "모드",
"config.resources.field.mode.option.official.label": "공식 CDN",
"config.resources.field.mode.option.official.help": "현재 버전의 공식 리소스 주소를 사용합니다.",
"config.resources.field.mode.option.server.label": "자체 호스팅 출처",
"config.resources.field.mode.option.server.help": "서버 소유자가 제공하는 정적 CDN 또는 캐싱 리버스 프록시에서 다운로드합니다.",
"config.resources.field.server_data_url.label": "ServerData URL",
"config.resources.field.server_data_url.help": "끝에 슬래시가 없는 절대 HTTP(S) 주소입니다. 루프백 주소 이외에는 HTTPS가 필수입니다.",
"config.resources.field.game_data_url.label": "GameData URL",
"config.resources.field.game_data_url.help": "끝에 슬래시가 없는 절대 HTTP(S) 주소입니다. 루프백 주소 이외에는 HTTPS가 필수입니다.",
"config.updates.title": "업데이트",
"config.updates.summary": "새 릴리스의 확인, 사전 다운로드 및 점검 중 설치 방식을 설정합니다. 확인과 다운로드는 게임에 영향을 주지 않으며 적용 시 콘솔이나 명령줄에서 확인해야 합니다. 설정 변경은 서버 재시작 후 적용됩니다.",
"config.updates.section.check.title": "확인 및 다운로드",
"config.updates.field.check.label": "새 릴리스 자동 확인",
"config.updates.field.check.help": "시작 시 릴리스 매니페스트를 확인하고 이후 설정된 간격에 무작위 오프셋을 더해 확인합니다.",
"config.updates.field.check_interval.label": "확인 간격",
"config.updates.field.download.label": "미리 다운로드",
"config.updates.field.download.help": "새 릴리스를 백그라운드에서 다운로드하고 검증하여 적용할 때 기다리지 않도록 합니다.",
"config.updates.field.manifest_url.label": "릴리스 매니페스트 URL",
"config.updates.field.manifest_url.help": "비워 두면 내장 주소를 사용합니다. 매니페스트는 내장 공개 키로 검증할 수 있는 서명이 있어야 합니다.",
"config.updates.field.changelog_urls.label": "변경 내역 URL",
"config.updates.field.changelog_urls.help": "순서대로 시도합니다. 비워 두면 내장된 GitHub 및 Gitea 주소를 사용합니다.",
"config.updates.field.changelog.notices.label": "변경 내역을 게임 내 공지로 게시",
"config.updates.section.install.title": "설치",
"config.updates.field.method.label": "설치 방식",
"config.updates.field.method.option.native.label": "네이티브 (systemd)",
"config.updates.field.method.option.native.help": "프로그램 파일을 교체하고 종료하면 systemd가 새 버전을 시작합니다. 실패하면 이전 프로그램으로 자동 복구합니다.",
"config.updates.field.method.option.docker.label": "Docker",
"config.updates.field.method.option.docker.help": "진행 중인 요청을 마무리하고 저장한 뒤 종료합니다. 이후 호스트 스크립트가 매니페스트에 지정된 이미지로 전환합니다.",
"config.updates.field.method.option.none.label": "알림만",
"config.updates.field.method.option.none.help": "릴리스 확인과 표시만 하며 업데이트를 적용할 수 없습니다.",
"config.updates.field.countdown_minutes.label": "기본 카운트다운 (분)",
"config.updates.field.maintenance_minutes.label": "예상 점검 시간 (분)",
"config.updates.field.webhook_url_env.label": "Webhook 환경 변수",
"config.updates.field.webhook_url_env.help": "새 릴리스를 발견하면 이 환경 변수에 저장된 주소로 JSON을 한 번 POST합니다. 비워 두면 전송하지 않습니다.",
"console.updates.title": "업데이트",
"console.updates.lead": "서버는 서명된 릴리스 매니페스트를 주기적으로 확인하며 미리 다운로드하고 검증할 수 있습니다. 적용 시 접속 중인 플레이어에게 알리고 신규 로그인을 차단한 뒤 진행 중인 요청을 마무리하고 저장하여 새 버전으로 전환합니다.",
"console.updates.check": "지금 확인",
"console.updates.fact.current_version": "현재 버전",
"console.updates.fact.method": "설치 방식",
"console.updates.fact.auto_check": "자동 확인",
"console.updates.fact.last_check": "마지막 확인",
"console.updates.fact.check_error": "확인 실패",
"console.updates.fact.last_switch": "마지막 전환",
"console.updates.enabled": "켜짐",
"console.updates.disabled": "꺼짐",
"console.updates.never_checked": "아직 확인하지 않음",
"console.updates.method.native": "네이티브 (systemd)",
"console.updates.method.docker": "Docker",
"console.updates.method.none": "알림만",
"console.updates.phase.preparing": "준비 중 (다운로드, 검증 및 사전 점검)",
"console.updates.phase.countdown": "카운트다운 중",
"console.updates.phase.closing": "진행 중인 요청 마무리 및 전환 중",
"console.updates.outcome.succeeded": "성공",
"console.updates.outcome.rolled_back": "이전 프로그램으로 복구됨",
"console.updates.outcome.needs_operator": "수동 조치 필요",
"console.updates.outcome.awaiting_host": "호스트 대기 중",
"console.updates.outcome.host_timed_out": "호스트가 전환하지 않았습니다",
"console.updates.outcome.switch_failed": "전환 실패",
"console.updates.outcome.cancelled": "취소됨",
"console.updates.migration.none": "저장 데이터 마이그레이션 없음",
"console.updates.migration.reversible": "저장 데이터 마이그레이션 (복구 가능)",
"console.updates.migration.irreversible": "저장 데이터 마이그레이션 (복구 불가)",
"console.updates.last_switch_value": "%[1]s → %[2]s: %[3]s",
"console.updates.last_switch_message": "%[1]s → %[2]s: %[3]s, %[4]s",
"console.updates.up_to_date": "최신 버전입니다.",
"console.updates.available": "새 버전 %[1]s 사용 가능",
"console.updates.published": "%[1]s 출시",
"console.updates.downloaded": "다운로드 및 검증 완료",
"console.updates.download_failed": "다운로드 실패: %[1]s",
"console.updates.not_downloaded": "아직 다운로드하지 않음",
"console.updates.maintenance": "점검: %[1]s → %[2]s (%[3]s)",
"console.updates.maintenance_at": "점검: %[1]s → %[2]s, 시작 %[3]s (%[4]s)",
"console.updates.cancel": "점검 취소",
"console.updates.delay": "카운트다운 (분)",
"console.updates.confirm_irreversible": "마이그레이션 안내를 읽었으며 되돌릴 수 없음을 이해했습니다",
"console.updates.apply": "업데이트 적용",
"console.updates.apply.title": "서버 업데이트를 적용할까요?",
"console.updates.apply.body_countdown": "준비가 완료되면 %[1]s분 카운트다운을 시작합니다. 접속 중인 플레이어에게 점검 공지를 표시하고 마지막 1분 동안 신규 로그인을 차단한 뒤 진행 중인 요청을 마무리하고 저장하여 %[2]s(으)로 전환합니다.",
"console.updates.apply.body_now": "준비가 완료되면 즉시 신규 로그인을 차단하고 진행 중인 요청을 마무리한 뒤 저장하여 %[1]s(으)로 전환합니다.",
"console.updates.scheduled": "점검을 예약했습니다.",
"console.updates.cancelled": "점검을 취소했습니다.",
"console.updates.checking": "확인 중…"
}
@@ -0,0 +1,502 @@
{
"console.title": "BD2 管理台",
"console.brand": "管理台",
"console.language": "语言",
"console.loading": "正在读取……",
"console.list.separator": "、",
"console.sentence.separator": ";",
"console.copy.done": "%[1]s已复制",
"console.copy.failed": "复制失败,请手动选择",
"console.dialog.ok": "确定",
"console.dialog.cancel": "取消",
"console.error.unauthorized": "登录已过期,请重新登录。",
"console.error.forbidden": "没有权限执行这个操作。",
"console.error.csrf": "页面已过期,请刷新后重试。",
"console.error.rate_limited": "尝试太频繁,请稍后再试。",
"console.error.expired": "登录已过期,请重新开始。",
"console.error.rejected": "登录被拒绝或已取消。",
"console.error.not_granted": "这个游戏账号不是管理员,不能进入管理台。如需权限请联系服主。",
"console.error.not_found": "玩家不存在或已停用。",
"console.error.invalid_permission": "包含无效的权限。",
"console.error.invalid_item": "这件物品不在可寄送目录中。",
"console.error.invalid_count": "数量需在 1 到 2,147,483,647 之间。",
"console.error.invalid_text": "邮件标题和正文都不能为空。",
"console.error.read_only": "该文件对服务端只读。",
"console.error.unavailable": "服务暂不可用,请稍后再试。",
"console.error.invalid": "请求无效。",
"console.error.unsupported": "这台服务器使用本地认证,请用服务端启动时打印的一次性链接登录。",
"console.error.notify_only": "部署方式为仅通知,不能在这里应用更新。",
"console.error.no_update": "没有可用的新版本。",
"console.error.already_scheduled": "已经安排了一次维护。",
"console.error.irreversible_unconfirmed": "该版本包含不可回滚的存档迁移,请先阅读迁移说明并勾选确认。",
"console.error.invalid_delay": "倒计时需在 0 到 1,440 分钟(24 小时)之间。",
"console.error.install_not_writable": "服务端对安装目录没有写权限,无法应用更新。",
"console.error.no_maintenance": "当前没有安排维护。",
"console.error.maintenance_closing": "维护已进入排空阶段,不能再取消。",
"console.error.http": "请求失败(%[1]s)",
"console.nav.mail": "邮件发放",
"console.nav.players": "玩家",
"console.nav.config": "服务器配置",
"console.nav.updates": "版本更新",
"console.logout": "退出",
"console.role.owner": "服主",
"console.role.admin": "管理员",
"console.account.as_owner": "%[1]s(服主)",
"console.account.as_admin": "%[1]s(管理员)",
"console.logout.confirm.title": "放弃未保存的配置?",
"console.logout.confirm.body": "退出会丢弃尚未保存的配置改动。",
"console.logout.confirm.ok": "退出",
"console.leave.title": "离开前保存配置?",
"console.leave.body": "有尚未保存的配置改动。离开后改动会保留在本页,直到刷新或退出。",
"console.leave.ok": "仍然离开",
"console.signin.title": "进入管理台",
"console.signin.loading": "正在读取服务器信息……",
"console.signin.local": "这台服务器使用本地认证。请打开服务端启动时在控制台打印的一次性登录链接。",
"console.signin.oauth": "使用你的游戏账号登录。只有服主和服主任命的管理员可以进入。",
"console.signin.provider": "使用 %[1]s 登录",
"console.signin.opening": "正在打开登录页面……",
"console.signin.continue_in_popup": "请在新窗口完成登录,完成后这里会自动进入。",
"console.signin.popup_blocked": "浏览器拦截了新窗口,请点击:%[1]s",
"console.signin.open_page": "打开登录页面",
"console.signin.success": "登录成功。",
"console.signin.no_permissions": "服主还没有给你分配任何权限。",
"console.mail.recipient": "收件人",
"console.mail.copy_uid": "点击复制 UID",
"console.mail.switch_player": "切换玩家",
"console.mail.recipient.none": "还没有可以寄件的玩家。玩家首次登录游戏后会出现在这里。",
"console.mail.catalog": "物品目录",
"console.mail.search.placeholder": "名称、ID、类别或别名,空格分隔多个词",
"console.mail.search.label": "搜索物品",
"console.mail.filter_label": "按类别筛选",
"console.mail.recent": "最近寄出",
"console.mail.items_label": "物品",
"console.mail.catalog_loading": "正在读取物品目录……",
"console.mail.keys.search": "搜索",
"console.mail.keys.pick": "挑选",
"console.mail.keys.add": "放入包裹单",
"console.mail.keys.clear": "清空",
"console.mail.category_all": "全部",
"console.mail.category.currency": "货币(直接入账)",
"console.mail.category.resource": "资源",
"console.mail.category.food": "料理",
"console.mail.category.cooking": "烹饪配方",
"console.mail.category.random_box": "随机箱",
"console.mail.category.quest_item": "任务物品",
"console.mail.category.use_item": "使用物品",
"console.mail.category.collection": "收藏品",
"console.mail.category.my_room": "我的房间物品",
"console.mail.category.instant_use": "即时使用物品",
"console.mail.count.all": "共 %[1]s 项",
"console.mail.count.matched": "匹配 %[1]s / %[2]s 项",
"console.mail.count.showing": "显示前 %[1]s 项",
"console.mail.items.none": "没有匹配的物品",
"console.mail.items.none_in_category": "当前只看「%[1]s」,可以切回「全部」试试",
"console.mail.aliases": "又名 %[1]s",
"console.mail.detail.currency": "邮件领取后直接叠加到账户余额,不生成背包物品。",
"console.mail.detail.direct": "直接发放此物品(无需开箱)",
"console.mail.detail.original_name": "原始资源名:%[1]s",
"console.mail.detail.box_name": "确定性箱名称:%[1]s",
"console.mail.detail.product_name": "商品名:%[1]s",
"console.mail.detail.boxes": "固定箱映射:%[1]s",
"console.mail.detail.boxes_more": "%[1]s 等 %[2]s 个",
"console.mail.slip": "包裹单",
"console.mail.slip.to": "寄往 UID",
"console.mail.parcel.empty": "从目录中挑一件物品放进来",
"console.mail.parcel.search_hint": "或按 %[1]s 直接搜索",
"console.mail.parcel.meta": "类型 %[1]s · ID %[2]s",
"console.mail.parcel.remove": "移出包裹单",
"console.mail.quantity": "数量",
"console.mail.quantity.hint": "支持 5k、2w、3万",
"console.mail.quantity.positive": "请输入正整数",
"console.mail.quantity.too_large": "不能超过 %[1]s",
"console.mail.presets.title": "点击设为该数量,按住 Shift 点击则累加",
"console.mail.presets.thousand": "1k",
"console.mail.presets.ten_thousand": "1w",
"console.mail.letter": "附信",
"console.mail.letter.expand": "展开",
"console.mail.letter.collapse": "收起",
"console.mail.letter.title": "邮件标题",
"console.mail.letter.body": "正文",
"console.mail.letter.default_title": "测试物品",
"console.mail.letter.default_body": "由管理台发放。",
"console.mail.letter.untitled": "(无标题)",
"console.mail.send": "寄出",
"console.mail.send.done": "已寄出",
"console.mail.pick_first": "请先在目录中挑选要寄出的物品。",
"console.mail.sent": "已寄往 UID %[1]s。玩家刷新游戏邮箱即可领取,无需重启服务端。",
"console.mail.lock.loading_player": "正在读取玩家设置……",
"console.mail.lock.no_player": "没有可以寄件的玩家",
"console.inventory.unlimited": "无限背包容量",
"console.mail.inventory.hint": "只影响当前玩家,玩家重新登录游戏后生效,无需重启服务端。关闭后恢复该玩家原有容量。",
"console.mail.inventory.no_permission": "没有调整背包容量的权限",
"console.mail.inventory.items": "道具",
"console.mail.inventory.equipment": "装备",
"console.mail.inventory.normal": "普通容量",
"console.mail.inventory.unlimited": "无限模式",
"console.mail.inventory.saved": "已保存 UID %[1]s 的设置。玩家重新登录游戏后生效。",
"console.mail.log.title": "本次寄件",
"console.mail.log.empty": "寄出的物品会记在这里,点击发放标识可复制。",
"console.mail.log.count": "%[1]s 件",
"console.mail.log.meta": "%[1]s · 寄往 %[2]s",
"console.mail.log.again": "再来一份",
"console.mail.log.again_title": "把这件物品和数量重新放进包裹单",
"console.mail.log.identity": "发放标识",
"console.mail.log.identity_title": "点击复制发放标识",
"console.roster.title": "玩家",
"console.roster.lead": "按游戏账号任命管理员,对方用自己的游戏账号登录管理台。管理员默认可以寄件和查看玩家,其余权限由服主逐项授予。",
"console.roster.search.placeholder": "UID 或名称",
"console.roster.search.label": "筛选玩家",
"console.roster.col.uid": "UID",
"console.roster.col.name": "名称",
"console.roster.col.role": "身份",
"console.roster.col.admin": "管理员",
"console.roster.col.unlimited": "无限背包",
"console.roster.inactive": "已停用",
"console.roster.permissions": "权限…",
"console.roster.mail": "寄件 →",
"console.roster.no_match": "没有匹配的玩家",
"console.roster.empty": "还没有玩家。玩家首次登录游戏后会出现在这里。",
"console.roster.summary.config_read": "配置 %[1]s 组(只读)",
"console.roster.summary.config_write": "配置 %[1]s 组(可改 %[2]s)",
"console.roster.summary.none": "无权限",
"console.roster.revoke.title": "撤销管理员?",
"console.roster.revoke.body": "UID %[1]s 将立即退出管理台,之后需要重新任命。",
"console.roster.revoke.ok": "撤销",
"console.roster.appointed": "已任命 UID %[1]s 为管理员(默认可寄件、查看玩家)",
"console.roster.revoked": "已撤销 UID %[1]s 的管理员身份",
"console.roster.permissions_updated": "已更新 UID %[1]s 的权限,立即生效",
"console.roster.unlimited_on": "UID %[1]s 已开启无限背包,重新登录游戏后生效",
"console.roster.unlimited_off": "UID %[1]s 已关闭无限背包,重新登录游戏后生效",
"console.permission.players.view.label": "查看玩家",
"console.permission.players.view.help": "查看玩家列表、UID 与背包设置。",
"console.permission.players.view.short": "查看玩家",
"console.permission.mail.send.label": "邮件发放",
"console.permission.mail.send.help": "给任意玩家寄送物品和货币。",
"console.permission.mail.send.short": "寄件",
"console.permission.players.inventory.label": "调整背包容量",
"console.permission.players.inventory.help": "开关任意玩家的无限背包容量。",
"console.permission.players.inventory.short": "背包",
"console.permissions.title": "UID %[1]s 的权限",
"console.permissions.save": "保存权限",
"console.permissions.abilities": "基础能力",
"console.permissions.configuration": "服务器配置",
"console.permissions.configuration_help": "按分组授权。修改包含查看;没有查看权限的分组对该管理员不可见。",
"console.permissions.owner_only": "任命和撤销管理员、服务器概览仅服主可用,不能授予。",
"console.permissions.toggle_all": "全部切换",
"console.permissions.read": "查看",
"console.permissions.write": "修改",
"console.permissions.read_aria": "%[1]s %[2]s 查看",
"console.permissions.write_aria": "%[1]s %[2]s 修改",
"console.config.documents": "配置文件",
"console.config.show_diff": "查看改动",
"console.config.discard": "放弃",
"console.config.save": "保存",
"console.config.modified": "修改于 %[1]s",
"console.config.read_only": "只读",
"console.config.advanced": "高级选项",
"console.config.locked": "🔒 已锁定:%[1]s",
"console.config.on": "已开启",
"console.config.off": "已关闭",
"console.config.click_remove": "点击移除",
"console.config.add_other": "其他范围,回车添加",
"console.config.selected": "已选 %[1]s 项",
"console.config.select_all": "全选",
"console.config.remove": "移除",
"console.config.add": "+ 添加",
"console.config.empty": "(空)",
"console.config.example.gold": "充值 %[1]s 付费钻石档位:消耗 %[2]s 金币",
"console.config.example.diamonds": "充值 %[1]s 付费钻石档位:消耗 %[2]s 普通钻石",
"console.config.example.free": "充值 %[1]s 付费钻石档位:%[2]s",
"console.config.example.free_value": "免费",
"console.config.example.ban": "付费钻石充值:%[1]s",
"console.config.example.ban_value": "已禁止",
"console.config.banner.pending.title": "已保存,等待重启生效",
"console.config.banner.pending.body": "%[1]s 的改动已经写入文件,但当前运行的服务端还在使用旧配置。重启服务端进程后生效。",
"console.config.banner.readonly.body": "服务端没有这个文件的写权限(例如部署方以只读方式挂载),这里只能查看。",
"console.config.banner.broken.title": "磁盘上的文件当前无效",
"console.config.banner.broken.body": "文件在管理台之外被改成了服务端无法加载的内容,下次重启会失败。修正下面的问题后保存即可。",
"console.config.banner.unchecked": "无法校验",
"console.config.problem.at": "%[1]s:%[2]s",
"console.config.badge.unsaved": "未保存",
"console.config.badge.pending": "待重启",
"console.config.bar.problems": "%[1]s 处需要修正",
"console.config.bar.changes": "%[1]s 处改动未保存",
"console.config.bar.changes_files": "%[1]s 处改动未保存(%[2]s 个文件)",
"console.config.unset": "(未设置)",
"console.config.diff.title": "尚未保存的改动",
"console.config.diff.body": "保存后需要重启服务端才会生效。",
"console.config.diff.ok": "知道了",
"console.config.discard.title": "放弃全部改动?",
"console.config.discard.body": "未保存的配置改动会被丢弃。",
"console.config.discard.ok": "放弃",
"console.config.save.title": "保存配置?",
"console.config.save.body": "将写入 %[1]s。改动在服务端重启后生效,重启前请确认配置无误。",
"console.config.save.ok": "保存",
"console.config.saved": "%[1]s 已保存,重启服务端后生效",
"console.config.conflict.title": "文件已被修改",
"console.config.conflict.body": "%[1]s 在你编辑期间被其他人或其他程序修改了。载入最新版本会丢弃你在这个文件上的改动。",
"console.config.conflict.ok": "载入最新版本",
"console.config.fix_needed": "有需要修正的地方",
"console.config.save_failed": "%[1]s:%[2]s",
"console.overview.title": "服务器概览",
"console.overview.server_version": "服务端版本",
"console.overview.game_version": "游戏版本",
"console.overview.game_data_version": "GameData",
"console.overview.bundle_version": "资源包",
"console.overview.auth_mode": "认证模式",
"console.overview.auth.oauth": "OAuth 联机",
"console.overview.auth.local": "本地单人",
"console.overview.listen": "监听地址",
"console.overview.started_at": "启动时间",
"console.overview.data_dir": "数据目录",
"console.overview.mail_spool": "邮件队列",
"console.overview.dev_tools": "开发覆盖",
"config.problem.item": "第 %[1]s 项:%[2]s",
"config.problem.enum": "不支持这个值",
"config.problem.enum_options": "只能选择:%[1]s",
"config.problem.enum_key": "不支持这一项",
"config.problem.range": "超出允许范围",
"config.problem.range_between": "需为 %[1]s 到 %[2]s 之间的整数",
"config.problem.required": "必填",
"config.problem.unique": "有重复项",
"config.problem.format": "取值无效:%[1]s",
"config.problem.conflict": "与其他设置冲突",
"config.problem.locked": "已锁定",
"config.problem.locked_reason": "已锁定:%[1]s",
"config.problem.decode": "格式错误:%[1]s",
"config.problem.custom": "无效:%[1]s",
"config.problem.forbidden": "你没有修改这个分组的权限",
"config.problem.environment": "当前服务端进程没有设置环境变量 %[1]s。保存后重启前,请先在服务端环境中设置它。",
"config.problem.environment_key": "当前服务端进程中环境变量 %[1]s 不是有效的 32 字节 base64 密钥,重启后服务端会拒绝启动。",
"config.problem.missing_file": "服务端当前读不到这个文件:%[1]s",
"config.problem.message.bare_host": "只填主机名,不带协议、路径或端口",
"config.problem.message.host_port": "格式应为 主机:端口,例如 0.0.0.0:8444",
"config.problem.message.plaintext_listen_loopback": "明文模式只能监听回环地址",
"config.problem.message.plaintext_host_loopback": "明文模式的公开地址必须是回环 IP",
"config.problem.message.tls_required": "未启用本机明文模式时必填",
"config.problem.message.nonempty_path": "路径不能为空",
"config.problem.message.required_by_provider": "启用第三方审核时必填",
"config.problem.message.required_by_azure": "Azure 需要填写这一项",
"config.problem.message.lowercase_identifier": "只能使用小写字母、数字和下划线,并以字母开头",
"config.problem.message.local_no_oauth": "本地模式下不能配置这一项",
"config.problem.message.required_oauth": "OAuth 模式下必填",
"config.problem.message.oauth_provider": "至少启用一个登录提供方",
"config.problem.message.absolute_origin": "应为不带路径的根地址,例如 https://game.example.com",
"config.problem.message.https_origin": "除 localhost 外必须使用 HTTPS",
"config.problem.message.positive_duration": "应为正的时长,例如 15m、720h",
"config.problem.message.official_origin": "官方模式只能使用官方地址",
"config.problem.message.required_server_mode": "自建资源源模式下必填",
"config.problem.message.absolute_url": "应为完整的 HTTP(S) 地址,不带账号、查询参数或锚点",
"config.problem.message.no_trailing_slash": "末尾不能带斜杠",
"config.problem.message.https_url": "除回环地址外必须使用 HTTPS",
"config.problem.message.list": "必须是列表",
"config.problem.message.object": "必须是对象",
"config.problem.message.present": "文件中必须写明这一项",
"config.problem.message.hidden_section": "你无权查看的分组中存在问题,请联系服主处理",
"config.game.title": "游戏规则",
"config.game.summary": "服务端统一的玩法规则。修改后重启服务端生效。",
"config.game.section.story.title": "开局章节",
"config.game.section.story.help": "首次成功初始化后永久保存在服务器状态中,之后不能更改;不能通过删除数据库切换开局。",
"config.game.field.story.start_pack_id.label": "起始章节",
"config.game.field.story.start_pack_id.option.21.label": "店长篇",
"config.game.field.story.start_pack_id.option.21.help": "当前客户端默认的开局,使用该篇的任务和教学流程。",
"config.game.field.story.start_pack_id.option.1.label": "旧主线第一章",
"config.game.field.story.start_pack_id.option.1.help": "使用当前 GameData 中该章的开场剧情、初始任务及购卡奖励。",
"config.game.lock.story.start_pack_id": "首次初始化后已永久保存于服务器状态,不能再更改",
"config.game.section.gacha.title": "抽卡",
"config.game.field.gacha.include_collaboration_ur_weapons.label": "UR 必得装备券加入联动专武",
"config.game.field.gacha.include_collaboration_ur_weapons.help": "在原池中加入 14 种联动角色 UR 专武(装备 943200–943213),沿用同星级单件权重;只改变券池候选,不直接发放装备。",
"config.game.section.purchases.title": "付费钻石充值",
"config.game.section.purchases.help": "普通现金商品固定消耗付费钻石,价格由 GameData 换算;这里只设置付费钻石充值本身的兑换方式。",
"config.game.field.purchases.diamond_recharge.currency.label": "充值方式",
"config.game.field.purchases.diamond_recharge.currency.option.free.label": "免费",
"config.game.field.purchases.diamond_recharge.currency.option.free.help": "不扣货币,直接发放所选充值商品的原始奖励。",
"config.game.field.purchases.diamond_recharge.currency.option.gold.label": "金币兑换",
"config.game.field.purchases.diamond_recharge.currency.option.gold.help": "每单位常规付费钻石消耗设定数量的金币。",
"config.game.field.purchases.diamond_recharge.currency.option.diamonds.label": "普通钻石兑换",
"config.game.field.purchases.diamond_recharge.currency.option.diamonds.help": "每单位常规付费钻石消耗设定数量的普通钻石。",
"config.game.field.purchases.diamond_recharge.currency.option.ban.label": "禁止充值",
"config.game.field.purchases.diamond_recharge.currency.option.ban.help": "禁止购买付费钻石充值商品,不影响玩家已有付费钻石。",
"config.game.field.purchases.diamond_recharge.currency.option..label": "禁止充值(空字符串)",
"config.game.field.purchases.diamond_recharge.currency.option..help": "与 ban 相同的旧写法。",
"config.game.field.purchases.diamond_recharge.gold_per_paid_diamond.label": "金币 / 付费钻石",
"config.game.field.purchases.diamond_recharge.gold_per_paid_diamond.help": "金币兑换时每单位常规付费钻石的费用。即使未选用也必须合法。",
"config.game.field.purchases.diamond_recharge.diamonds_per_paid_diamond.label": "普通钻石 / 付费钻石",
"config.game.field.purchases.diamond_recharge.diamonds_per_paid_diamond.help": "普通钻石兑换时每单位常规付费钻石的费用。即使未选用也必须合法。",
"config.game.section.realtime.title": "实时联机",
"config.game.section.realtime.help": "动作小游戏、联机钓鱼与随机防御使用的原生 TCP/UDP 连接。关闭时不监听实时端口,会影响玩家体验。",
"config.game.field.realtime.enabled.label": "启用实时联机",
"config.game.field.realtime.public_host.label": "公开主机名",
"config.game.field.realtime.public_host.help": "玩家能够访问的主机名,不带协议、路径或端口。",
"config.game.field.realtime.tcp_port.label": "公开 TCP 端口",
"config.game.field.realtime.udp_port.label": "公开 UDP 端口",
"config.game.field.realtime.tcp_listen.label": "TCP 监听地址",
"config.game.field.realtime.tcp_listen.help": "公开端口可以与监听端口不同,适用于端口映射。",
"config.game.field.realtime.udp_listen.label": "UDP 监听地址",
"config.game.field.realtime.tls_cert_file.label": "TLS 证书",
"config.game.field.realtime.tls_cert_file.help": "与公开主机名匹配且受客户端信任的证书。相对路径以 game.json 所在目录为基准;更新后新握手自动载入。",
"config.game.field.realtime.tls_key_file.label": "TLS 私钥",
"config.game.field.realtime.tls_key_file.help": "私钥只留在服务端,须允许服务进程读取。",
"config.game.field.realtime.development_plain_loopback.label": "本机开发明文模式",
"config.game.field.realtime.development_plain_loopback.help": "仅限本机开发:监听地址和公开地址都必须是回环 IP,此时不需要证书。",
"config.game.section.text_moderation.title": "文本审核",
"config.game.section.text_moderation.help": "本地规则先执行,通过后才调用第三方。已有昵称和简介不会在登录时重新审核。",
"config.game.field.text_moderation.rule_files.label": "本地词库文件",
"config.game.field.text_moderation.rule_files.help": "UTF-8 的 .txt(每行一个词,子串匹配)或 .json(逐条指定匹配方式与范围),单文件最多 4 MiB。相对路径以 game.json 所在目录为基准。",
"config.game.field.text_moderation.provider.type.label": "第三方审核",
"config.game.field.text_moderation.provider.type.option.off.label": "关闭",
"config.game.field.text_moderation.provider.type.option.http_json.label": "通用 HTTP JSON",
"config.game.field.text_moderation.provider.type.option.http_json.help": "接入自建审核服务或第三方适配网关。",
"config.game.field.text_moderation.provider.type.option.azure_content_safety.label": "Azure AI Content Safety",
"config.game.field.text_moderation.provider.endpoint.label": "审核地址",
"config.game.field.text_moderation.provider.endpoint.help": "使用 HTTPS,只有回环地址允许 HTTP,不跟随重定向。Azure 填资源根地址。",
"config.game.field.text_moderation.provider.api_key_env.label": "密钥环境变量",
"config.game.field.text_moderation.provider.api_key_env.help": "服务端从这个环境变量读取密钥,配置文件里不保存密钥本身。",
"config.game.field.text_moderation.provider.api_key_header.label": "密钥请求头",
"config.game.field.text_moderation.provider.api_key_header.help": "Authorization 头会发送 Bearer <密钥>,其他头名原样传递密钥。",
"config.game.field.text_moderation.provider.scopes.label": "审核范围",
"config.game.field.text_moderation.provider.scopes.help": "第三方只审核明确列出的输入入口。",
"config.game.field.text_moderation.provider.scopes.option.nickname.label": "玩家昵称",
"config.game.field.text_moderation.provider.scopes.option.greeting.label": "个人简介",
"config.game.field.text_moderation.provider.scopes.option.master_title.label": "主角称呼",
"config.game.field.text_moderation.provider.scopes.option.preset_name.label": "配队预设名",
"config.game.field.text_moderation.provider.scopes.option.equipment_preset_name.label": "装备预设名",
"config.game.field.text_moderation.provider.scopes.option.equipment_mark.label": "装备标记",
"config.game.field.text_moderation.provider.scopes.option.monster_hunt_preset_name.label": "魔兽追踪者预设名",
"config.game.field.text_moderation.provider.scopes.option.guild_raid_preset_name.label": "公会战预设名",
"config.game.field.text_moderation.provider.scopes.option.colosseum_preset_name.label": "斗兽场预设名",
"config.game.field.text_moderation.provider.scopes.option.guild_name.label": "公会名称",
"config.game.field.text_moderation.provider.scopes.option.guild_message.label": "公会介绍",
"config.game.field.text_moderation.provider.scopes.option.guild_notice.label": "公会公告",
"config.game.field.text_moderation.provider.scopes.option.room_name.label": "房间名称",
"config.game.field.text_moderation.provider.scopes.option.chat.label": "联机聊天",
"config.game.field.text_moderation.provider.timeout_ms.label": "超时(毫秒)",
"config.game.field.text_moderation.provider.failure_policy.label": "接口故障时",
"config.game.field.text_moderation.provider.failure_policy.option.deny.label": "暂不接受修改",
"config.game.field.text_moderation.provider.failure_policy.option.deny.help": "客户端提示审核暂时不可用。",
"config.game.field.text_moderation.provider.failure_policy.option.allow.label": "放行",
"config.game.field.text_moderation.provider.failure_policy.option.allow.help": "放行已通过本地规则的文本;明确拒绝的结果不会被放行。",
"config.game.field.text_moderation.provider.severity_threshold.label": "Azure 拒绝阈值",
"config.game.field.text_moderation.provider.severity_threshold.help": "任一类别达到该严重程度即拒绝;0 表示连严重程度 0 的结果也拒绝。",
"config.game.section.format.title": "格式",
"config.game.field.schema_version.label": "格式版本",
"config.authentication.title": "登录与认证",
"config.authentication.summary": "玩家登录方式。修改后重启服务端生效;密钥只从环境变量读取,不写入此文件。",
"config.authentication.section.mode.title": "认证模式",
"config.authentication.field.mode.label": "模式",
"config.authentication.field.mode.option.local.label": "本地单人",
"config.authentication.field.mode.option.local.help": "无需登录,只有一个本地玩家。",
"config.authentication.field.mode.option.oauth.label": "OAuth 联机",
"config.authentication.field.mode.option.oauth.help": "玩家通过 Discord 或 Google 登录,服务器可供多人使用。",
"config.authentication.field.public_url.label": "公开地址",
"config.authentication.field.public_url.help": "玩家和 OAuth 回调访问的根地址,不带路径;除 localhost 外必须使用 HTTPS。",
"config.authentication.field.master_key_env.label": "主密钥环境变量",
"config.authentication.field.master_key_env.help": "该环境变量须为 base64 编码的 32 字节密钥,用于加密登录数据。",
"config.authentication.section.providers.title": "登录提供方",
"config.authentication.section.providers.help": "回调地址为 公开地址/auth/<提供方>/callback。",
"config.authentication.field.providers.label": "启用的提供方",
"config.authentication.field.providers.*.client_id.label": "Client ID",
"config.authentication.field.providers.*.client_secret_env.label": "Client secret 环境变量",
"config.authentication.section.session.title": "会话时长",
"config.authentication.section.session.help": "使用 Go 时长格式,例如 15m、720h。留空使用默认值。",
"config.authentication.field.session.access_ttl.label": "访问令牌有效期",
"config.authentication.field.session.refresh_ttl.label": "刷新令牌有效期",
"config.authentication.field.session.device_transaction_ttl.label": "登录事务有效期",
"config.resources.title": "客户端资源",
"config.resources.summary": "客户端下载 ServerData 与 GameData 的来源。修改后重启服务端生效;版本号来自 versions.json,不在此配置。",
"config.resources.section.source.title": "资源来源",
"config.resources.field.mode.label": "模式",
"config.resources.field.mode.option.official.label": "官方 CDN",
"config.resources.field.mode.option.official.help": "使用当前版本的官方资源地址。",
"config.resources.field.mode.option.server.label": "自建资源源",
"config.resources.field.mode.option.server.help": "从服主提供的静态 CDN 或缓存反代下载。",
"config.resources.field.server_data_url.label": "ServerData 地址",
"config.resources.field.server_data_url.help": "绝对 HTTP(S) 地址,末尾不带斜杠;除回环地址外必须使用 HTTPS。",
"config.resources.field.game_data_url.label": "GameData 地址",
"config.resources.field.game_data_url.help": "绝对 HTTP(S) 地址,末尾不带斜杠;除回环地址外必须使用 HTTPS。",
"config.updates.title": "版本更新",
"config.updates.summary": "检查新版、预下载与维护更新方式。检查与下载不影响游戏;更新需要在管理台或命令行确认。修改后重启服务端生效。",
"config.updates.section.check.title": "检查与下载",
"config.updates.field.check.label": "自动检查新版",
"config.updates.field.check.help": "启动后及运行期间按间隔检查发布清单,并加随机偏移。",
"config.updates.field.check_interval.label": "检查间隔",
"config.updates.field.download.label": "提前下载",
"config.updates.field.download.help": "发现新版后在后台下载并校验,应用更新时不必再等待。",
"config.updates.field.manifest_url.label": "发布清单地址",
"config.updates.field.manifest_url.help": "留空使用内置地址;清单的签名必须能用内置公钥验证。",
"config.updates.field.changelog_urls.label": "更新日志地址",
"config.updates.field.changelog_urls.help": "按顺序尝试;留空使用内置的 GitHub 与 Gitea 地址。",
"config.updates.field.changelog.notices.label": "更新日志作为游戏公告",
"config.updates.section.install.title": "安装方式",
"config.updates.field.method.label": "部署方式",
"config.updates.field.method.option.native.label": "原生(systemd)",
"config.updates.field.method.option.native.help": "替换程序文件后退出,由 systemd 以新版重启;失败时自动换回上一版程序。",
"config.updates.field.method.option.docker.label": "Docker",
"config.updates.field.method.option.docker.help": "排空并保存后退出,由宿主机脚本切换到清单指定的镜像。",
"config.updates.field.method.option.none.label": "仅通知",
"config.updates.field.method.option.none.help": "只检查和展示,不提供应用更新。",
"config.updates.field.countdown_minutes.label": "默认倒计时(分钟)",
"config.updates.field.maintenance_minutes.label": "预计维护时长(分钟)",
"config.updates.field.webhook_url_env.label": "Webhook 环境变量",
"config.updates.field.webhook_url_env.help": "发现新版时向该环境变量中的地址 POST 一次 JSON;留空不发送。",
"console.updates.title": "版本更新",
"console.updates.lead": "服务端按间隔检查签名的发布清单,可提前下载并校验。应用更新会先通知在线玩家、关闭新登录、排空请求并保存,再切换到新版。",
"console.updates.check": "立即检查",
"console.updates.fact.current_version": "当前版本",
"console.updates.fact.method": "部署方式",
"console.updates.fact.auto_check": "自动检查",
"console.updates.fact.last_check": "上次检查",
"console.updates.fact.check_error": "检查失败",
"console.updates.fact.last_switch": "上次切换",
"console.updates.enabled": "开启",
"console.updates.disabled": "关闭",
"console.updates.never_checked": "尚未检查",
"console.updates.method.native": "原生(systemd)",
"console.updates.method.docker": "Docker",
"console.updates.method.none": "仅通知",
"console.updates.phase.preparing": "准备中(下载、校验与预检)",
"console.updates.phase.countdown": "倒计时",
"console.updates.phase.closing": "正在排空并切换",
"console.updates.outcome.succeeded": "成功",
"console.updates.outcome.rolled_back": "已换回旧程序",
"console.updates.outcome.needs_operator": "需要人工处理",
"console.updates.outcome.awaiting_host": "等待宿主机",
"console.updates.outcome.host_timed_out": "宿主机未切换",
"console.updates.outcome.switch_failed": "切换失败",
"console.updates.outcome.cancelled": "已取消",
"console.updates.migration.none": "无存档迁移",
"console.updates.migration.reversible": "存档迁移(可回滚)",
"console.updates.migration.irreversible": "存档迁移(不可回滚)",
"console.updates.last_switch_value": "%[1]s → %[2]s:%[3]s",
"console.updates.last_switch_message": "%[1]s → %[2]s:%[3]s,%[4]s",
"console.updates.up_to_date": "已是最新版本。",
"console.updates.available": "可用版本 %[1]s",
"console.updates.published": "发布于 %[1]s",
"console.updates.downloaded": "已下载并校验",
"console.updates.download_failed": "下载失败:%[1]s",
"console.updates.not_downloaded": "尚未下载",
"console.updates.maintenance": "维护:%[1]s → %[2]s(%[3]s)",
"console.updates.maintenance_at": "维护:%[1]s → %[2]s,%[3]s 开始(%[4]s)",
"console.updates.cancel": "取消维护",
"console.updates.delay": "倒计时(分钟)",
"console.updates.confirm_irreversible": "我已阅读迁移说明,确认不可回滚",
"console.updates.apply": "应用更新",
"console.updates.apply.title": "应用服务端更新?",
"console.updates.apply.body_countdown": "准备完成后倒计时 %[1]s 分钟:在线玩家会看到维护提示,最后 1 分钟关闭新登录,随后排空、保存并切换到 %[2]s。",
"console.updates.apply.body_now": "准备完成后立即关闭新登录、排空、保存并切换到 %[1]s。",
"console.updates.scheduled": "已安排维护。",
"console.updates.cancelled": "已取消维护。",
"console.updates.checking": "正在检查……"
}
@@ -0,0 +1,490 @@
{
"console.title": "BD2 管理台",
"console.brand": "管理台",
"console.language": "語言",
"console.loading": "正在讀取……",
"console.list.separator": "、",
"console.sentence.separator": ";",
"console.copy.done": "%[1]s已複製",
"console.copy.failed": "無法複製,請手動選取文字。",
"console.dialog.ok": "確定",
"console.dialog.cancel": "取消",
"console.error.unauthorized": "登入已過期,請重新登入。",
"console.error.forbidden": "沒有權限執行這個操作。",
"console.error.csrf": "頁面已過期,請重新整理後重試。",
"console.error.rate_limited": "嘗試太頻繁,請稍後再試。",
"console.error.expired": "登入已過期,請重新開始。",
"console.error.rejected": "登入被拒絕或已取消。",
"console.error.not_granted": "這個遊戲帳號不是管理員,不能進入管理台。如需權限請聯絡伺服器擁有者。",
"console.error.not_found": "玩家不存在或已停用。",
"console.error.invalid_permission": "包含無效的權限。",
"console.error.invalid_item": "這件物品不在可寄送目錄中。",
"console.error.invalid_count": "數量需在 1 到 2,147,483,647 之間。",
"console.error.invalid_text": "郵件標題和內文都不能為空。",
"console.error.read_only": "伺服器只能讀取這個檔案,無法寫入。",
"console.error.unavailable": "服務暫不可用,請稍後再試。",
"console.error.invalid": "請求無效。",
"console.error.unsupported": "這台伺服器使用本機驗證。請使用伺服器啟動時顯示的一次性連結登入。",
"console.error.notify_only": "安裝方式為「僅通知」,無法在這裡套用更新。",
"console.error.no_update": "沒有可用的新版本。",
"console.error.already_scheduled": "已經安排了一次維護。",
"console.error.irreversible_unconfirmed": "該版本包含不可還原的存檔遷移,請先閱讀遷移說明並勾選確認。",
"console.error.invalid_delay": "倒數計時需在 0 到 1,440 分鐘(24 小時)之間。",
"console.error.install_not_writable": "伺服器沒有安裝目錄的寫入權限,無法套用更新。",
"console.error.no_maintenance": "目前沒有安排維護。",
"console.error.maintenance_closing": "維護已開始等待進行中的請求完成,無法再取消。",
"console.error.http": "請求失敗(%[1]s)",
"console.nav.mail": "郵件發放",
"console.nav.players": "玩家",
"console.nav.config": "伺服器設定",
"console.nav.updates": "版本更新",
"console.logout": "登出",
"console.role.owner": "伺服器擁有者",
"console.role.admin": "管理員",
"console.account.as_owner": "%[1]s(伺服器擁有者)",
"console.account.as_admin": "%[1]s(管理員)",
"console.logout.confirm.title": "放棄未儲存的設定?",
"console.logout.confirm.body": "登出後會捨棄尚未儲存的設定變更。",
"console.logout.confirm.ok": "登出",
"console.leave.title": "離開前儲存設定?",
"console.leave.body": "有尚未儲存的設定變更。離開後仍會保留在本頁,直到重新整理或登出。",
"console.leave.ok": "仍然離開",
"console.signin.title": "進入管理台",
"console.signin.loading": "正在讀取伺服器資訊……",
"console.signin.local": "這台伺服器使用本機驗證。請開啟伺服器啟動時在主控台顯示的一次性登入連結。",
"console.signin.oauth": "使用你的遊戲帳號登入。只有伺服器擁有者與其任命的管理員可以進入。",
"console.signin.provider": "使用 %[1]s 登入",
"console.signin.opening": "正在開啟登入頁面……",
"console.signin.continue_in_popup": "請在新視窗完成登入,完成後這裡會自動進入。",
"console.signin.popup_blocked": "瀏覽器攔截了新視窗,請點選:%[1]s",
"console.signin.open_page": "開啟登入頁面",
"console.signin.success": "登入成功。",
"console.signin.no_permissions": "伺服器擁有者還沒有給你分配任何權限。",
"console.mail.recipient": "收件人",
"console.mail.copy_uid": "點選複製 UID",
"console.mail.switch_player": "切換玩家",
"console.mail.recipient.none": "還沒有可以收件的玩家。玩家首次登入遊戲後會出現在這裡。",
"console.mail.catalog": "物品目錄",
"console.mail.search.placeholder": "名稱、ID、類別或別名,空格分隔多個詞",
"console.mail.search.label": "搜尋物品",
"console.mail.filter_label": "按類別篩選",
"console.mail.recent": "最近寄出",
"console.mail.items_label": "物品",
"console.mail.catalog_loading": "正在讀取物品目錄……",
"console.mail.keys.search": "搜尋",
"console.mail.keys.pick": "挑選",
"console.mail.keys.add": "放入包裹單",
"console.mail.keys.clear": "清空",
"console.mail.category_all": "全部",
"console.mail.category.currency": "貨幣(直接入帳)",
"console.mail.category.resource": "資源",
"console.mail.category.food": "料理",
"console.mail.category.cooking": "烹飪配方",
"console.mail.category.random_box": "隨機箱",
"console.mail.category.quest_item": "任務物品",
"console.mail.category.use_item": "使用物品",
"console.mail.category.collection": "收藏品",
"console.mail.category.my_room": "我的房間物品",
"console.mail.category.instant_use": "即時使用物品",
"console.mail.count.all": "共 %[1]s 項",
"console.mail.count.matched": "符合 %[1]s / %[2]s 項",
"console.mail.count.showing": "顯示前 %[1]s 項",
"console.mail.items.none": "沒有符合的物品",
"console.mail.items.none_in_category": "目前只看「%[1]s」,可以切回「全部」試試",
"console.mail.aliases": "又名 %[1]s",
"console.mail.detail.currency": "領取郵件後會直接加到帳戶餘額,不會新增背包物品。",
"console.mail.detail.direct": "直接發放此物品(無需開箱)",
"console.mail.detail.original_name": "原始資源名:%[1]s",
"console.mail.detail.box_name": "固定獎勵箱名稱:%[1]s",
"console.mail.detail.product_name": "商品名:%[1]s",
"console.mail.detail.boxes": "固定獎勵箱對應:%[1]s",
"console.mail.detail.boxes_more": "%[1]s 等 %[2]s 個",
"console.mail.slip": "包裹單",
"console.mail.slip.to": "寄往 UID",
"console.mail.parcel.empty": "從目錄中挑一件物品放進來",
"console.mail.parcel.search_hint": "或按 %[1]s 直接搜尋",
"console.mail.parcel.meta": "類型 %[1]s · ID %[2]s",
"console.mail.parcel.remove": "移出包裹單",
"console.mail.quantity": "數量",
"console.mail.quantity.hint": "支援 5k、2m",
"console.mail.quantity.positive": "請輸入正整數",
"console.mail.quantity.too_large": "不能超過 %[1]s",
"console.mail.presets.title": "點選設為該數量,按住 Shift 點選則累加",
"console.mail.presets.thousand": "1k",
"console.mail.presets.ten_thousand": "10k",
"console.mail.letter": "附信",
"console.mail.letter.expand": "展開",
"console.mail.letter.collapse": "收合",
"console.mail.letter.title": "郵件標題",
"console.mail.letter.body": "內文",
"console.mail.letter.default_title": "測試物品",
"console.mail.letter.default_body": "由管理台發放。",
"console.mail.letter.untitled": "(無標題)",
"console.mail.send": "寄出",
"console.mail.send.done": "已寄出",
"console.mail.pick_first": "請先在目錄中挑選要寄出的物品。",
"console.mail.sent": "已寄往 UID %[1]s。玩家重新整理遊戲郵箱即可領取,無需重新啟動伺服器。",
"console.mail.lock.loading_player": "正在讀取玩家設定……",
"console.mail.lock.no_player": "沒有可以收件的玩家",
"console.inventory.unlimited": "無限背包容量",
"console.mail.inventory.hint": "只影響目前玩家,玩家重新登入遊戲後生效,無需重新啟動伺服器。關閉後恢復該玩家原有容量。",
"console.mail.inventory.no_permission": "沒有調整背包容量的權限",
"console.mail.inventory.items": "道具",
"console.mail.inventory.equipment": "裝備",
"console.mail.inventory.normal": "普通容量",
"console.mail.inventory.unlimited": "無限模式",
"console.mail.inventory.saved": "已儲存 UID %[1]s 的設定。玩家重新登入遊戲後生效。",
"console.mail.log.title": "本次寄件",
"console.mail.log.empty": "寄出的物品會記在這裡,點選發放 ID可複製。",
"console.mail.log.count": "%[1]s 件",
"console.mail.log.meta": "%[1]s · 寄往 %[2]s",
"console.mail.log.again": "再來一份",
"console.mail.log.again_title": "把這件物品和數量重新放進包裹單",
"console.mail.log.identity": "發放 ID",
"console.mail.log.identity_title": "點選複製發放 ID",
"console.roster.title": "玩家",
"console.roster.lead": "按遊戲帳號任命管理員,對方用自己的遊戲帳號登入管理台。管理員預設可以寄件和檢視玩家,其餘權限由伺服器擁有者逐項授予。",
"console.roster.search.placeholder": "UID 或名稱",
"console.roster.search.label": "篩選玩家",
"console.roster.col.uid": "UID",
"console.roster.col.name": "名稱",
"console.roster.col.role": "身份",
"console.roster.col.admin": "管理員",
"console.roster.col.unlimited": "無限背包",
"console.roster.inactive": "已停用",
"console.roster.permissions": "權限…",
"console.roster.mail": "寄件 →",
"console.roster.no_match": "沒有符合的玩家",
"console.roster.empty": "還沒有玩家。玩家首次登入遊戲後會出現在這裡。",
"console.roster.summary.config_read": "設定 %[1]s 組(唯讀)",
"console.roster.summary.config_write": "設定 %[1]s 組(可改 %[2]s)",
"console.roster.summary.none": "無權限",
"console.roster.revoke.title": "撤銷管理員?",
"console.roster.revoke.body": "UID %[1]s 將立即退出管理台,之後需要重新任命。",
"console.roster.revoke.ok": "撤銷",
"console.roster.appointed": "已任命 UID %[1]s 為管理員(預設可寄件、檢視玩家)",
"console.roster.revoked": "已撤銷 UID %[1]s 的管理員身份",
"console.roster.permissions_updated": "已更新 UID %[1]s 的權限,立即生效",
"console.roster.unlimited_on": "UID %[1]s 已開啟無限背包,重新登入遊戲後生效",
"console.roster.unlimited_off": "UID %[1]s 已關閉無限背包,重新登入遊戲後生效",
"console.permission.players.view.label": "檢視玩家",
"console.permission.players.view.help": "檢視玩家列表、UID 與背包設定。",
"console.permission.players.view.short": "檢視玩家",
"console.permission.mail.send.label": "郵件發放",
"console.permission.mail.send.help": "給任意玩家寄送物品和貨幣。",
"console.permission.mail.send.short": "寄件",
"console.permission.players.inventory.label": "調整背包容量",
"console.permission.players.inventory.help": "開關任意玩家的無限背包容量。",
"console.permission.players.inventory.short": "背包",
"console.permissions.title": "UID %[1]s 的權限",
"console.permissions.save": "儲存權限",
"console.permissions.abilities": "基礎能力",
"console.permissions.configuration": "伺服器設定",
"console.permissions.configuration_help": "按分組授權。修改包含檢視;沒有檢視權限的分組對該管理員不可見。",
"console.permissions.owner_only": "任命和撤銷管理員、伺服器概覽僅伺服器擁有者可用,不能授予。",
"console.permissions.toggle_all": "全部切換",
"console.permissions.read": "檢視",
"console.permissions.write": "修改",
"console.permissions.read_aria": "%[1]s %[2]s 檢視",
"console.permissions.write_aria": "%[1]s %[2]s 修改",
"console.config.documents": "設定檔案",
"console.config.show_diff": "檢視改動",
"console.config.discard": "放棄",
"console.config.save": "儲存",
"console.config.modified": "修改於 %[1]s",
"console.config.read_only": "唯讀",
"console.config.advanced": "高階選項",
"console.config.locked": "🔒 已鎖定:%[1]s",
"console.config.on": "已開啟",
"console.config.off": "已關閉",
"console.config.click_remove": "點選移除",
"console.config.add_other": "輸入其他範圍,按 Enter 新增",
"console.config.selected": "已選 %[1]s 項",
"console.config.select_all": "全選",
"console.config.remove": "移除",
"console.config.add": "+ 新增",
"console.config.empty": "(空)",
"console.config.example.gold": "儲值 %[1]s 付費鑽石檔位:消耗 %[2]s 金幣",
"console.config.example.diamonds": "儲值 %[1]s 付費鑽石檔位:消耗 %[2]s 普通鑽石",
"console.config.example.free": "儲值 %[1]s 付費鑽石檔位:%[2]s",
"console.config.example.free_value": "免費",
"console.config.example.ban": "付費鑽石儲值:%[1]s",
"console.config.example.ban_value": "已禁止",
"console.config.banner.pending.title": "已儲存,等待重新啟動生效",
"console.config.banner.pending.body": "%[1]s 的改動已經寫入檔案,但目前執行的伺服器還在使用舊設定。重新啟動伺服器程序後生效。",
"console.config.banner.readonly.body": "伺服器沒有這個檔案的寫權限(例如部署方以唯讀方式掛載),這裡只能檢視。",
"console.config.banner.broken.title": "磁碟上的檔案目前無效",
"console.config.banner.broken.body": "檔案在管理台之外被改成了伺服器無法載入的內容,下次重新啟動會失敗。修正下面的問題後儲存即可。",
"console.config.banner.unchecked": "無法驗證",
"console.config.problem.at": "%[1]s:%[2]s",
"console.config.badge.unsaved": "未儲存",
"console.config.badge.pending": "待重新啟動",
"console.config.bar.problems": "%[1]s 處需要修正",
"console.config.bar.changes": "%[1]s 處改動未儲存",
"console.config.bar.changes_files": "%[1]s 處改動未儲存(%[2]s 個檔案)",
"console.config.unset": "(未設定)",
"console.config.diff.title": "尚未儲存的改動",
"console.config.diff.body": "儲存後需要重新啟動伺服器才會生效。",
"console.config.diff.ok": "知道了",
"console.config.discard.title": "放棄全部改動?",
"console.config.discard.body": "未儲存的設定改動會被丟棄。",
"console.config.discard.ok": "放棄",
"console.config.save.title": "儲存設定?",
"console.config.save.body": "將寫入 %[1]s。改動在伺服器重新啟動後生效,重新啟動前請確認設定無誤。",
"console.config.save.ok": "儲存",
"console.config.saved": "%[1]s 已儲存,重新啟動伺服器後生效",
"console.config.conflict.title": "檔案已被修改",
"console.config.conflict.body": "%[1]s 在你編輯期間被其他人或其他程式修改了。載入最新版本會丟棄你在這個檔案上的改動。",
"console.config.conflict.ok": "載入最新版本",
"console.config.fix_needed": "有需要修正的地方",
"console.config.save_failed": "%[1]s:%[2]s",
"console.overview.title": "伺服器概覽",
"console.overview.server_version": "伺服器版本",
"console.overview.game_version": "遊戲版本",
"console.overview.game_data_version": "GameData",
"console.overview.bundle_version": "資源包",
"console.overview.auth_mode": "認證模式",
"console.overview.auth.oauth": "OAuth(線上)",
"console.overview.auth.local": "本機單人",
"console.overview.listen": "監聽位址",
"console.overview.started_at": "啟動時間",
"console.overview.data_dir": "資料目錄",
"console.overview.mail_spool": "郵件佇列",
"console.overview.dev_tools": "開發用覆寫設定",
"config.problem.item": "第 %[1]s 項:%[2]s",
"config.problem.enum": "不支援這個值",
"config.problem.enum_options": "只能選擇:%[1]s",
"config.problem.enum_key": "不支援這一項",
"config.problem.range": "超出允許範圍",
"config.problem.range_between": "需為 %[1]s 到 %[2]s 之間的整數",
"config.problem.required": "必填",
"config.problem.unique": "有重複項",
"config.problem.format": "取值無效:%[1]s",
"config.problem.conflict": "與其他設定衝突",
"config.problem.locked": "已鎖定",
"config.problem.locked_reason": "已鎖定:%[1]s",
"config.problem.decode": "格式錯誤:%[1]s",
"config.problem.custom": "無效:%[1]s",
"config.problem.forbidden": "你沒有修改這個分組的權限",
"config.problem.environment": "目前伺服器程序沒有設定環境變數 %[1]s。儲存後重新啟動前,請先在伺服器環境中設定它。",
"config.problem.environment_key": "目前伺服器程序中環境變數 %[1]s 不是有效的 32 位元組 base64 金鑰,重新啟動後伺服器會拒絕啟動。",
"config.problem.missing_file": "伺服器目前讀不到這個檔案:%[1]s",
"config.problem.message.bare_host": "只填主機名稱,不含通訊協定、路徑或連接埠",
"config.problem.message.host_port": "請使用 host:port 格式,例如 0.0.0.0:8444",
"config.problem.message.plaintext_listen_loopback": "明文模式只能監聽loopback位址",
"config.problem.message.plaintext_host_loopback": "明文模式的公開位址必須是loopback IP",
"config.problem.message.tls_required": "未啟用本機明文模式時必填",
"config.problem.message.nonempty_path": "路徑不能為空",
"config.problem.message.required_by_provider": "啟用第三方審查時必填",
"config.problem.message.required_by_azure": "Azure 需要填寫這一項",
"config.problem.message.lowercase_identifier": "只能使用小寫字母、數字和底線,並以字母開頭",
"config.problem.message.local_no_oauth": "本機模式下不能設定這一項",
"config.problem.message.required_oauth": "OAuth 模式下必填",
"config.problem.message.oauth_provider": "至少啟用一個登入提供方",
"config.problem.message.absolute_origin": "應為不帶路徑的根位址,例如 https://game.example.com",
"config.problem.message.https_origin": "除 localhost 外必須使用 HTTPS",
"config.problem.message.positive_duration": "應為正的時長,例如 15m、720h",
"config.problem.message.official_origin": "官方模式只能使用官方位址",
"config.problem.message.required_server_mode": "自建資源源模式下必填",
"config.problem.message.absolute_url": "應為完整的 HTTP(S) 位址,不帶帳號、查詢引數或錨點",
"config.problem.message.no_trailing_slash": "末尾不能帶斜線",
"config.problem.message.https_url": "除loopback位址外必須使用 HTTPS",
"config.problem.message.list": "必須是列表",
"config.problem.message.object": "必須是物件",
"config.problem.message.present": "檔案中必須寫明這一項",
"config.problem.message.hidden_section": "你無權檢視的分組中存在問題,請聯絡伺服器擁有者處理",
"config.game.title": "遊戲規則",
"config.game.summary": "伺服器統一的玩法規則。修改後重新啟動伺服器生效。",
"config.game.section.story.title": "開局章節",
"config.game.section.story.help": "首次成功初始化後永久儲存在伺服器狀態中,之後不能更改;不能透過刪除資料庫切換開局。",
"config.game.field.story.start_pack_id.label": "起始章節",
"config.game.field.story.start_pack_id.option.21.label": "店長篇",
"config.game.field.story.start_pack_id.option.21.help": "目前用戶端預設的開局,使用該篇的任務和教學流程。",
"config.game.field.story.start_pack_id.option.1.label": "舊主線第一章",
"config.game.field.story.start_pack_id.option.1.help": "使用目前 GameData 中該章的開場劇情、初始任務及購卡獎勵。",
"config.game.lock.story.start_pack_id": "首次初始化後已永久儲存於伺服器狀態,不能再更改",
"config.game.section.gacha.title": "抽卡",
"config.game.field.gacha.include_collaboration_ur_weapons.label": "UR 必得裝備券加入聯動專武",
"config.game.field.gacha.include_collaboration_ur_weapons.help": "在原池中加入 14 種聯動角色 UR 專武(裝備 943200–943213),沿用同星級單件權重;只改變券池候選,不直接發放裝備。",
"config.game.section.purchases.title": "付費鑽石儲值",
"config.game.section.purchases.help": "普通現金商品固定消耗付費鑽石,價格由 GameData 換算;這裡只設定付費鑽石儲值本身的兌換方式。",
"config.game.field.purchases.diamond_recharge.currency.label": "儲值方式",
"config.game.field.purchases.diamond_recharge.currency.option.free.label": "免費",
"config.game.field.purchases.diamond_recharge.currency.option.free.help": "不扣貨幣,直接發放所選儲值商品的原始獎勵。",
"config.game.field.purchases.diamond_recharge.currency.option.gold.label": "金幣兌換",
"config.game.field.purchases.diamond_recharge.currency.option.gold.help": "每單位一般付費鑽石消耗設定數量的金幣。",
"config.game.field.purchases.diamond_recharge.currency.option.diamonds.label": "普通鑽石兌換",
"config.game.field.purchases.diamond_recharge.currency.option.diamonds.help": "每單位一般付費鑽石消耗設定數量的普通鑽石。",
"config.game.field.purchases.diamond_recharge.currency.option.ban.label": "禁止儲值",
"config.game.field.purchases.diamond_recharge.currency.option.ban.help": "禁止購買付費鑽石儲值商品,不影響玩家已有付費鑽石。",
"config.game.field.purchases.diamond_recharge.currency.option..label": "禁止儲值(空字串)",
"config.game.field.purchases.diamond_recharge.currency.option..help": "與 ban 相同的舊寫法。",
"config.game.field.purchases.diamond_recharge.gold_per_paid_diamond.label": "金幣 / 付費鑽石",
"config.game.field.purchases.diamond_recharge.gold_per_paid_diamond.help": "金幣兌換時每單位一般付費鑽石的費用。即使未選用也必須合法。",
"config.game.field.purchases.diamond_recharge.diamonds_per_paid_diamond.label": "普通鑽石 / 付費鑽石",
"config.game.field.purchases.diamond_recharge.diamonds_per_paid_diamond.help": "普通鑽石兌換時每單位一般付費鑽石的費用。即使未選用也必須合法。",
"config.game.section.realtime.title": "即時多人連線",
"config.game.section.realtime.help": "動作小遊戲、連線釣魚與隨機防禦使用的原生 TCP/UDP 連線。關閉時不監聽即時連接埠,會影響玩家體驗。",
"config.game.field.realtime.enabled.label": "啟用即時多人連線",
"config.game.field.realtime.public_host.label": "公開主機名稱",
"config.game.field.realtime.public_host.help": "玩家可連線的主機名稱,不含通訊協定、路徑或連接埠。",
"config.game.field.realtime.tcp_port.label": "公開 TCP 連接埠",
"config.game.field.realtime.udp_port.label": "公開 UDP 連接埠",
"config.game.field.realtime.tcp_listen.label": "TCP 監聽位址",
"config.game.field.realtime.tcp_listen.help": "公開連接埠可與監聽連接埠不同,適用於連接埠轉送。",
"config.game.field.realtime.udp_listen.label": "UDP 監聽位址",
"config.game.field.realtime.tls_cert_file.label": "TLS 憑證",
"config.game.field.realtime.tls_cert_file.help": "與公開主機名符合且受用戶端信任的憑證。相對路徑以 game.json 所在目錄為基準;更新後新握手自動載入。",
"config.game.field.realtime.tls_key_file.label": "TLS 私鑰",
"config.game.field.realtime.tls_key_file.help": "私鑰只留在伺服器,須允許服務程序讀取。",
"config.game.field.realtime.development_plain_loopback.label": "本機開發明文模式",
"config.game.field.realtime.development_plain_loopback.help": "僅限本機開發:監聽位址和公開位址都必須是loopback IP,此時不需要憑證。",
"config.game.section.text_moderation.title": "文字審查",
"config.game.section.text_moderation.help": "本機規則先執行,透過後才呼叫第三方。已有暱稱和簡介不會在登入時重新審查。",
"config.game.field.text_moderation.rule_files.label": "本機詞庫檔案",
"config.game.field.text_moderation.rule_files.help": "UTF-8 .txt(每行一個詞,使用子字串比對)或 .json(逐條指定比對方式與範圍),每個檔案最多 4 MiB。相對路徑以 game.json 所在目錄為基準。",
"config.game.field.text_moderation.provider.type.label": "第三方審查",
"config.game.field.text_moderation.provider.type.option.off.label": "關閉",
"config.game.field.text_moderation.provider.type.option.http_json.label": "通用 HTTP JSON",
"config.game.field.text_moderation.provider.type.option.http_json.help": "連接自行架設的審查服務或第三方轉接閘道。",
"config.game.field.text_moderation.provider.type.option.azure_content_safety.label": "Azure AI Content Safety",
"config.game.field.text_moderation.provider.endpoint.label": "審查端點",
"config.game.field.text_moderation.provider.endpoint.help": "請使用 HTTPS。只有 loopback 位址允許 HTTP,且不會跟隨重新導向。Azure 請填入資源的根位址。",
"config.game.field.text_moderation.provider.api_key_env.label": "API 金鑰環境變數",
"config.game.field.text_moderation.provider.api_key_env.help": "伺服器從這個環境變數讀取金鑰,設定檔案裡不儲存金鑰本身。",
"config.game.field.text_moderation.provider.api_key_header.label": "API 金鑰標頭",
"config.game.field.text_moderation.provider.api_key_header.help": "Authorization 標頭會傳送 Bearer <key>;其他標頭名稱則原樣傳遞金鑰。",
"config.game.field.text_moderation.provider.scopes.label": "審查範圍",
"config.game.field.text_moderation.provider.scopes.help": "第三方服務只審查明確列出的輸入來源。",
"config.game.field.text_moderation.provider.scopes.option.nickname.label": "玩家暱稱",
"config.game.field.text_moderation.provider.scopes.option.greeting.label": "個人簡介",
"config.game.field.text_moderation.provider.scopes.option.master_title.label": "主角稱呼",
"config.game.field.text_moderation.provider.scopes.option.preset_name.label": "隊伍預設名稱",
"config.game.field.text_moderation.provider.scopes.option.equipment_preset_name.label": "裝備預設名稱",
"config.game.field.text_moderation.provider.scopes.option.equipment_mark.label": "裝備標記",
"config.game.field.text_moderation.provider.scopes.option.monster_hunt_preset_name.label": "魔獸追蹤者預設名稱",
"config.game.field.text_moderation.provider.scopes.option.guild_raid_preset_name.label": "公會戰預設名稱",
"config.game.field.text_moderation.provider.scopes.option.colosseum_preset_name.label": "競技場預設名稱",
"config.game.field.text_moderation.provider.scopes.option.guild_name.label": "公會名稱",
"config.game.field.text_moderation.provider.scopes.option.guild_message.label": "公會介紹",
"config.game.field.text_moderation.provider.scopes.option.guild_notice.label": "公會公告",
"config.game.field.text_moderation.provider.scopes.option.room_name.label": "房間名稱",
"config.game.field.text_moderation.provider.scopes.option.chat.label": "連線聊天",
"config.game.field.text_moderation.provider.timeout_ms.label": "逾時(毫秒)",
"config.game.field.text_moderation.provider.failure_policy.label": "服務無法使用時",
"config.game.field.text_moderation.provider.failure_policy.option.deny.label": "暫不接受修改",
"config.game.field.text_moderation.provider.failure_policy.option.deny.help": "用戶端提示審查暫時不可用。",
"config.game.field.text_moderation.provider.failure_policy.option.allow.label": "放行",
"config.game.field.text_moderation.provider.failure_policy.option.allow.help": "放行已透過本機規則的文字;明確拒絕的結果不會被放行。",
"config.game.field.text_moderation.provider.severity_threshold.label": "Azure 拒絕門檻",
"config.game.field.text_moderation.provider.severity_threshold.help": "任一類別達到該嚴重程度即拒絕;0 表示連嚴重程度 0 的結果也拒絕。",
"config.game.section.format.title": "格式",
"config.game.field.schema_version.label": "格式版本",
"config.authentication.title": "登入與認證",
"config.authentication.summary": "玩家登入方式。修改後重新啟動伺服器生效;金鑰只從環境變數讀取,不寫入此檔案。",
"config.authentication.section.mode.title": "認證模式",
"config.authentication.field.mode.label": "模式",
"config.authentication.field.mode.option.local.label": "本機單人",
"config.authentication.field.mode.option.local.help": "無需登入,只有一個本機玩家。",
"config.authentication.field.mode.option.oauth.label": "OAuth(線上)",
"config.authentication.field.mode.option.oauth.help": "玩家透過 Discord 或 Google 登入,伺服器可供多人使用。",
"config.authentication.field.public_url.label": "公開 URL",
"config.authentication.field.public_url.help": "玩家和 OAuth 回呼存取的根位址,不帶路徑;除 localhost 外必須使用 HTTPS。",
"config.authentication.field.master_key_env.label": "主金鑰環境變數",
"config.authentication.field.master_key_env.help": "該環境變數須為 base64 編碼的 32 位元組金鑰,用於加密登入資料。",
"config.authentication.section.providers.title": "登入提供方",
"config.authentication.section.providers.help": "回呼 URL 為 <public URL>/auth/<provider>/callback。",
"config.authentication.field.providers.label": "啟用的提供方",
"config.authentication.field.providers.*.client_id.label": "Client ID",
"config.authentication.field.providers.*.client_secret_env.label": "Client secret 環境變數",
"config.authentication.section.session.title": "工作階段有效時間",
"config.authentication.section.session.help": "使用 Go 時長格式,例如 15m、720h。留空使用預設值。",
"config.authentication.field.session.access_ttl.label": "存取權杖有效期",
"config.authentication.field.session.refresh_ttl.label": "更新權杖有效期",
"config.authentication.field.session.device_transaction_ttl.label": "登入交易有效時間",
"config.resources.title": "用戶端資源",
"config.resources.summary": "用戶端下載 ServerData 與 GameData 的來源。修改後重新啟動伺服器生效;版本號來自 versions.json,不在此設定。",
"config.resources.section.source.title": "資源來源",
"config.resources.field.mode.label": "模式",
"config.resources.field.mode.option.official.label": "官方 CDN",
"config.resources.field.mode.option.official.help": "使用目前版本的官方資源位址。",
"config.resources.field.mode.option.server.label": "自行架設的資源來源",
"config.resources.field.mode.option.server.help": "從伺服器擁有者提供的靜態 CDN 或快取反向代理下載。",
"config.resources.field.server_data_url.label": "ServerData 位址",
"config.resources.field.server_data_url.help": "絕對 HTTP(S) 位址,末尾不帶斜線;除loopback位址外必須使用 HTTPS。",
"config.resources.field.game_data_url.label": "GameData 位址",
"config.resources.field.game_data_url.help": "絕對 HTTP(S) 位址,末尾不帶斜線;除loopback位址外必須使用 HTTPS。",
"config.updates.title": "版本更新",
"config.updates.summary": "檢查新版、預下載與維護更新方式。檢查與下載不影響遊戲;更新需要在管理台或命令列確認。修改後重新啟動伺服器生效。",
"config.updates.section.check.title": "檢查與下載",
"config.updates.field.check.label": "自動檢查新版",
"config.updates.field.check.help": "啟動後及執行期間按間隔檢查發布清單,並加隨機偏移。",
"config.updates.field.check_interval.label": "檢查間隔",
"config.updates.field.download.label": "提前下載",
"config.updates.field.download.help": "在背景下載並驗證新版本,減少套用更新時的等待時間。",
"config.updates.field.manifest_url.label": "發布清單位址",
"config.updates.field.manifest_url.help": "留空使用內建位址;清單的簽章必須能以內建公開金鑰驗證。",
"config.updates.field.changelog_urls.label": "更新日誌位址",
"config.updates.field.changelog_urls.help": "按順序嘗試;留空使用內建的 GitHub 與 Gitea 位址。",
"config.updates.field.changelog.notices.label": "將更新日誌發布為遊戲內公告",
"config.updates.section.install.title": "安裝方式",
"config.updates.field.method.label": "安裝方式",
"config.updates.field.method.option.native.label": "原生(systemd)",
"config.updates.field.method.option.native.help": "替換程式檔案後退出,由 systemd 以新版重新啟動;失敗時自動換回上一版程式。",
"config.updates.field.method.option.docker.label": "Docker",
"config.updates.field.method.option.docker.help": "等待進行中的請求完成,儲存後結束程式,再由主機腳本切換至清單指定的映像檔。",
"config.updates.field.method.option.none.label": "僅通知",
"config.updates.field.method.option.none.help": "只檢查和顯示新版本,無法套用更新。",
"config.updates.field.countdown_minutes.label": "預設倒數計時(分鐘)",
"config.updates.field.maintenance_minutes.label": "預計維護時長(分鐘)",
"config.updates.field.webhook_url_env.label": "Webhook 環境變數",
"config.updates.field.webhook_url_env.help": "發現新版時向該環境變數中的位址 POST 一次 JSON;留空不傳送。",
"console.updates.title": "版本更新",
"console.updates.lead": "伺服器會定期檢查已簽署的發布清單,並可提前下載及驗證。套用更新時,會先通知線上玩家、停止接受新登入、等待進行中的請求完成並儲存,再切換至新版本。",
"console.updates.check": "立即檢查",
"console.updates.fact.current_version": "目前版本",
"console.updates.fact.method": "安裝方式",
"console.updates.fact.auto_check": "自動檢查",
"console.updates.fact.last_check": "上次檢查",
"console.updates.fact.check_error": "檢查失敗",
"console.updates.fact.last_switch": "上次切換",
"console.updates.enabled": "開啟",
"console.updates.disabled": "關閉",
"console.updates.never_checked": "尚未檢查",
"console.updates.method.native": "原生(systemd)",
"console.updates.method.docker": "Docker",
"console.updates.method.none": "僅通知",
"console.updates.phase.preparing": "準備中(下載、驗證與預檢)",
"console.updates.phase.countdown": "倒數計時",
"console.updates.phase.closing": "等待請求完成並切換版本",
"console.updates.outcome.succeeded": "成功",
"console.updates.outcome.rolled_back": "已還原為先前的程式版本",
"console.updates.outcome.needs_operator": "需要人工處理",
"console.updates.outcome.awaiting_host": "等待主機",
"console.updates.outcome.host_timed_out": "主機未切換",
"console.updates.outcome.switch_failed": "切換失敗",
"console.updates.outcome.cancelled": "已取消",
"console.updates.migration.none": "無存檔遷移",
"console.updates.migration.reversible": "存檔遷移(可還原)",
"console.updates.migration.irreversible": "存檔遷移(不可還原)",
"console.updates.last_switch_value": "%[1]s → %[2]s:%[3]s",
"console.updates.last_switch_message": "%[1]s → %[2]s:%[3]s,%[4]s",
"console.updates.up_to_date": "已是最新版本。",
"console.updates.available": "可用版本 %[1]s",
"console.updates.published": "發布於 %[1]s",
"console.updates.downloaded": "已下載並驗證",
"console.updates.download_failed": "下載失敗:%[1]s",
"console.updates.not_downloaded": "尚未下載",
"console.updates.maintenance": "維護:%[1]s → %[2]s(%[3]s)",
"console.updates.maintenance_at": "維護:%[1]s → %[2]s,%[3]s 開始(%[4]s)",
"console.updates.cancel": "取消維護",
"console.updates.delay": "倒數計時(分鐘)",
"console.updates.confirm_irreversible": "我已閱讀遷移說明,並了解此遷移無法還原",
"console.updates.apply": "套用更新",
"console.updates.apply.title": "套用伺服器更新?",
"console.updates.apply.body_countdown": "準備完成後會開始 %[1]s 分鐘倒數:線上玩家會看到維護通知,最後 1 分鐘停止接受新登入,接著等待進行中的請求完成、儲存並切換至 %[2]s。",
"console.updates.apply.body_now": "準備完成後會立即停止接受新登入,等待進行中的請求完成、儲存並切換至 %[1]s。",
"console.updates.scheduled": "已安排維護。",
"console.updates.cancelled": "已取消維護。",
"console.updates.checking": "正在檢查……"
}
+65 -42
View File
@@ -1,104 +1,113 @@
<!doctype html>
<html lang="zh-CN">
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>BD2 管理台</title>
<title>BD2</title>
<link rel="stylesheet" href="assets/app.css">
<script src="assets/text.js" defer></script>
<script src="assets/app.js" defer></script>
</head>
<body>
<header class="top">
<div class="brand"><span class="seal-mark" aria-hidden="true"></span><b>BD2</b><span>管理台</span></div>
<div class="brand"><span class="seal-mark" aria-hidden="true"></span><b>BD2</b><span data-i18n="console.brand"></span></div>
<nav class="tabs" id="tabs" hidden>
<a href="#mail" data-view="mail">邮件发放</a>
<a href="#players" data-view="players" data-owner>玩家</a>
<a href="#config" data-view="config" data-owner>服务器配置</a>
<a href="#mail" data-view="mail" data-i18n="console.nav.mail"></a>
<a href="#players" data-view="players" data-owner data-i18n="console.nav.players"></a>
<a href="#config" data-view="config" data-owner data-i18n="console.nav.config"></a>
<a href="#updates" data-view="updates" data-owner data-i18n="console.nav.updates"></a>
</nav>
<div class="account" id="account" hidden><span class="user" id="account-name"></span><button type="button" id="logout">退出</button></div>
<div class="account" id="account" hidden><span class="user" id="account-name"></span><button type="button" id="logout" data-i18n="console.logout"></button></div>
<select class="locale" id="locale" data-i18n-attr="aria-label:console.language;title:console.language">
<option value="en_us" lang="en">English</option>
<option value="ko_kr" lang="ko">한국어</option>
<option value="ja_jp" lang="ja">日本語</option>
<option value="zh_tw" lang="zh-TW">繁體中文</option>
<option value="zh_cn" lang="zh-CN">简体中文</option>
</select>
</header>
<main class="desk">
<!-- 登录 -->
<!-- Sign in -->
<section class="view sign-in" id="view-sign-in" hidden>
<div class="card sheet">
<h1>进入管理台</h1>
<p class="muted" id="sign-in-lead">正在读取服务器信息……</p>
<h1 data-i18n="console.signin.title"></h1>
<p class="muted" id="sign-in-lead" data-i18n="console.signin.loading"></p>
<div class="providers" id="providers"></div>
<p id="sign-in-status" class="status" aria-live="polite"></p>
</div>
</section>
<!-- 邮件发放 -->
<!-- Mail -->
<section class="view" id="view-mail" hidden>
<section class="card recipient" id="recipient">
<div class="who">
<span class="eyebrow">收件人</span>
<div class="uid none" id="uid-display" title="点击复制 UID">——</div>
<span class="eyebrow" data-i18n="console.mail.recipient"></span>
<div class="uid none" id="uid-display" data-i18n-attr="title:console.mail.copy_uid">——</div>
<p id="recipient-note" class="muted"></p>
</div>
<div class="recipient-side">
<label id="player-selector" class="player" hidden>切换玩家<select id="player"></select></label>
<label id="player-selector" class="player" hidden><span data-i18n="console.mail.switch_player"></span><select id="player"></select></label>
</div>
</section>
<fieldset id="tools" class="work" disabled>
<div class="lock"><span id="lock-note">正在读取……</span></div>
<div class="lock"><span id="lock-note" data-i18n="console.loading"></span></div>
<section class="card catalog">
<div class="cat-head"><h2>物品目录</h2><span id="count" class="muted"></span></div>
<div class="cat-head"><h2 data-i18n="console.mail.catalog"></h2><span id="count" class="muted"></span></div>
<div class="search">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true"><circle cx="7" cy="7" r="4.8"/><path d="m10.6 10.6 3.4 3.4" stroke-linecap="round"/></svg>
<input id="q" type="search" placeholder="名称、ID、类别或别名,空格分隔多个词" autocomplete="off" spellcheck="false" aria-label="搜索物品" aria-controls="items">
<input id="q" type="search" data-i18n-attr="placeholder:console.mail.search.placeholder;aria-label:console.mail.search.label" autocomplete="off" spellcheck="false" aria-controls="items">
<kbd>/</kbd>
</div>
<div class="chips" id="cats" aria-label="按类别筛选"></div>
<div class="recent" id="recent" hidden><span class="eyebrow">最近寄出</span></div>
<ol class="items" id="items" role="listbox" aria-label="物品"><li class="empty">正在读取物品目录……</li></ol>
<p class="keys muted"><span><kbd>/</kbd>搜索</span><span><kbd>↑</kbd><kbd>↓</kbd>挑选</span><span><kbd>Enter</kbd>放入包裹单</span><span><kbd>Esc</kbd>清空</span></p>
<div class="chips" id="cats" data-i18n-attr="aria-label:console.mail.filter_label"></div>
<div class="recent" id="recent" hidden><span class="eyebrow" data-i18n="console.mail.recent"></span></div>
<ol class="items" id="items" role="listbox" data-i18n-attr="aria-label:console.mail.items_label"><li class="empty" data-i18n="console.mail.catalog_loading"></li></ol>
<p class="keys muted"><span><kbd>/</kbd><span data-i18n="console.mail.keys.search"></span></span><span><kbd>↑</kbd><kbd>↓</kbd><span data-i18n="console.mail.keys.pick"></span></span><span><kbd>Enter</kbd><span data-i18n="console.mail.keys.add"></span></span><span><kbd>Esc</kbd><span data-i18n="console.mail.keys.clear"></span></span></p>
</section>
<aside class="side">
<form id="form" class="card slip" novalidate>
<div class="slip-head"><span class="eyebrow">包裹单</span><span class="to">寄往 UID<b id="slip-uid">—</b></span></div>
<div class="slip-head"><span class="eyebrow" data-i18n="console.mail.slip"></span><span class="to"><span data-i18n="console.mail.slip.to"></span><b id="slip-uid">—</b></span></div>
<div class="parcel empty" id="parcel"></div>
<div class="field">
<label for="quantity">数量 <span id="qty-hint">支持 5k、2w、3万</span></label>
<label for="quantity"><span data-i18n="console.mail.quantity"></span> <span id="qty-hint" data-i18n="console.mail.quantity.hint"></span></label>
<input id="quantity" value="1" inputmode="numeric" autocomplete="off" required>
<div class="presets" id="presets" title="点击设为该数量,按住 Shift 点击则累加">
<button type="button" data-q="1">1</button><button type="button" data-q="10">10</button><button type="button" data-q="100">100</button><button type="button" data-q="1000">1k</button><button type="button" data-q="10000">1w</button>
<div class="presets" id="presets" data-i18n-attr="title:console.mail.presets.title">
<button type="button" data-q="1">1</button><button type="button" data-q="10">10</button><button type="button" data-q="100">100</button><button type="button" data-q="1000" data-i18n="console.mail.presets.thousand"></button><button type="button" data-q="10000" data-i18n="console.mail.presets.ten_thousand"></button>
</div>
</div>
<details class="letter" id="letter">
<summary>附信 <span id="letter-peek">测试物品</span></summary>
<label>邮件标题<input id="title" value="测试物品" required maxlength="500"></label>
<label>正文<textarea id="body" required maxlength="5000">由管理台发放。</textarea></label>
<summary data-i18n-attr="data-expand:console.mail.letter.expand;data-collapse:console.mail.letter.collapse"><span data-i18n="console.mail.letter"></span> <span id="letter-peek"></span></summary>
<label><span data-i18n="console.mail.letter.title"></span><input id="title" data-i18n-attr="value:console.mail.letter.default_title" required maxlength="500"></label>
<label><span data-i18n="console.mail.letter.body"></span><textarea id="body" data-i18n="console.mail.letter.default_body" required maxlength="5000"></textarea></label>
</details>
<button id="grant-submit" class="btn seal send">寄出<kbd>Ctrl ↵</kbd></button>
<button id="grant-submit" class="btn seal send"><span data-i18n="console.mail.send"></span><kbd>Ctrl ↵</kbd></button>
<p id="status" class="status" aria-live="polite"></p>
</form>
<section class="card panel">
<h3><label class="switch"><input id="unlimited-inventory" type="checkbox" role="switch"><span class="track" aria-hidden="true"></span>无限背包容量</label></h3>
<h3><label class="switch"><input id="unlimited-inventory" type="checkbox" role="switch"><span class="track" aria-hidden="true"></span><span data-i18n="console.inventory.unlimited"></span></label></h3>
<div id="inventory-limits" class="limits"></div>
<p class="hint">只影响当前玩家,玩家重新登录游戏后生效,无需重启服务端。关闭后恢复该玩家原有容量。</p>
<p class="hint" data-i18n="console.mail.inventory.hint"></p>
<p id="inventory-status" class="status" aria-live="polite"></p>
</section>
<section class="card panel">
<h3>本次寄件 <span class="muted" id="log-count"></span></h3>
<h3><span data-i18n="console.mail.log.title"></span> <span class="muted" id="log-count"></span></h3>
<ol class="log" id="log"></ol>
<p class="log-empty" id="log-empty">寄出的物品会记在这里,点击发放标识可复制。</p>
<p class="log-empty" id="log-empty" data-i18n="console.mail.log.empty"></p>
</section>
</aside>
</fieldset>
</section>
<!-- 玩家 -->
<!-- Players -->
<section class="view" id="view-players" hidden>
<section class="card roster">
<div class="roster-head">
<div><h2>玩家</h2><p class="muted">按游戏账号任命管理员,对方用自己的游戏账号登录管理台。管理员默认可以寄件和查看玩家,其余权限由服主逐项授予。</p></div>
<div class="search small"><input id="player-q" type="search" placeholder="UID 或名称" autocomplete="off" aria-label="筛选玩家"></div>
<div><h2 data-i18n="console.roster.title"></h2><p class="muted" data-i18n="console.roster.lead"></p></div>
<div class="search small"><input id="player-q" type="search" data-i18n-attr="placeholder:console.roster.search.placeholder;aria-label:console.roster.search.label" autocomplete="off"></div>
</div>
<table class="roster-table">
<thead><tr id="roster-head-row"></tr></thead>
@@ -108,10 +117,10 @@
</section>
</section>
<!-- 服务器配置 -->
<!-- Server configuration -->
<section class="view" id="view-config" hidden>
<div class="config-layout">
<nav class="card doc-nav" id="doc-nav" aria-label="配置文件"></nav>
<nav class="card doc-nav" id="doc-nav" data-i18n-attr="aria-label:console.config.documents"></nav>
<div class="config-main">
<div id="config-banners"></div>
<form id="config-form" class="config-form" novalidate></form>
@@ -120,18 +129,32 @@
</div>
<div class="savebar" id="savebar" hidden>
<span id="savebar-text"></span>
<button type="button" class="btn ghost" id="show-diff">查看改动</button>
<button type="button" class="btn ghost" id="discard">放弃</button>
<button type="button" class="btn seal" id="save">保存 <kbd>Ctrl S</kbd></button>
<button type="button" class="btn ghost" id="show-diff" data-i18n="console.config.show_diff"></button>
<button type="button" class="btn ghost" id="discard" data-i18n="console.config.discard"></button>
<button type="button" class="btn seal" id="save"><span data-i18n="console.config.save"></span> <kbd>Ctrl S</kbd></button>
</div>
</section>
<!-- Updates -->
<section class="view" id="view-updates" hidden>
<section class="card updates">
<div class="roster-head">
<div><h2 data-i18n="console.updates.title"></h2><p class="muted" data-i18n="console.updates.lead"></p></div>
<button type="button" class="btn" id="update-check" data-i18n="console.updates.check"></button>
</div>
<dl class="update-facts" id="update-facts"></dl>
<div id="update-available"></div>
<div class="update-actions" id="update-actions"></div>
<p id="update-status" class="status" aria-live="polite"></p>
</section>
</section>
</main>
<dialog class="ask" id="ask">
<h3 id="ask-title"></h3>
<p id="ask-body"></p>
<div id="ask-extra"></div>
<div class="ask-actions"><button type="button" class="btn" id="ask-cancel">取消</button><button type="button" class="btn seal" id="ask-ok">确定</button></div>
<div class="ask-actions"><button type="button" class="btn" id="ask-cancel" data-i18n="console.dialog.cancel"></button><button type="button" class="btn seal" id="ask-ok"></button></div>
</dialog>
<div class="toast" id="toast" role="status"></div>
</body>
@@ -0,0 +1,86 @@
//go:build integration
package app
import (
"bytes"
"testing"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/runtime/player"
)
// LocalText457/469 and FriendShipWeightPopupUI describe partner efficiency;
// current Lathel->Justia is a directed pair with base10 and10% bonus per win.
func TestQuestVictoryPersistsPartnerProgressAndRetryCannotDuplicateIt(t *testing.T) {
g := newInventoryGameplay(t)
var entered []roster.Character
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
if _, err := p.collection.GrantCostumes(ctx, "battle-partners", []uint64{101, 201}, p.design.regularGacha); err != nil {
t.Fatal(err)
}
for _, c := range p.worldService.CharacterService().RawAll() {
if !roster.IsStoryCharacter(c) && !roster.IsCharmCharacter(c) && (c.ID == 10 || c.ID == 20) {
entered = append(entered, c)
}
}
if len(entered) != 2 {
t.Fatal("battle fixture requires owned Lathel and Justia")
}
if err := p.progressState.SetActivePackID(ctx, 1); err != nil {
t.Fatal(err)
}
for quest := 1; quest < 9; quest++ {
if err := p.progressState.ClearQuest(ctx, quest, 1, 0); err != nil {
t.Fatal(err)
}
}
})
g.reopen()
enter := append(appScalar(3, 1), appScalar(4, 1)...)
enter = append(enter, appScalar(5, 1)...)
g.call("/BattleEnter", enter)
start := appScalar(2, 1)
for i, c := range entered {
deck := append(appScalar(1, c.InvenIndex), appScalar(2, uint64(i))...)
deck = append(deck, appScalar(3, uint64(i+1))...)
start = append(start, appMessage(3, deck)...)
character := append(appScalar(2, c.InvenIndex), appScalar(3, 100)...)
character = append(character, appScalar(4, 100)...)
start = append(start, appMessage(5, character)...)
}
g.call("/BattleStart", start)
partnerPoint := func() uint64 {
t.Helper()
for _, row := range appRows(g.call("/CharPartnerInfo", nil), 1) {
if appValue(row, 1) == 1 && appValue(row, 2) == 2 {
return appValue(row, 3)
}
}
return 0
}
if partnerPoint() != 0 {
t.Fatal("starting a battle granted partner progress before victory")
}
failed := g.request("/BattleEnd", appScalar(2, 1))
failed.Requests = append(failed.Requests, player.Request{Path: "/ItemDump", Body: append(appScalar(1, 900), appMessage(2, inventoryItem(999999, 1, 8, 1))...)})
g.execute(failed, true)
g.reopen()
if partnerPoint() != 0 {
t.Fatal("failed settlement batch committed partner progress")
}
end := g.request("/BattleEnd", appScalar(2, 1))
reply := g.execute(end, false)
partners := appRows(reply, 9)
if len(partners) != 1 || appValue(partners[0], 3) != 11 || partnerPoint() != 11 {
t.Fatal("victory did not persist the partner gain consumed by the client")
}
g.reopen()
if partnerPoint() != 11 {
t.Fatal("partner gain disappeared after reopening account")
}
if retry := g.execute(end, false); !bytes.Equal(retry, reply) || partnerPoint() != 11 {
t.Fatal("settlement replay duplicated partner progress or changed response")
}
}
+39 -1
View File
@@ -2,13 +2,17 @@ package app
import (
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/release"
"bd2server/internal/common/versionconfig"
"bd2server/internal/server/design/gameconfig"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/events/calendar"
"bd2server/internal/server/domain/notice"
"bd2server/internal/server/gateway/authconfig"
"bd2server/internal/server/gateway/bootstrap"
"bd2server/internal/server/platform/textmoderation"
"bd2server/internal/server/platform/updates"
resourcefetch "bd2server/internal/server/resources/fetch"
"bd2server/internal/server/resources/policy"
"context"
"errors"
@@ -41,11 +45,16 @@ type configuration struct {
worldSeed string
devToolsConfig string
versions versionconfig.Config
compatibility updateCompatibility
calendars *calendar.Set
gameRules gameconfig.Config
gameFile *commonconfig.File[gameconfig.Config]
authFile *commonconfig.File[authconfig.Config]
resourceFile *commonconfig.File[resourcepolicy.Config]
updateFile *commonconfig.File[updates.Config]
updates updates.Config
notices *notice.Board
serveArgs []string
textModerator *textmoderation.Service
authentication authconfig.Config
authRuntime authconfig.Runtime
@@ -63,6 +72,7 @@ func loadConfiguration(args []string) (result *configuration, loadErr error) {
authConfigPath := fs.String("authentication-config", "", "authentication.json path (default DATA_DIR/config/authentication.json)")
resourceConfigPath := fs.String("resource-config", "", "resources.json path (default DATA_DIR/config/resources.json)")
gameConfigPath := fs.String("game-config", "", "game.json path (default DATA_DIR/config/game.json)")
updateConfigPath := fs.String("update-config", "", "updates.json path (default DATA_DIR/config/updates.json)")
listen := fs.String("listen", "127.0.0.1:8080", "local listen address")
dataDir := fs.String("data-dir", "", "server data directory (defaults beside the executable)")
gameDataVersion := fs.String("game-data-version", "", "validated GameData version (defaults to versions.json)")
@@ -157,11 +167,32 @@ func loadConfiguration(args []string) (result *configuration, loadErr error) {
return nil, err
}
*resourceConfigPath = resourceFile.Path()
if *updateConfigPath == "" {
*updateConfigPath = updates.Document.Path(configDirectory)
}
updateFile, updateConfig, err := updates.Document.Open(*updateConfigPath)
if err != nil {
return nil, err
}
*devToolsConfig = resolveDevelopmentSettingsPath(*dataDir, *devToolsConfig)
if *mailGrantSpool == "" {
*mailGrantSpool = filepath.Join(*dataDir, "mail-grants-spool.json")
}
gameData := filepath.Join(*dataDir, "resources", "GameData")
compatibility, err := loadUpdateCompatibility(versions)
if err != nil {
return nil, err
}
if compatibility.fingerprint != nil && compatibility.fingerprint.RequireGameUpdate && compatibility.fingerprint.Game != nil {
g := compatibility.fingerprint.Game
root := updates.ResourceDirectory(*dataDir, *g)
if _, ready := resourcefetch.Prepared(root, *g); !ready {
if _, err := resourcefetch.Fetch(context.Background(), resourcefetch.Options{OutputRoot: root, Pinned: g}); err != nil {
return nil, err
}
}
gameData = filepath.Join(root, "GameData")
}
if *stateDirectory == "" {
*stateDirectory = filepath.Join(*dataDir, "state")
}
@@ -199,6 +230,12 @@ func loadConfiguration(args []string) (result *configuration, loadErr error) {
if downloaded {
slog.Info("repaired GameData from official CDN", "archive", verifiedGameData.ArchivePath, "entries", verifiedGameData.EntryCount)
}
if compatibility.fingerprint != nil && compatibility.fingerprint.RequireGameUpdate && compatibility.fingerprint.Game != nil {
g := compatibility.fingerprint.Game
if !release.Matches(verifiedGameData.ArchivePath, release.File{Size: g.DataBytes, SHA256: g.DataSHA256}) {
return nil, errors.New("installed GameData differs from signed update fingerprint")
}
}
if err := calendars.ValidateDesign(gameData, *gameDataVersion); err != nil {
return nil, fmt.Errorf("validate project calendar GameData references: %w", err)
}
@@ -222,6 +259,7 @@ func loadConfiguration(args []string) (result *configuration, loadErr error) {
deckSeed: *deckSeed,
worldSeed: *worldSeed,
devToolsConfig: *devToolsConfig,
versions: versions, calendars: calendars, gameRules: gameRules, gameFile: gameFile, authFile: authFile, resourceFile: resourceFile, authentication: authentication, authRuntime: authRuntime, publicResources: publicResources, bootstrap: cfg, gameData: gameData, verifiedGameData: verifiedGameData,
versions: versions, calendars: calendars, gameRules: gameRules, gameFile: gameFile, authFile: authFile, resourceFile: resourceFile, updateFile: updateFile, updates: updateConfig, notices: notice.NewBoard(nil), serveArgs: args, authentication: authentication, authRuntime: authRuntime, publicResources: publicResources, bootstrap: cfg, gameData: gameData, verifiedGameData: verifiedGameData,
compatibility: compatibility,
}, nil
}
+1 -1
View File
@@ -63,7 +63,7 @@ func openConsole(c *configuration, design *designCatalog, seeds *seedCatalog, au
Items: admin.CapacityLimits{Default: slots.Items.Default, Maximum: slots.Items.Maximum},
Equipment: admin.CapacityLimits{Default: slots.Equipment.Default, Maximum: slots.Equipment.Maximum},
},
Configuration: commonconfig.NewRegistry(c.gameFile, c.authFile, c.resourceFile),
Configuration: commonconfig.NewRegistry(c.gameFile, c.authFile, c.resourceFile, c.updateFile),
Secure: c.authentication.Mode == "oauth" && c.authRuntime.PublicURLParsed != nil && c.authRuntime.PublicURLParsed.Scheme == "https",
Server: func() any {
return map[string]any{
+10
View File
@@ -43,6 +43,8 @@ type designCatalog struct {
avatarProfile *gamedata.AvatarProfileDesign
equipmentSlots map[uint64]uint64
equipmentUpgrade *gamedata.EquipmentUpgradeDesign
equipmentRankPurchases *gamedata.EquipmentRankPurchaseDesign
rosterProgress *gamedata.RosterProgressDesign
equipmentCraft *gamedata.EquipmentCraftDesign
talentGrowth *gamedata.TalentGrowthDesign
equipmentSmelting *gamedata.EquipmentSmeltingDesign
@@ -171,6 +173,14 @@ func loadDesign(c *configuration, seeds *seedCatalog) (*designCatalog, error) {
if err != nil {
return nil, fmt.Errorf("load equipment upgrade GameData: %w", err)
}
d.equipmentRankPurchases, err = gamedata.LoadEquipmentRankPurchaseDesign(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load equipment rank purchases: %w", err)
}
d.rosterProgress, err = gamedata.LoadRosterProgressDesign(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load roster progression: %w", err)
}
d.equipmentCraft, err = gamedata.LoadEquipmentCraftDesign(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load equipment crafting GameData: %w", err)
@@ -0,0 +1,114 @@
//go:build integration
package app
import (
"bytes"
"encoding/json"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
)
// LocalText38037 sells every pending fish when auto-sale is selected. The
// current fish1 trap price30 and endpoint size premiums2 yield60coins per fish.
func TestFishingTrapAutoSaleUsesNativeCurrencyAndAtomicSettlement(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
g := newSquareGameplay(t, factory, accounts[0])
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
if _, err := p.eventEconomy.Apply(ctx, "trap-boat-budget", nil, []gamedata.Reward{{Type: 54, Count: 1000}}); err != nil {
t.Fatal(err)
}
})
g.call("/FishingBoatUpgrade", nil)
var fullCount uint64
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
raw, found, err := ctx.State.LoadEntry("fishing", "state", "core")
if err != nil || !found {
t.Fatal("missing fishing core", err)
}
var saved map[string]json.RawMessage
if err = json.Unmarshal(raw, &saved); err != nil {
t.Fatal(err)
}
if err = json.Unmarshal(saved["FishSlots"], &fullCount); err != nil || fullCount == 0 {
t.Fatal("invalid fishing capacity", err)
}
var next uint64
if err = json.Unmarshal(saved["Next"], &next); err != nil {
t.Fatal(err)
}
now := time.Now().Unix()
fish := make([]map[string]uint64, fullCount)
for i := range fish {
fish[i] = map[string]uint64{"Index": next + uint64(i), "ID": 1, "Count": 1, "Size": 250, "Time": uint64(now - 10000)}
}
saved["Fish"], err = json.Marshal(fish)
if err != nil {
t.Fatal(err)
}
saved["Next"], err = json.Marshal(next + fullCount)
if err != nil {
t.Fatal(err)
}
saved["Collection"], err = json.Marshal(map[string]map[string]int64{"1": {"Min": 250, "Max": 750, "Created": now - 10000}})
if err != nil {
t.Fatal(err)
}
raw, err = json.Marshal(saved)
if err != nil {
t.Fatal(err)
}
if err = ctx.State.PutEntry("fishing", "state", "core", raw); err != nil {
t.Fatal(err)
}
raw, err = json.Marshal(map[string]any{"Version": 1, "Receipt": now - 7200, "Cursor": now, "Fish": []map[string]uint64{{"ID": 1, "Size": 250}, {"ID": 1, "Size": 750}}})
if err != nil {
t.Fatal(err)
}
if err = ctx.State.PutEntry("fishing", "state", "trap", raw); err != nil {
t.Fatal(err)
}
})
g.reopen()
before := squareBalance(t, g, 54, 0)
if body := g.call("/FishingTrapInfo", nil); len(appRows(body, 2)) != 2 || appValue(body, 3) != 6 {
t.Fatal("saved pending trap did not resume")
}
g.execute(g.request("/FishingTrapCumulativeReward", nil), true)
if len(appRows(g.call("/FishingTrapInfo", nil), 2)) != 2 || squareBalance(t, g, 54, 0) != before {
t.Fatal("full-backpack rejection lost pending fish or credited currency")
}
failed := g.request("/FishingTrapCumulativeReward", appScalar(2, 1))
bad := g.request("/ItemDump", appMessage(2, inventoryItem(999999, 1, 8, 1)))
failed.Requests = append(failed.Requests, bad.Requests...)
g.execute(failed, true)
g.reopen()
if len(appRows(g.call("/FishingTrapInfo", nil), 2)) != 2 || squareBalance(t, g, 54, 0) != before {
t.Fatal("aborted sale consumed pending fish or credited coins")
}
claim := g.request("/FishingTrapCumulativeReward", appScalar(2, 1))
body := g.execute(claim, false)
if appValue(body, 5) != 6 || squareBalance(t, g, 54, 0) != before+120 {
t.Fatal("trap auto-sale did not credit authored fishing coins/experience")
}
if uint64(len(appRows(g.call("/FishingItemInfo", nil), 1))) != fullCount {
t.Fatal("auto-sale modified backpack fish")
}
info := appRows(g.call("/FishingInfo", nil), 1)
if len(info) != 1 || appValue(info[0], 1) != 6 {
t.Fatal("trap experience was only returned and not saved")
}
g.reopen()
if replay := g.execute(claim, false); !bytes.Equal(replay, body) {
t.Fatal("auto-sale replay changed")
}
if squareBalance(t, g, 54, 0) != before+120 || len(appRows(g.call("/FishingTrapInfo", nil), 2)) != 0 {
t.Fatal("reopened sale duplicated currency or pending fish")
}
if g.owner.assembly.fishingService.Profile().Exp != 6 {
t.Fatal("reopened fishing experience lost")
}
}
@@ -281,6 +281,15 @@ func TestNativeGuildRaidSettlesBothMembersAndClaimsOnce(t *testing.T) {
if appValue(entered, 4) != 1 {
t.Fatal("raid enter omitted native engine mode")
}
if i == 0 {
g.close()
f.open(g)
resume := g.pvpCall("/BattleResume", nil)
mode := appRows(resume, 1)
if len(mode) != 1 || appValue(mode[0], 1) != social.RaidBattleMode || appValue(mode[0], 2) != boss.DeckID || appValue(mode[0], 3) != 0 || appValue(resume, 3) != level || appValue(resume, 4) != boss.MonsterID || appValue(resume, 17) != season {
t.Fatal("reconnecting before the first raid turn lost the entered boss or season")
}
}
g.pvpCall("/BattleStart", appScalar(2, boss.DeckID))
g.seq++
end := registryCommand(g.account, fmt.Sprintf("raid-end-%d", i), "/BattleEnd", append(appScalar(1, g.seq), appScalar(2, 1)...))
@@ -0,0 +1,374 @@
//go:build integration
package app
import (
"bytes"
"context"
"slices"
"testing"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/runtime/player"
)
func newInventoryGameplay(t *testing.T) *puzzleGameplay {
t.Helper()
factory, accounts := newIntegrationFactory(t)
owner, err := factory.open(accounts[0])
if err != nil {
t.Fatal(err)
}
g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
t.Cleanup(func() {
if g.owner != nil {
if err := g.owner.Close(); err != nil {
t.Error(err)
}
}
})
return g
}
func inventorySetup(t *testing.T, g *puzzleGameplay, fn func(command.Context, *playerAssembly)) {
t.Helper()
tx, err := g.owner.repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
defer func() { _ = tx.Rollback() }()
fn(command.Context{Identity: command.Identity{AccountID: g.account, SessionID: "setup"}, State: tx}, g.owner.assembly)
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
}
func inventoryItem(index, id, kind, count uint64) []byte {
out := appScalar(1, index)
out = append(out, appScalar(2, id)...)
out = append(out, appScalar(3, kind)...)
return append(out, appScalar(4, count)...)
}
func inventoryEquipment(index, id uint64) []byte {
return appMessage(2, append(appScalar(1, index), appMessage(5, appScalar(1, id))...))
}
func inventoryOwnedEquipment(t *testing.T, g *puzzleGameplay, index uint64) []byte {
t.Helper()
for _, entry := range appRows(g.call("/EquipInfo", nil), 1) {
if appValue(entry, 1) == index {
return entry
}
}
return nil
}
func TestInventoryStorageMovesPreserveCountsMetadataAndRollback(t *testing.T) {
g := newInventoryGameplay(t)
// CommonPacket.AddKeepItem adds response counts, so movement replies must
// carry deltas; ResourceTable[1] permits ordinary discard and stacks to9999.
var index uint64
baseline := g.itemCount(8, 1)
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
items, err := p.ownedItems.GrantOnce(ctx, "storage-test-resource", []gamedata.BattleReward{{Type: 8, ID: 1, Count: 25}})
if err != nil {
t.Fatal(err)
}
index = items[0].InvenIndex
})
put := func(n uint64) []byte { return appMessage(2, inventoryItem(index, 1, 8, n)) }
first := g.request("/ItemStoragePut", put(10))
response := g.execute(first, false)
stored := appRows(response, 1)
if len(stored) != 1 || appValue(stored[0], 4) != 10 || appValue(stored[0], 1) == index {
t.Fatalf("split must create destination stack with delta10: %x", response)
}
storageIndex := appValue(stored[0], 1)
if count := g.itemCount(8, 1); count != baseline+15 {
t.Fatalf("put backpack count=%d", count)
}
if again := g.execute(first, false); !bytes.Equal(again, response) {
t.Fatal("put retry changed response")
}
g.call("/ItemStoragePut", put(5))
info := g.call("/ItemStorageInfo", nil)
rows := appRows(info, 1)
if len(rows) != 1 || appValue(rows[0], 1) != storageIndex || appValue(rows[0], 4) != 15 {
t.Fatalf("storage did not merge into one stack: %x", info)
}
g.reopen()
info = g.call("/ItemStorageInfo", nil)
if rows = appRows(info, 1); len(rows) != 1 || appValue(rows[0], 4) != 15 {
t.Fatal("storage not durable")
}
// The first move succeeds inside the batch, then an invalid discard must
// roll back both sides and discard the assembly's mutated cache.
failed := g.request("/ItemStorageOut", appMessage(2, inventoryItem(storageIndex, 1, 8, 4)))
failed.Requests = append(failed.Requests, player.Request{Path: "/ItemDump", Body: append(appScalar(1, 900), appMessage(2, inventoryItem(999999, 1, 8, 1))...)})
g.execute(failed, true)
g.reopen()
if rows = appRows(g.call("/ItemStorageInfo", nil), 1); len(rows) != 1 || appValue(rows[0], 4) != 15 {
t.Fatal("failed batch changed storage")
}
if got := g.itemCount(8, 1); got != baseline+10 {
t.Fatalf("failed batch changed backpack count: %d", got)
}
out := g.request("/ItemStorageOut", appMessage(2, inventoryItem(storageIndex, 1, 8, 7)))
outReply := g.execute(out, false)
if deltas := appRows(outReply, 1); len(deltas) != 1 || appValue(deltas[0], 4) != 7 {
t.Fatal("storage out must return delta")
}
// ItemLock flag1 protects discard; a false flag is protobuf's omitted zero.
target := appValue(appRows(outReply, 1)[0], 1)
g.call("/ItemLock", appMessage(2, append(appScalar(1, target), appScalar(2, 1)...)))
g.execute(g.request("/ItemDump", appMessage(2, inventoryItem(target, 1, 8, 1))), true)
g.call("/ItemLock", appMessage(2, appScalar(1, target)))
g.call("/ItemDump", appMessage(2, inventoryItem(target, 1, 8, 2)))
g.reopen()
if got := g.itemCount(8, 1); got != baseline+15 {
t.Fatalf("count conservation after put/out/dump: %d want%d", got, baseline+15)
}
rows = appRows(g.call("/ItemStorageInfo", nil), 1)
if len(rows) != 1 || appValue(rows[0], 4) != 8 {
t.Fatal("storage remaining count mismatch")
}
if again := g.execute(out, false); !bytes.Equal(again, outReply) {
t.Fatal("out retry after reopen changed result")
}
}
func TestEquipmentStorageAndRankPurchaseUsePersistedGameRules(t *testing.T) {
g := newInventoryGameplay(t)
var equipment assets.Equipment
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
var err error
design, ok := p.design.equipmentCraft.Equipment[43010]
if !ok {
t.Fatal("rank fixture needs a craftable UR equipment")
}
generated := assets.Equipment{ID: 43010, Level: 9, Rank: []uint64{1, 1, 1}, LockFlag: 1, Mark: "Keep this"}
options := func(groups []gamedata.OptionGroup) []assets.EquipmentOption {
var values []assets.EquipmentOption
for _, group := range groups {
if len(group.Choices) == 0 {
t.Fatal("rank fixture option group has no choices")
}
values = append(values, assets.EquipmentOption{GroupID: group.ID, ID: group.Choices[0].ID})
}
return values
}
generated.MainOption = options(design.Main)
generated.SubOption = options(design.Sub)
if private := options(design.Private); len(private) != 0 {
generated.PrivateOption = &private[0]
}
equipment, err = p.ownedEquipment.GrantGeneratedOnce(ctx, "rank-test-equipment", generated)
if err != nil {
t.Fatal(err)
}
if err = p.wallet.ExchangeOnce(ctx, "rank-test-mileage", nil, []gamedata.Reward{{Type: 68, Count: 20000}}); err != nil {
t.Fatal(err)
}
})
assertMetadata := func(entry []byte, wantRank []uint64) {
t.Helper()
base := appRows(entry, 5)
mark := appRows(entry, 8)
if len(base) != 1 || len(mark) != 1 || appValue(entry, 1) != equipment.InvenIndex || appValue(entry, 4) != 1 || appValue(base[0], 1) != equipment.ID || appValue(base[0], 2) != equipment.Level || !bytes.Equal(mark[0], []byte(equipment.Mark)) || !slices.Equal(puzzleNumbers(t, base[0], 6), wantRank) {
t.Fatal("equipment metadata changed while moving or purchasing rank")
}
checkOptions := func(field int, expected []assets.EquipmentOption) {
t.Helper()
options := appRows(base[0], field)
if len(options) != len(expected) {
t.Fatal("equipment options lost")
}
for i, option := range options {
if appValue(option, 1) != expected[i].GroupID || appValue(option, 2) != expected[i].ID {
t.Fatal("equipment option identity changed")
}
}
}
checkOptions(3, equipment.MainOption)
checkOptions(4, equipment.SubOption)
var private []assets.EquipmentOption
if equipment.PrivateOption != nil {
private = append(private, *equipment.PrivateOption)
} else {
private = append(private, assets.EquipmentOption{})
}
checkOptions(5, private)
}
// InventoryPacket performs EquipClear before storing assigned equipment;
// locked equipment remains storable because storage is not destruction.
ref := inventoryEquipment(equipment.InvenIndex, equipment.ID)
put := g.request("/EquipStoragePut", ref)
putReply := g.execute(put, false)
if appValue(appRows(putReply, 1)[0], 4) != 1 {
t.Fatal("storage lost equipment lock")
}
if inventoryOwnedEquipment(t, g, equipment.InvenIndex) != nil {
t.Fatal("stored equipment stayed usable")
}
g.reopen()
stored := appRows(g.call("/EquipStorageInfo", nil), 1)
if len(stored) != 1 || appValue(stored[0], 1) != equipment.InvenIndex {
t.Fatal("equipment storage not durable")
}
assertMetadata(stored[0], []uint64{1, 1, 1})
if again := g.execute(put, false); !bytes.Equal(again, putReply) {
t.Fatal("equipment put retry changed")
}
g.call("/EquipStorageOut", ref)
entry := inventoryOwnedEquipment(t, g, equipment.InvenIndex)
if entry == nil || appValue(entry, 4) != 1 {
t.Fatal("retrieval lost lock or instance")
}
assertMetadata(entry, []uint64{1, 1, 1})
// Current GameData: product1600001/4 costs500 type68 and resolves to
// ticket1 ranks[3,3,4], the21-point ticket described by NameText8065.
request := append(appScalar(2, equipment.InvenIndex), appScalar(3, 1600001)...)
request = append(request, appScalar(4, 4)...)
request = append(request, appMessage(5, inventoryItem(0, 0, 68, 500))...)
var before uint64
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) { before = p.wallet.Snapshot(ctx).EquipMileage })
failed := g.request("/EquipRankUpgradeBuy", request)
failed.Requests = append(failed.Requests, player.Request{Path: "/ItemDump", Body: append(appScalar(1, 901), appMessage(2, inventoryItem(999999, 1, 8, 1))...)})
g.execute(failed, true)
g.reopen()
if ranks := puzzleNumbers(t, appRows(inventoryOwnedEquipment(t, g, equipment.InvenIndex), 5)[0], 6); !slices.Equal(ranks, []uint64{1, 1, 1}) {
t.Fatalf("failed purchase changed ranks:%v", ranks)
}
buy := g.request("/EquipRankUpgradeBuy", request)
reply := g.execute(buy, false)
if ranks := puzzleNumbers(t, reply, 1); !slices.Equal(ranks, []uint64{3, 3, 4}) {
t.Fatalf("rank ticket must replace full vector:%v", ranks)
}
assertMetadata(inventoryOwnedEquipment(t, g, equipment.InvenIndex), []uint64{3, 3, 4})
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
if got := p.wallet.Snapshot(ctx).EquipMileage; got != before-500 {
t.Fatalf("rank debit=%d want%d", got, before-500)
}
})
g.reopen()
assertMetadata(inventoryOwnedEquipment(t, g, equipment.InvenIndex), []uint64{3, 3, 4})
if again := g.execute(buy, false); !bytes.Equal(again, reply) {
t.Fatal("rank retry changed")
}
g.execute(g.request("/EquipRankUpgradeBuy", request), true)
counts := appRows(g.call("/CashShopPurchaseCountInfo", nil), 1)
found := false
for _, row := range counts {
if appValue(row, 1) == 1600001 && appValue(row, 2) == 4 {
found = true
if appValue(row, 4) != 1 {
t.Fatal("rank purchase count not exactly1")
}
}
}
if !found {
t.Fatal("rank purchase count missing")
}
}
func TestEquipmentConversionsCraftOneAndApplyUpgradeAndBreak(t *testing.T) {
g := newInventoryGameplay(t)
var char uint64
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
if _, err := p.collection.GrantCostumes(ctx, "crafting-character", []uint64{1401}, p.design.regularGacha); err != nil {
t.Fatal(err)
}
for _, c := range p.worldService.CharacterService().EquipmentCharacters() {
if _, ok := p.design.equipmentCraft.CharTalent[c.ID]; ok {
char = c.InvenIndex
break
}
}
if char == 0 {
t.Fatal("fixture needs crafting character")
}
rewards := []gamedata.BattleReward{{Type: 8, ID: 204, Count: 50}, {Type: 8, ID: 201, Count: 50}, {Type: 8, ID: 1, Count: 10000}}
if _, err := p.ownedItems.GrantOnce(ctx, "conversion-budget", rewards); err != nil {
t.Fatal(err)
}
if err := p.wallet.ExchangeOnce(ctx, "conversion-wallet", nil, []gamedata.Reward{{Type: 4, Count: 1000000}, {Type: 12, Count: 100}}); err != nil {
t.Fatal(err)
}
})
material := func() []byte {
t.Helper()
var out []byte
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
for _, id := range []uint64{204, 201} {
items, err := p.ownedItems.SelectMutable(ctx, 8, id, 3)
if err != nil {
t.Fatal(err)
}
for _, i := range items {
out = append(out, appMessage(4, assets.ItemWire(i))...)
}
}
})
return out
}
makeRequest := func(attempts uint64) []byte {
out := append(appScalar(2, char), appScalar(3, 1)...)
out = append(out, material()...)
out = append(out, appScalar(5, attempts)...)
out = append(out, appScalar(7, 1)...)
return append(out, appScalar(8, 3)...)
}
before := g.itemCount(8, 204)
powderBefore := g.itemCount(8, 10)
var goldBefore uint64
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) { goldBefore = p.wallet.Snapshot(ctx).Gold })
// A gold budget of1 stops upgrades before any debit; field5 is attempt
// count. Even0 attempts still makes exactly1 recipe, not0 orN crafts.
made := g.call("/EquipFromMakingToUpgrade", makeRequest(7))
equip := appRows(made, 2)
if len(equip) != 1 || appValue(made, 4) != 0 || appValue(made, 3) != 5 {
t.Fatalf("craft/upgrade budget result:%x", made)
}
index := appValue(equip[0], 1)
if index == 0 || inventoryOwnedEquipment(t, g, index) == nil {
t.Fatal("made equipment missing")
}
if got := g.itemCount(8, 204); got != before-3 {
t.Fatalf("field5 incorrectly multiplied craft material:%d", got)
}
direct := append(appScalar(2, index), appScalar(3, 1)...)
direct = append(direct, appScalar(5, 15)...)
direct = append(direct, appScalar(6, 3)...)
broke := g.call("/EquipFromUpgradeToBreak", direct)
if appValue(broke, 3) != 1 || appValue(broke, 6) != 15 || appValue(appRows(appRows(broke, 1)[0], 5)[0], 2) != 1 || len(appRows(broke, 7)) != 1 || inventoryOwnedEquipment(t, g, index) != nil {
t.Fatalf("upgrade-to-break failed to remove/reward:%x", broke)
}
if got := g.itemCount(8, 10); got != powderBefore+4 {
t.Fatalf("level1 break must grant4 refinement powder: got%d", got)
}
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
if p.wallet.Snapshot(ctx).Gold != goldBefore-15 {
t.Fatal("actual upgrade did not charge exactly15 gold")
}
})
combined := g.request("/EquipFromMakingToBreak", makeRequest(0))
combinedReply := g.execute(combined, false)
if len(appRows(combinedReply, 2)) != 1 || len(appRows(combinedReply, 8)) != 1 || appValue(combinedReply, 4) != 0 {
t.Fatalf("make/break zero-attempt contract:%x", combinedReply)
}
removed := appValue(appRows(combinedReply, 2)[0], 1)
if inventoryOwnedEquipment(t, g, removed) != nil {
t.Fatal("combined break retained equipment")
}
if got := g.itemCount(8, 204); got != before-6 {
t.Fatalf("combined material charge:%d", got)
}
g.reopen()
if got := g.itemCount(8, 10); got != powderBefore+7 {
t.Fatalf("reopened powder does not include both break rewards: got%d", got)
}
if again := g.execute(combined, false); !bytes.Equal(again, combinedReply) {
t.Fatal("combined retry after reopen changed result")
}
}
+3
View File
@@ -88,6 +88,7 @@ func (p *playerAssembly) assets(ctx command.Context) error {
return fmt.Errorf("load inventory slot state: %w", err)
}
p.inventorySlots.AttachDevelopmentSettings(p.options.devToolsConfig)
p.ownedItems.AttachCapacity(p.inventorySlots)
if err := p.login.AttachInventorySlots(p.inventorySlots); err != nil {
return fmt.Errorf("attach inventory slots to login: %w", err)
}
@@ -129,6 +130,8 @@ func (p *playerAssembly) assets(ctx command.Context) error {
if err := p.ownedEquipment.AttachSlots(ctx, p.design.equipmentSlots); err != nil {
return fmt.Errorf("attach equipment slot GameData: %w", err)
}
p.ownedEquipment.AttachCapacity(p.inventorySlots)
p.ownedItems.AttachDiscard(10, p.ownedEquipment.Discard)
if err := p.ownedEquipment.AttachUpgrade(ctx, p.design.equipmentUpgrade, p.wallet, p.ownedItems); err != nil {
return fmt.Errorf("attach equipment upgrade GameData: %w", err)
}
@@ -0,0 +1,57 @@
package app
import (
"bd2server/internal/server/domain/battle"
"bd2server/internal/server/domain/battle/pvp"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/protocol/wire"
)
func (p *playerAssembly) prepareBattle(ctx command.Context, result battle.Completion) error {
if len(result.Deck) == 0 {
return nil
}
for _, entry := range result.Deck {
character, owned := p.worldService.CharacterService().Find(ctx, entry.CharacterInvenIndex)
if !owned || roster.IsStoryCharacter(character) || roster.IsCharmCharacter(character) {
return nil
}
}
return p.deckStateStore.PrepareRecommendation(ctx, result.Identity, result.Context, result.Deck)
}
func (p *playerAssembly) completeBattle(ctx command.Context, result battle.Completion) ([]byte, error) {
partners, err := p.rosterProgressService.ApplyBattlePartners(ctx, result.Identity, result.Participants, result.Win)
if err != nil {
return nil, err
}
var response []byte
for _, partner := range partners {
response = wire.AppendBytes(response, 9, roster.PartnerWire(partner))
}
return response, p.deckStateStore.CompleteRecommendation(ctx, result.Identity, result.Win)
}
func (p *playerAssembly) completePVP(ctx command.Context, mode pvp.Mode, identity string, win bool, enteredDeck [][]byte) ([]byte, error) {
if mode != pvp.Mirror {
return nil, nil
}
var indices []uint64
for _, entry := range enteredDeck {
index, _, err := wire.Varint(entry, 1)
if err != nil {
return nil, err
}
indices = append(indices, index)
}
partners, err := p.rosterProgressService.ApplyBattlePartners(ctx, "pvp:"+identity, indices, win)
if err != nil {
return nil, err
}
var response []byte
for _, partner := range partners {
response = wire.AppendBytes(response, 3, roster.PartnerWire(partner))
}
return response, p.deckStateStore.CompleteRecommendation(ctx, "pvp:"+identity, win)
}
@@ -48,6 +48,10 @@ func (p *playerAssembly) commerce(ctx command.Context) error {
return fmt.Errorf("load cash bonus claims: %w", err)
}
p.cashService.AttachLegacyCounts(p.gachaService)
if err := p.ownedEquipment.AttachRankPurchases(p.design.equipmentRankPurchases, p.cashService.ChargeGameplayPurchase); err != nil {
return err
}
p.rosterProgressService.AttachPurchase(p.cashService.ChargeGameplayPurchase)
var cashSpecialProducts []gamedata.CashProductKey
if infinite := p.design.infiniteGacha; infinite != nil {
cashSpecialProducts = append(cashSpecialProducts, gamedata.CashProductKey{GroupID: infinite.ProductGroupID, ProductID: infinite.ProductID, SaleGroup: infinite.SaleGroup})
+3
View File
@@ -77,6 +77,9 @@ func (p *playerAssembly) events(ctx command.Context) error {
if err != nil {
return fmt.Errorf("load event action state: %w", err)
}
if p.shared != nil {
p.eventActionsService.AttachStatueHits(p.shared.statueHits)
}
if err = p.eventActionsService.AttachMiniContent(ctx, p.eventPlayService, p.design.miniContent); err != nil {
return fmt.Errorf("attach mini event content: %w", err)
}
+1
View File
@@ -83,6 +83,7 @@ type playerAssembly struct {
gachaService *gacha.Service
pictorialService *pictorial.Service
charAwakeService *roster.CharAwakeService
rosterProgressService *roster.RosterProgressService
costumePotentialService *roster.CostumePotentialService
costumeBurstService *roster.CostumeBurstService
friendshipService *roster.FriendshipService
+12
View File
@@ -10,6 +10,7 @@ import (
"bd2server/internal/server/domain/events"
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/domain/social"
"bd2server/internal/server/domain/world/todayquest"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/stateio"
@@ -19,6 +20,17 @@ import (
func (p *playerAssembly) gameplay(ctx command.Context) error {
var err error
p.battleService = battle.NewService(p.options.gameData, p.options.gameDataVersion, p.worldService.CurrentPackID)
if err := p.battleService.Restore(ctx); err != nil {
return fmt.Errorf("load battle checkpoint: %w", err)
}
p.battleService.AttachCompletion(p.completeBattle)
p.battleService.AttachPreparation(p.prepareBattle)
p.battleService.AttachAbandonment(func(ctx command.Context, identity string) error {
return p.deckStateStore.CompleteRecommendation(ctx, identity, false)
})
p.battleService.AttachExternalResume(func(ctx command.Context, mode uint64, identity string) ([]byte, error) {
return social.InitialRaidResume(ctx, p.design.guild, mode, identity)
})
freeHuntingAP, bonusHuntingAP, err := p.login.SeedHuntingAP()
if err != nil {
return fmt.Errorf("read initial hunting AP: %w", err)
+4 -2
View File
@@ -24,7 +24,7 @@ func (p *playerAssembly) multiplayerPVP(ctx command.Context) error {
if err != nil {
return err
}
public := pvp.Profile{OwnerID: ctx.AccountID, OwnerIndex: owner, Name: profile.UserID, XP: exp, PortraitCostume: profile.PortraitCostumeID, PortraitDesign: profile.PortraitDesignID, Title: profile.TitleID}
public := pvp.Profile{OwnerID: ctx.AccountID, OwnerIndex: owner, Name: profile.UserID, XP: exp, PortraitCostume: profile.PortraitCostumeID, PortraitDesign: profile.PortraitDesignID, Title: profile.TitleID, Guild: profile.GuildBase}
builder := &pvp.OwnedSnapshotBuilder{Design: p.design.pvp.Design, Characters: p.worldService.CharacterService(), Collection: p.collection, Equipment: p.ownedEquipment, OwnerIndex: owner,
Buffs: func(ctx command.Context) ([]gamedata.PictorialBuffStat, error) {
_, buffs, err := p.pictorialService.Snapshot(ctx)
@@ -56,13 +56,15 @@ func (p *playerAssembly) multiplayerPVP(ctx command.Context) error {
if err != nil {
return pvp.Profile{}, err
}
return pvp.Profile{OwnerID: ctx.AccountID, OwnerIndex: owner, Name: current.UserID, XP: xp, PortraitCostume: current.PortraitCostumeID, PortraitDesign: current.PortraitDesignID, Title: current.TitleID}, nil
return pvp.Profile{OwnerID: ctx.AccountID, OwnerIndex: owner, Name: current.UserID, XP: xp, PortraitCostume: current.PortraitCostumeID, PortraitDesign: current.PortraitDesignID, Title: current.TitleID, Guild: current.GuildBase}, nil
}); err != nil {
return err
}
if err = p.login.AttachColosseumSlots(p.pvpService); err != nil {
return err
}
p.pvpService.AttachCompletion(p.completePVP)
p.pvpService.AttachPreparation(p.preparePVPRecommendation)
return p.login.AttachAdditionalCurrencies(pvpLoginCurrencies{p})
}
@@ -0,0 +1,151 @@
package app
import (
"bd2server/internal/server/domain/battle/pvp"
"bd2server/internal/server/domain/command"
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/domain/roster/deck"
"bd2server/internal/server/protocol/ownership"
"bd2server/internal/server/protocol/wire"
"encoding/binary"
"fmt"
"math"
)
func (p *playerAssembly) preparePVPRecommendation(ctx command.Context, mode pvp.Mode, identity string, snapshot pvp.PublishedSnapshot, request []byte) error {
if mode != pvp.Mirror {
return nil
}
var scenario deck.RecommendContext
found := false
err := wire.Walk(request, func(f wire.Field) error {
if f.Number != 103 {
return nil
}
if f.Type != 2 || found {
return fmt.Errorf("pvp: invalid recommendation context")
}
found = true
fields := map[int]*uint64{2: &scenario.BattleMode, 3: &scenario.PackID, 4: &scenario.BattleIndex, 5: &scenario.Level, 6: &scenario.TeamCountType, 7: &scenario.DeckType}
seen := map[int]bool{}
return wire.Walk(f.Value, func(field wire.Field) error {
target := fields[field.Number]
if target == nil {
return nil
}
if field.Type != 0 || seen[field.Number] {
return fmt.Errorf("pvp: invalid recommendation context field")
}
seen[field.Number] = true
value, _ := binary.Uvarint(field.Value)
if value > math.MaxInt32 {
return fmt.Errorf("pvp: recommendation context outside protocol range")
}
*target = value
return nil
})
})
if err != nil || !found {
return err
}
if scenario.BattleMode != 6 || scenario.Level != 0 || scenario.TeamCountType != 0 || scenario.DeckType != 0 {
return fmt.Errorf("pvp: invalid offense recommendation context")
}
r := deck.RecommendRecord{Context: scenario, Identity: deck.RecommendIdentity{OwnerIndex: snapshot.Profile.OwnerIndex, UserID: snapshot.Profile.Name, UserExp: snapshot.Profile.XP, PortraitCostumeID: snapshot.Profile.PortraitCostume, PortraitDesignID: snapshot.Profile.PortraitDesign, TitleID: snapshot.Profile.Title, GuildBase: append([]byte(nil), snapshot.Profile.Guild...)}, Awake: map[uint64]roster.CharAwakeProgress{}}
err = wire.Walk(snapshot.Snapshot.FullDeck, func(f wire.Field) error {
if f.Number < 1 || f.Number > 6 || f.Number == 5 {
return nil
}
if f.Type != 2 {
return fmt.Errorf("pvp: invalid frozen recommendation row")
}
switch f.Number {
case 1:
var entry deck.DeckEntry
entry.CharacterInvenIndex, _, err = wire.Varint(f.Value, 1)
if err != nil {
return err
}
entry.CostumeInvenIndex, _, err = wire.Varint(f.Value, 2)
if err != nil {
return err
}
entry.Slot, _, err = wire.Varint(f.Value, 3)
r.Deck = append(r.Deck, entry)
case 2:
value, e := ownership.DecodeCharacter(f.Value)
if e != nil {
return e
}
character := roster.Character{InvenIndex: value.InvenIndex, ID: value.ID, HP: value.HP, Level: value.Level, CostumeID: value.CostumeID, Exp: value.Exp, UseCostume: value.UseCostume, TalentLevel: value.TalentLevel, TalentExp: value.TalentExp, SolidarityReward: value.SolidarityReward, ExpiryTime: value.ExpiryTime, ConnectPotentialCostume: value.ConnectPotentialCostume}
for _, book := range value.Pictorialbook {
character.Pictorialbook = append(character.Pictorialbook, roster.Pictorial{ID: book.ID, GroupID: book.GroupID})
}
r.Characters = append(r.Characters, character)
case 3:
value, e := ownership.DecodeCostume(f.Value)
if e != nil {
return e
}
costume := roster.Costume{InvenIndex: value.InvenIndex, ID: value.ID, Level: value.Level, UseChar: value.UseChar, SortID: value.SortID, PotentialLockIDs: value.PotentialLockIDs, PotentialIDs: value.PotentialIDs, DesignID: value.DesignID, BurstLevel: value.BurstLevel, TimeValue: value.TimeValue}
for _, book := range value.Pictorialbook {
costume.Pictorialbook = append(costume.Pictorialbook, roster.Pictorial{ID: book.ID, GroupID: book.GroupID})
}
r.Costumes = append(r.Costumes, deck.RecommendCostume{Costume: costume, Potential: append([]uint64(nil), value.PotentialIDs...), Locked: append([]uint64(nil), value.PotentialLockIDs...)})
case 4:
value, e := ownership.DecodeEquipment(f.Value)
if e != nil {
return e
}
equipment := assets.Equipment{InvenIndex: value.InvenIndex, ID: value.ID, Level: value.Level, UseChar: value.UseChar, KeepFlag: value.KeepFlag, LockFlag: value.LockFlag, SortID: value.SortID, Mark: value.Mark, Rank: value.Rank}
for _, option := range value.MainOption {
equipment.MainOption = append(equipment.MainOption, assets.EquipmentOption(option))
}
for _, option := range value.SubOption {
equipment.SubOption = append(equipment.SubOption, assets.EquipmentOption(option))
}
if value.PrivateOption != nil {
option := assets.EquipmentOption(*value.PrivateOption)
equipment.PrivateOption = &option
}
r.Equipment = append(r.Equipment, equipment)
case 6:
unique, _, e := wire.Varint(f.Value, 1)
if e != nil {
return e
}
var awake roster.CharAwakeProgress
for i := range awake.ImprintLevels {
awake.ImprintLevels[i], _, e = wire.Varint(f.Value, i+2)
if e != nil {
return e
}
}
enabled, _, e := wire.Varint(f.Value, 5)
if e != nil || enabled > 1 {
return fmt.Errorf("pvp: invalid frozen awake state")
}
awake.IsAwake = enabled == 1
for _, character := range r.Characters {
if p.design.costumePotentialDesign.CharacterUnique[character.ID] == unique {
r.Awake[unique] = awake
break
}
}
}
return err
})
if err != nil {
return err
}
costumes := make([]roster.Costume, 0, len(r.Costumes))
for _, costume := range r.Costumes {
costumes = append(costumes, costume.Costume)
}
r.Power, err = p.rosterProgressService.SnapshotBattlePower(r.Characters, costumes, r.Equipment, r.Awake)
if err != nil {
return err
}
return p.deckStateStore.PrepareRecommendationSnapshot(ctx, "pvp:"+identity, r)
}
+4
View File
@@ -6,6 +6,7 @@ import (
"bd2server/internal/server/domain/commerce"
"bd2server/internal/server/domain/commerce/gacha"
"bd2server/internal/server/domain/events"
"bd2server/internal/server/domain/notice"
"bd2server/internal/server/domain/profile"
"bd2server/internal/server/domain/social"
"bd2server/internal/server/gateway/session"
@@ -41,6 +42,7 @@ func (p *playerAssembly) session(ctx command.Context) error {
if err := p.multiplayerPVP(ctx); err != nil {
return err
}
p.worldService.AttachRankStatues(p.rankStatues)
if err := p.achievementObserver.SyncRecordedHistory(ctx); err != nil {
return fmt.Errorf("restore recorded achievement history: %w", err)
}
@@ -84,6 +86,7 @@ func (p *playerAssembly) session(ctx command.Context) error {
p.ownedEquipment,
p.inventorySlots,
p.charAwakeService,
p.rosterProgressService,
p.costumePotentialService,
p.costumeBurstService,
p.friendshipService,
@@ -105,6 +108,7 @@ func (p *playerAssembly) session(ctx command.Context) error {
&scheduleadapter.Service{Schedule: p.options.calendars.RegularService},
readonly.Service{Seed: p.seeds.defaults},
feature.Service{},
notice.Handler{Board: p.options.notices},
}
if p.pvpService != nil {
p.handlers = append([]session.Handler{p.pvpService}, p.handlers...)
+6
View File
@@ -34,6 +34,12 @@ func (p *playerInstance) recoverSharedBattle(ctx context.Context) (result error)
}
}()
c := command.Context{Identity: command.Identity{AccountID: p.accountID, SessionID: "recovery", RequestID: "shared-battle"}, State: tx, Cancellation: ctx}
if err := p.assembly.battleService.Restore(c); err != nil {
return err
}
if p.assembly.battleService.Active(c) {
return nil
}
published := false
c.Emit = func(event command.Event) error {
if err := outbox.Publish(tx, p.accountID, event); err != nil {
+94
View File
@@ -0,0 +1,94 @@
package app
import (
"context"
"time"
"bd2server/internal/server/domain/battle/pvp"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/world"
"bd2server/internal/server/protocol/wire"
)
func statuePlayer(kind, season, rank, owner uint64, name string, portrait, design uint64) []byte {
b := wire.AppendVarint(nil, 1, kind)
b = wire.AppendVarint(b, 2, season)
b = wire.AppendVarint(b, 3, rank)
b = wire.AppendVarint(b, 4, owner)
b = wire.AppendString(b, 5, name)
b = wire.AppendVarint(b, 6, portrait)
return wire.AppendVarint(b, 7, design)
}
func statueGroup(kind, season, rank uint64) []byte {
b := wire.AppendVarint(nil, 1, kind)
b = wire.AppendVarint(b, 2, season)
return wire.AppendVarint(b, 3, rank)
}
func (p *playerAssembly) rankStatues(ctx command.Context) ([]world.RankStatue, error) {
if p.shared == nil {
return nil, nil
}
var out []world.RankStatue
for _, mode := range []pvp.Mode{pvp.Mirror, pvp.Colosseum} {
season, rows, err := p.shared.pvp.StatueRanking(mode)
if err != nil {
return nil, err
}
if len(rows) == 0 {
continue
}
kind := uint64(1)
if mode == pvp.Colosseum {
kind = 5
}
g := statueGroup(kind, season, 0)
for _, row := range rows {
profile := row.Profile
g = wire.AppendBytes(g, 5, statuePlayer(kind, season, row.Rank, profile.OwnerIndex, profile.Name, profile.PortraitCostume, profile.PortraitDesign))
}
out = append(out, world.RankStatue{ID: kind, Season: season, Groups: [][]byte{g}})
}
var huntSeason uint64
for _, season := range monsterHuntSeasons(p.seeds.defaults) {
if season.Calculate <= uint64(time.Now().UnixMilli()) && season.ID > huntSeason {
huntSeason = season.ID
}
}
if huntSeason != 0 {
rows := p.shared.huntRanks.Top(huntSeason, 3)
if len(rows) > 0 {
g := statueGroup(3, huntSeason, 0)
for _, row := range rows {
profile := row.Profile
g = wire.AppendBytes(g, 5, statuePlayer(3, huntSeason, row.Rank, profile.Owner, profile.Name, profile.Portrait, profile.PortraitDesign))
}
out = append(out, world.RankStatue{ID: 3, Season: huntSeason, Groups: [][]byte{g}})
}
}
cancel := ctx.Cancellation
if cancel == nil {
cancel = context.Background()
}
season, rows, err := p.shared.guild.StatueRanking(cancel)
if err != nil {
return nil, err
}
if len(rows) > 0 {
statue := world.RankStatue{ID: 4, Season: season}
for _, row := range rows {
g := statueGroup(4, season, row.Rank)
base := wire.AppendVarint(nil, 1, row.Guild.ID)
base = wire.AppendString(base, 2, row.Guild.Name)
base = wire.AppendVarint(base, 3, row.Guild.Icon)
base = wire.AppendString(base, 4, row.Guild.IconColor)
g = wire.AppendBytes(g, 4, base)
for i, member := range row.Members[:min(3, len(row.Members))] {
g = wire.AppendBytes(g, 5, statuePlayer(4, season, uint64(i+1), member.OwnerIndex, member.Name, member.PortraitID, member.PortraitDesignID))
}
statue.Groups = append(statue.Groups, g)
}
out = append(out, statue)
}
return out, nil
}
@@ -16,7 +16,7 @@ import (
// pack22 FieldMonsterTable id8 has phase group1; PhaseBattleTable group1 rows
// id1/id2 use decks8/9. BattleEnter/Start/PhaseChange request fields are from
// the original generated Proto.Net classes, not the server's response writer.
func TestFailedBatchDiscardsRealBattlePhaseBeforeBattleCanRestart(t *testing.T) {
func TestFailedBatchRestoresCommittedBattlePhase(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
owner, err := factory.open(accounts[0])
if err != nil {
@@ -63,10 +63,14 @@ func TestFailedBatchDiscardsRealBattlePhaseBeforeBattleCanRestart(t *testing.T)
t.Fatal("invalid next phase start committed its preceding phase transition")
}
identity := command.Context{Identity: command.Identity{AccountID: accounts[0], SessionID: "registry-client", RequestID: "inspect-recovered-battle"}}
if owner.assembly.battleService.Active(identity) {
t.Fatal("recovered account retained uncommitted in-battle ownership")
if !owner.assembly.battleService.Active(identity) || owner.assembly.battleService.RoundCount(identity) != 1 {
t.Fatal("recovery lost the last committed battle turn")
}
if _, err := run(registryCommand(accounts[0], "invalid-before-enter", "/BattleStart", append(appScalar(1, 5), appScalar(2, 9)...))); err == nil {
t.Fatal("post-recovery battle start bypassed required enter")
t.Fatal("post-recovery battle start bypassed the rolled-back phase transition")
}
reply, err := run(registryCommand(accounts[0], "committed-phase-retry", "/BattlePhaseChange", appScalar(1, 6)))
if err != nil || len(reply.Responses) != 1 || appValue(reply.Responses[0].Body, 8) != 9 {
t.Fatalf("recovery did not preserve the pending authored second phase: %+v %v", reply, err)
}
}
@@ -7,6 +7,7 @@ import (
"bd2server/internal/server/domain/progression/missions"
"bd2server/internal/server/domain/progression/pictorial"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/domain/roster/deck"
"bd2server/internal/server/domain/world"
"bd2server/internal/server/protocol/wire"
"errors"
@@ -138,6 +139,37 @@ func (p *playerAssembly) worldRoster(ctx command.Context) error {
return err
}
p.pictorialService.PotentialContributions = p.costumePotentialService.Contributions
p.rosterProgressService, err = roster.NewRosterProgressService(p.design.rosterProgress, p.design.costumePotentialDesign, p.worldService.CharacterService(), p.collection, p.ownedItems, p.wallet)
if err != nil {
return fmt.Errorf("load roster progression: %w", err)
}
p.rosterProgressService.AttachExpiry(p.deckStateStore.ExpireCharacter)
p.ownedItems.AttachDiscard(11, p.rosterProgressService.DiscardCostume)
if err = p.deckStateStore.AttachRecommendation(func(ctx command.Context) (deck.RecommendIdentity, error) {
owner, err := p.ProfileOwner(ctx)
if err != nil {
return deck.RecommendIdentity{}, err
}
profile, err := p.PublicProfile(ctx, owner)
if err != nil {
return deck.RecommendIdentity{}, err
}
exp, err := p.missionService.AchievementExperience()
if err != nil {
return deck.RecommendIdentity{}, err
}
return deck.RecommendIdentity{OwnerIndex: owner, UserID: profile.UserID, UserExp: exp, PortraitCostumeID: profile.PortraitCostumeID, PortraitDesignID: profile.PortraitDesignID, TitleID: profile.TitleID, GuildBase: profile.GuildBase}, nil
}, func(ctx command.Context, characters []roster.Character) (uint64, error) {
return p.rosterProgressService.TeamBattlePower(ctx, characters, p.ownedEquipment.All(ctx))
}); err != nil {
return err
}
if err = p.login.AttachRecommendationOptions(p.deckStateStore); err != nil {
return err
}
if err = p.attachRecommendationCommunity(); err != nil {
return err
}
p.costumeBurstService, err = roster.NewCostumeBurstService(p.design.costumeBurstDesign, p.collection, p.ownedItems, p.wallet)
if err != nil {
return err
@@ -5,9 +5,11 @@ package app
import (
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/world/progress"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/runtime/player"
"bytes"
"context"
"encoding/base64"
"maps"
"testing"
)
@@ -78,7 +80,9 @@ func TestQuestBattleUsesItsOwnQuestDifficultyAndRewardOwner(t *testing.T) {
})
run := func(identity, path string, body []byte) []byte {
t.Helper()
reply := registryExecute(t, runtime, registryCommand(accounts[0], scenario.name+identity, path, body))
request := registryCommand(accounts[0], scenario.name+identity, path, body)
request.Identity.SessionID = scenario.name
reply := registryExecute(t, runtime, request)
return reply.Responses[0].Body
}
beforeGold := owner.assembly.wallet.Snapshot(command.Context{}).Gold
@@ -86,14 +90,16 @@ func TestQuestBattleUsesItsOwnQuestDifficultyAndRewardOwner(t *testing.T) {
invalid := append(appScalar(1, 99), appScalar(3, scenario.monster)...)
invalid = append(invalid, appScalar(4, 303)...)
invalid = append(invalid, appScalar(5, 1)...)
future, err := runtime.Submit(context.Background(), registryCommand(accounts[0], scenario.name+"wrong-monster-deck", "/BattleEnter", invalid))
invalidRequest := registryCommand(accounts[0], scenario.name+"wrong-monster-deck", "/BattleEnter", invalid)
invalidRequest.Identity.SessionID = scenario.name
future, err := runtime.Submit(context.Background(), invalidRequest)
if err != nil {
t.Fatal(err)
}
if _, err := future.Wait(context.Background()); err == nil {
t.Fatal("quest battle accepted another monster's authored deck")
}
if owner.assembly.battleService.Active(command.Context{Identity: command.Identity{SessionID: "registry-client"}}) {
if owner.assembly.battleService.Active(command.Context{Identity: command.Identity{SessionID: scenario.name}}) {
t.Fatal("rejected deck installed an active battle")
}
if owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold || !maps.Equal(appItemTotals(run("items-rejected", "/ItemInfo", appScalar(1, 100))), beforeItems) {
@@ -106,7 +112,26 @@ func TestQuestBattleUsesItsOwnQuestDifficultyAndRewardOwner(t *testing.T) {
if appValue(response, 2) != scenario.selected {
t.Fatalf("client receives wrong enemy deck: %d, want %d", appValue(response, 2), scenario.selected)
}
run("start", "/BattleStart", append(appScalar(1, 3), appScalar(2, scenario.selected)...))
blue := appScalar(3, 300)
common := append(appScalar(1, 1), appScalar(2, scenario.selected)...)
checkpoint := appMessage(1, common)
encoded := []byte(base64.StdEncoding.EncodeToString(appMessage(3, blue)))
checkpoint = append(checkpoint, appMessage(8, encoded)...)
start := append(appScalar(1, 3), appScalar(2, scenario.selected)...)
start = append(start, appMessage(100, checkpoint)...)
run("start", "/BattleStart", start)
if err := owner.Recover(context.Background()); err != nil {
t.Fatal(err)
}
resume := run("resume", "/BattleResume", appScalar(1, 101))
if appValue(resume, 5) != uint64(scenario.activeQuest) {
t.Fatal("story battle recovery lost its actual owning quest")
}
resumedStart, _, err := wire.ReplaceVarint(start, 1, 102)
if err != nil {
t.Fatal(err)
}
run("resumed-start", "/BattleStart", resumedStart)
end := append(appScalar(1, 4), appScalar(2, 1)...)
response = run("end", "/BattleEnd", end)
bundles := appRows(response, 5)
+10
View File
@@ -1,6 +1,7 @@
package app
import (
"bd2server/internal/common/release"
"bd2server/internal/common/versionconfig"
"bd2server/internal/server/resources/fetch"
"context"
@@ -33,10 +34,19 @@ func Resources(args []string) error {
if err != nil {
return err
}
compatibility, err := loadUpdateCompatibility(versions)
if err != nil {
return err
}
var pinned *release.GameResources
if compatibility.fingerprint != nil {
pinned = compatibility.fingerprint.Game
}
manifest, err := resourcefetch.Fetch(context.Background(), resourcefetch.Options{
OutputRoot: *output, Platform: *platform, BundleVersion: versions.BundleVersion,
GameDataVersion: versions.GameDataVersion,
Progress: func(message string) { slog.Info(message) },
Pinned: pinned,
})
if err != nil {
return err
@@ -0,0 +1,66 @@
//go:build integration
package app
import (
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/runtime/player"
"testing"
)
func TestAllRounderPurchaseChargesNativeMileageAndRollsBackWithBatch(t *testing.T) {
g := newInventoryGameplay(t)
var index, beforeLevel, beforeMileage uint64
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
for _, c := range p.collection.Costumes() {
rule := p.design.rosterProgress.Costumes[c.ID]
if c.Level < rule.Maximum && (index == 0 || c.InvenIndex < index) {
index = c.InvenIndex
beforeLevel = c.Level
}
}
if index == 0 {
t.Fatal("starter has no upgradable owned costume")
}
if e := p.wallet.ExchangeOnce(ctx, "all-rounder-test-mileage", nil, []gamedata.Reward{{Type: 20, Count: 4000}}); e != nil {
t.Fatal(e)
}
beforeMileage = p.wallet.Snapshot(ctx).Mileage
})
// Current product600001/23 is the monthly one-time selection upgrade; its native price is1600 mileage.
fields := append(appScalar(2, index), appScalar(3, 600001)...)
fields = append(fields, appScalar(4, 23)...)
fields = append(fields, appMessage(5, inventoryItem(0, 0, 20, 1600))...)
failed := g.request("/CostumeAllRounderUpgrade", fields)
failed.Requests = append(failed.Requests, player.Request{Path: "/ItemDump", Body: append(appScalar(1, 900), appMessage(2, inventoryItem(999999, 1, 8, 1))...)})
g.execute(failed, true)
g.reopen()
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
c, ok := p.collection.CostumeByIndex(index)
if !ok || c.Level != beforeLevel || p.wallet.Snapshot(ctx).Mileage != beforeMileage {
t.Fatal("failed batch committed costume upgrade or native mileage")
}
})
buy := g.request("/CostumeAllRounderUpgrade", fields)
g.execute(buy, false)
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
c, ok := p.collection.CostumeByIndex(index)
if !ok || c.Level != beforeLevel+1 {
t.Fatalf("all-rounder did not advance exactly one level: %+v", c)
}
if got := p.wallet.Snapshot(ctx).Mileage; got != beforeMileage-1600 {
t.Fatalf("all-rounder native charge=%d want%d", got, beforeMileage-1600)
}
})
g.reopen()
g.execute(buy, false)
g.execute(g.request("/CostumeAllRounderUpgrade", fields), true)
g.reopen()
inventorySetup(t, g, func(ctx command.Context, p *playerAssembly) {
c, _ := p.collection.CostumeByIndex(index)
if c.Level != beforeLevel+1 || p.wallet.Snapshot(ctx).Mileage != beforeMileage-1600 {
t.Fatal("replay or exhausted native monthly limit duplicated charge/upgrade")
}
})
}
+127 -1
View File
@@ -2,12 +2,16 @@ package app
import (
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/i18n"
"bd2server/internal/common/versionconfig"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/notice"
"bd2server/internal/server/gateway/auth"
"bd2server/internal/server/gateway/session"
"bd2server/internal/server/gateway/transport"
"bd2server/internal/server/platform/lifecycle"
"bd2server/internal/server/platform/textmoderation"
"bd2server/internal/server/platform/updates"
identitystore "bd2server/internal/server/storage/identity"
"context"
"crypto/rand"
@@ -19,11 +23,24 @@ import (
"os"
"os/signal"
"path/filepath"
"strings"
"sync"
"time"
)
func Serve(args []string) (serveErr error) {
defer func() { serveErr = errors.Join(serveErr, gamedata.CloseDatabaseCache()) }()
confirmation, err := startUpdatedVersion(args)
if err != nil {
return err
}
defer func() {
var restart *updates.RestartError
if serveErr != nil && confirmation != nil && !errors.As(serveErr, &restart) {
code, err := confirmation.Failed(serveErr)
serveErr = &updates.ExitError{Code: code, Err: err}
}
}()
c, err := loadConfiguration(args)
if err != nil {
return err
@@ -115,12 +132,45 @@ func Serve(args []string) (serveErr error) {
return fmt.Errorf("open administration console: %w", err)
}
defer func() { serveErr = errors.Join(serveErr, consoleStore.Close()) }()
dispatcher := transport.Bootstrap{Config: c.bootstrap}
var stopOnce sync.Once
stopForUpdate := make(chan struct{})
updater := updates.New(updates.Options{
Config: c.updates, DataDir: c.dataDir, StateDirs: []string{c.stateDirectory, filepath.Join(c.dataDir, "config")},
ServerVersion: c.versions.ServerVersion, ServeArgs: c.serveArgs, Board: c.notices, BundledChangelog: c.versions.Resolve("CHANGELOG.md"),
Shutdown: func() { stopOnce.Do(func() { close(stopForUpdate) }) },
})
console.AttachUpdates(updater)
updateContext, stopUpdates := context.WithCancel(context.Background())
defer stopUpdates()
go updater.Run(updateContext)
compatibility := c.compatibility
go confirmation.AfterHealthy(updateContext, availability.Ready)
game.Broadcast = func() []byte { return notice.Notify(c.notices.Sequence(), updater.MaintenanceStart()) }
game.LoggedIn = func(account string, language uint64) { c.notices.SetLanguage(account, i18n.FromGameLanguage(language)) }
loginsClosed := func(language uint64) string {
_, message := updater.LoginsClosed(i18n.FromGameLanguage(language))
return message
}
dispatcher := transport.Bootstrap{Config: c.bootstrap, Notices: c.notices, LoginsClosed: loginsClosed}
handler := transport.HTTP{
Dispatcher: dispatcher, Raw: game, Authentication: c.authentication,
AuthenticationHandler: authHandler, ResourcePolicy: c.publicResources,
CommerceManifest: func() any { return design.cashCatalog.Manifest() }, Availability: availability, InstanceID: instanceID, RealtimeTickets: realtimeTickets,
StoryCheckpoints: storyCheckpoints{game: game, players: registry}, Console: console.Handler(),
LoginsClosed: func() bool { return loginsClosed(0) != "" },
Releases: releaseFiles(filepath.Join(c.dataDir, "releases")),
ClientAllowed: compatibility.allowed,
UpdateFingerprint: func() []byte { return compatibility.envelope },
Compatibility: func() any {
minimum := c.versions.MinimumPlugins.ByID()
delete(minimum, "capture_environment")
return map[string]any{
"server_version": c.versions.ServerVersion, "game_version": c.versions.GameVersion,
"bundle_version": c.versions.BundleVersion, "game_data_version": c.versions.GameDataVersion,
"fingerprint": compatibility.summary(), "fingerprint_url": "/client/update-fingerprint",
"minimum_plugins": minimum, "maintenance_at": updater.MaintenanceStart(), "logins_closed": loginsClosed(0) != "",
}
},
}.Handler()
server := &http.Server{
Addr: c.listen,
@@ -152,6 +202,8 @@ func Serve(args []string) (serveErr error) {
return err
case received := <-signals:
slog.Info("BD2 server draining", "signal", received.String())
case <-stopForUpdate:
slog.Info("BD2 server draining for update")
}
availability.Drain()
drainContext, cancelDrain := context.WithTimeout(context.Background(), 60*time.Second)
@@ -167,5 +219,79 @@ func Serve(args []string) (serveErr error) {
return err
}
slog.Info("BD2 server stopped after drain")
if plan := updater.TakePlan(); plan != nil {
return &updates.RestartError{Plan: plan}
}
return nil
}
// releaseFiles serves signed manifests and content-addressed files uploaded
// independently to DATA_DIR/releases.
func releaseFiles(directory string) http.Handler {
files := http.StripPrefix("/releases/", http.FileServerFS(os.DirFS(directory)))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if err := http.NewResponseController(w).SetWriteDeadline(time.Time{}); err != nil && !errors.Is(err, http.ErrNotSupported) {
http.Error(w, "download unavailable", http.StatusServiceUnavailable)
return
}
if strings.HasSuffix(r.URL.Path, "/") {
http.NotFound(w, r)
return
}
if strings.HasPrefix(r.URL.Path, "/releases/files/") {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
} else {
w.Header().Set("Cache-Control", "no-cache")
}
files.ServeHTTP(w, r)
})
}
// startUpdatedVersion runs before configuration loads, so that a new version
// whose configuration or stores fail to open is still rolled back.
func startUpdatedVersion(args []string) (*updates.Confirmation, error) {
dataDir, versionPath := "", ""
for i := 0; i < len(args); i++ {
name, value, assigned := strings.Cut(strings.TrimLeft(args[i], "-"), "=")
if name != "data-dir" && name != "version-config" {
continue
}
if !assigned && i+1 < len(args) {
i++
value = args[i]
}
if name == "data-dir" {
dataDir = value
} else {
versionPath = value
}
}
if dataDir == "" {
executable, err := os.Executable()
if err != nil {
return nil, err
}
dataDir = filepath.Join(filepath.Dir(executable), "data")
}
dataDir, err := filepath.Abs(dataDir)
if err != nil {
return nil, err
}
var versions versionconfig.Config
if versionPath != "" {
versions, err = versionconfig.Load(versionPath)
} else {
versions, err = versionconfig.Find()
}
if err != nil {
return nil, err
}
// A container waiting for its replacement image must still stop promptly.
ctx, stop := signal.NotifyContext(context.Background(), lifecycle.ShutdownSignals()...)
defer stop()
confirmation, code, err := updates.Startup(ctx, dataDir, versions.ServerVersion)
if err != nil {
return nil, &updates.ExitError{Code: code, Err: err}
}
return confirmation, nil
}
@@ -569,7 +569,7 @@ func (g *guildGameplay) ownedPVPDeck() ([]byte, uint64) {
}
for _, costume := range g.owner.assembly.collection.Costumes() {
if costume.UseChar == char.InvenIndex {
return append(appScalar(1, char.InvenIndex), appScalar(4, costume.InvenIndex)...), char.InvenIndex
return append(append(appScalar(1, char.InvenIndex), appScalar(3, 1)...), appScalar(4, costume.InvenIndex)...), char.InvenIndex
}
}
}
@@ -604,12 +604,55 @@ func TestNativePVPGameplayUsesOwnedSnapshotsAndTickets(t *testing.T) {
if got := appValue(login[0], 16); got != factory.design.pvp.Design.FreeMirrorTickets {
t.Fatalf("free mirror ticket initial grant=%d", got)
}
attackDeck, character := attacker.ownedPVPDeck()
var character, frozenCostume, liveCostume uint64
var frozenEquipment assets.Equipment
inventorySetup(t, &puzzleGameplay{t: t, factory: factory, account: attacker.account, owner: attacker.owner}, func(ctx command.Context, p *playerAssembly) {
if _, err := p.collection.GrantCostumes(ctx, "pvp-recommendation-costumes", []uint64{101, 102}, p.design.regularGacha); err != nil {
t.Fatal(err)
}
for _, costume := range p.collection.Costumes() {
if costume.ID == 101 {
character, frozenCostume = costume.UseChar, costume.InvenIndex
}
if costume.ID == 102 {
liveCostume = costume.InvenIndex
}
}
design := p.design.equipmentCraft.Equipment[43010]
options := func(groups []gamedata.OptionGroup) []assets.EquipmentOption {
var result []assets.EquipmentOption
for _, group := range groups {
if len(group.Choices) == 0 {
t.Fatal("PVP weapon option missing")
}
result = append(result, assets.EquipmentOption{GroupID: group.ID, ID: group.Choices[0].ID})
}
return result
}
equipment := assets.Equipment{ID: 43010, Level: 1, UseChar: character, Rank: []uint64{1, 1, 1}, MainOption: options(design.Main), SubOption: options(design.Sub)}
if private := options(design.Private); len(private) != 0 {
equipment.PrivateOption = &private[0]
}
var err error
frozenEquipment, err = p.ownedEquipment.GrantGeneratedOnce(ctx, "pvp-recommendation-weapon", equipment)
if err != nil {
t.Fatal(err)
}
})
attacker.close()
attacker.open()
attackDeck := append(append(appScalar(1, character), appScalar(3, 1)...), appScalar(4, frozenCostume)...)
defenseDeck, _ := defender.ownedPVPDeck()
attacker.pvpCall("/PvpBattleDeckSave", append(appScalar(2, 0), appMessage(3, attackDeck)...))
defender.pvpCall("/PvpBattleDeckSave", append(appScalar(2, 1), appMessage(3, defenseDeck)...))
defender.drainPVP()
mirror := attacker.pvpCall("/PvpBattleMatching", appScalar(2, 1))
attacker.pvpCall("/CostumeUse", appMessage(2, append(appScalar(1, liveCostume), appScalar(2, character)...)))
attacker.pvpCall("/EquipClear", append(appScalar(2, frozenEquipment.InvenIndex), appScalar(3, character)...))
recommendationQuery := append(append(appScalar(2, 6), appScalar(3, 1)...), appScalar(4, 37)...)
mirror := attacker.pvpCall("/PvpBattleMatching", append(appScalar(2, 1), appMessage(103, recommendationQuery)...))
if len(appRows(defender.pvpCall("/RecommendDeckInfo", recommendationQuery), 1)) != 0 {
t.Fatal("PVP matching published before a win")
}
opponent, err := factory.profiles.GameIdentity(context.Background(), defender.account)
if err != nil {
t.Fatal(err)
@@ -617,8 +660,26 @@ func TestNativePVPGameplayUsesOwnedSnapshotsAndTickets(t *testing.T) {
if appValue(mirror, 4) != uint64(opponent.OwnerIndex) {
t.Fatal("matching did not use the other account's published defense")
}
attacker.pvpCall("/PvpBattleStart", nil)
attacker.pvpCall("/PvpBattleEnd", append(appScalar(2, 1), appScalar(3, character)...))
attacker.drainPVP()
recommendationResponse := defender.pvpCall("/RecommendDeckInfo", recommendationQuery)
recommendationRows := appRows(recommendationResponse, 1)
if len(recommendationRows) != 1 {
t.Fatalf("PVP winner missing from exact ready recommendation context: %x", recommendationRows)
}
_, recommendation := recommendationBaseFromResponse(t, recommendationResponse)
frozenCharacters, frozenEquips := appRows(recommendation, 4), appRows(recommendation, 6)
if len(frozenCharacters) != 1 || appValue(frozenCharacters[0], 7) != frozenCostume || appValue(frozenCharacters[0], 7) == liveCostume {
t.Fatal("PVP recommendation used live outfit instead of saved attack outfit")
}
if len(frozenEquips) != 1 || appValue(frozenEquips[0], 1) != frozenEquipment.InvenIndex || appValue(frozenEquips[0], 2) != character {
t.Fatal("PVP recommendation lost saved equipment after live unequip")
}
// EquipmentGrowth43/1=569 plus rank43 first values 34,67,101; two +0 costumes and one level1 character add 510.
if appValue(recommendation, 1) != 1281 {
t.Fatalf("PVP frozen power=%d want1281", appValue(recommendation, 1))
}
login = appRows(attacker.pvpCall("/LoginUser", nil), 1)
if got, want := appValue(login[0], 16), factory.design.pvp.Design.FreeMirrorTickets-factory.design.pvp.Design.Mirror.TicketCost; got != want {
t.Fatalf("mirror battle ticket debit=%d want %d", got, want)
@@ -0,0 +1,145 @@
package app
import (
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/roster/deck"
"bd2server/internal/server/storage/outbox"
"bd2server/internal/server/storage/shared"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
)
type recommendationVisibility struct {
Revision uint64
Public bool
}
type sharedRecommendation struct {
Source string
Record deck.RecommendRecord
}
func recommendationPrefix(c deck.RecommendContext) string {
return fmt.Sprintf("%010d:%010d:%010d:%010d:%010d:%010d:", c.BattleMode, c.PackID, c.BattleIndex, c.Level, c.TeamCountType, c.DeckType)
}
func recommendationSource(source string) string {
return fmt.Sprintf("%x", sha256.Sum256([]byte(source)))
}
func (s *sharedRuntime) consumeRecommendation(ctx context.Context, event outbox.Pending) error {
if event.Envelope.Event.Topic != deck.RecommendationTopic {
return fmt.Errorf("invalid recommendation topic")
}
var update deck.RecommendationPublication
if json.Unmarshal(event.Envelope.Event.Payload, &update) != nil || update.Revision == 0 {
return fmt.Errorf("invalid recommendation publication")
}
if update.Record != nil {
if !update.Public || update.Record.Revision != update.Revision {
return fmt.Errorf("invalid recommendation snapshot revision")
}
if e := update.Record.Validate(); e != nil {
return e
}
}
return s.store.Consume(ctx, event, func(tx *shared.Tx, envelope outbox.Envelope) error {
source := recommendationSource(envelope.Source)
raw, found, e := tx.Get("recommendation_visibility", source)
if e != nil {
return e
}
var previous recommendationVisibility
if found && json.Unmarshal(raw, &previous) != nil {
return fmt.Errorf("invalid recommendation visibility")
}
if update.Revision > previous.Revision {
raw, e = json.Marshal(recommendationVisibility{Revision: update.Revision, Public: update.Public})
if e != nil {
return e
}
if e = tx.Put("recommendation_visibility", source, raw); e != nil {
return e
}
}
if update.Record == nil {
return nil
}
ownerKey := fmt.Sprintf("%020d", update.Record.Identity.OwnerIndex)
assigned, exists, e := tx.Get("recommendation_owners", ownerKey)
if e != nil {
return e
}
if exists && string(assigned) != source {
return fmt.Errorf("recommendation owner source conflict")
}
if !exists {
if e = tx.Put("recommendation_owners", ownerKey, []byte(source)); e != nil {
return e
}
}
key := recommendationPrefix(update.Record.Context) + ownerKey + ":" + source
raw, found, e = tx.Get("recommendations", key)
if e != nil {
return e
}
if found {
var previous sharedRecommendation
if json.Unmarshal(raw, &previous) != nil || previous.Source != source {
return fmt.Errorf("invalid shared recommendation")
}
if previous.Record.Revision >= update.Revision {
return nil
}
}
raw, e = json.Marshal(sharedRecommendation{Source: source, Record: *update.Record})
if e != nil {
return e
}
return tx.Put("recommendations", key, raw)
})
}
func (s *sharedRuntime) queryRecommendations(ctx command.Context, scenario deck.RecommendContext) ([]deck.RecommendRecord, error) {
cancel := ctx.Cancellation
if cancel == nil {
cancel = context.Background()
}
var records []deck.RecommendRecord
e := s.store.View(cancel, func(tx *shared.Tx) error {
prefix := recommendationPrefix(scenario)
cursor := ""
for {
rows, e := tx.Scan("recommendations", prefix, cursor, 256)
if e != nil {
return e
}
if len(rows) == 0 {
return nil
}
for _, row := range rows {
cursor = row.Key
var value sharedRecommendation
if json.Unmarshal(row.Value, &value) != nil || value.Record.Context != scenario {
return fmt.Errorf("invalid shared recommendation record")
}
raw, found, e := tx.Get("recommendation_visibility", value.Source)
if e != nil {
return e
}
var visibility recommendationVisibility
if !found || json.Unmarshal(raw, &visibility) != nil {
return fmt.Errorf("missing recommendation visibility")
}
if visibility.Public {
records = append(records, value.Record)
}
}
}
})
return records, e
}
func (p *playerAssembly) attachRecommendationCommunity() error {
if p.shared == nil {
return nil
}
return p.deckStateStore.AttachRecommendationCommunity(p.shared.queryRecommendations, p.design.costumePotentialDesign.CharacterUnique)
}
Loaded 100 of 205 files, more files were not shown because too many files have changed in this diff. Show more