feat(server): add built-in web console and generic configuration API
Serve an /admin/ console with game-account sign-in, owner and member roles, single-use owner links, schema-driven configuration editing, direct mail and inventory overrides. Turn common/config into documents with schemas, located problems, advice, locks and revision-checked atomic writes; migrate game, authentication, resources and dev-tools settings onto it, default them to DATA_DIR/config and expose them through configapi. Port the direct-mail item catalog to Go, write mail through the spool reader's own validation and document the console.
This commit is contained in:
1 parent
a35f949391
commit
c6250e62af
36 files changed
+4529
-292
No files matched your search
@@ -0,0 +1,34 @@
|
||||
# 网页管理台
|
||||
|
||||
服务端自带网页管理台,与游戏共用同一个监听地址,路径为 `/admin/`。例如单人本地服默认是 `http://127.0.0.1:8080/admin/`,联机服是 `<public_url>/admin/`。反向代理按原样转发 `/admin/` 即可,不需要额外端口。
|
||||
|
||||
## 登录与权限
|
||||
|
||||
- **服主**:可以修改服务器配置、管理玩家与成员权限,并给任何玩家寄件或调整背包。
|
||||
- **成员**:只能给自己的游戏账号寄件、调整自己的背包,看不到其他玩家和服务器配置。
|
||||
|
||||
OAuth 联机服使用与游戏相同的 Discord 或 Google 登录。第一个注册的游戏账号(游戏的管理员账号)就是服主。其他玩家登录前需要服主在“玩家”页打开“管理台成员”;撤销后对方会立即退出管理台。在管理台登录不会影响游戏内的登录状态。
|
||||
|
||||
服务端每次启动都会在日志中打印一条一次性服主登录链接,24 小时内有效,打开后即以服主身份登录。单人本地服没有 OAuth,需要用这条链接进入。联机服的服主账号无法登录时,也可以用它进入。能读取服务端日志的人就能拿到这条链接,因此要像对待服务器本身一样保护日志。
|
||||
|
||||
登录会话保存在 `data/state/admin.db`,服务端重启后不需要重新登录。
|
||||
|
||||
## 邮件发放与背包
|
||||
|
||||
物品目录直接读取当前版本的 GameData,只列出能通过邮件直接领取的物品和货币。内容固定的随机箱会换成箱内的实际物品,输入的数量就是玩家最终得到的数量。数量支持 `5k`、`2w`、`3万` 这类简写。
|
||||
|
||||
寄出的邮件写入邮件队列(默认 `data/mail-grants-spool.json`,可用 `--mail-grant-spool` 修改),玩家刷新游戏邮箱即可领取,不需要重启服务端。
|
||||
|
||||
“无限背包容量”写入 `data/dev-tools.json`(可用 `--dev-tools-config` 修改),玩家重新登录游戏后生效;关闭后恢复玩家原有的容量。
|
||||
|
||||
## 服务器配置
|
||||
|
||||
“服务器配置”页直接编辑服务端正在使用的 `game.json`、`authentication.json` 和 `resources.json`,字段含义与 [游戏规则配置](GAME_CONFIGURATION.md)、[认证配置](AUTHENTICATION.md)、[资源配置](RESOURCES.md) 一致。
|
||||
|
||||
- 编辑时实时校验,使用的规则与服务端启动时完全相同;有错误的配置无法保存。
|
||||
- 保存是整文件原子替换。如果文件在你编辑期间被其他人或其他程序修改,保存会被拒绝,可以选择载入最新版本。
|
||||
- 配置在**重启服务端后生效**。保存后页面会一直标记“等待重启生效”,直到服务端以新配置重新启动。
|
||||
- 首次初始化后已经永久保存的起始章节会显示为锁定,不能修改。
|
||||
- 引用的环境变量(OAuth 密钥、审核接口密钥)在当前服务端进程中未设置,或者引用的文件(词库、TLS 证书)读取不到时,页面会给出提醒。密钥本身只能通过环境变量提供,不会写入配置文件,也不会在页面中显示。
|
||||
- 服务端对配置文件没有写权限时(例如部署方以只读方式挂载),页面只能查看,不能修改。需要锁定某份配置时,以只读方式提供即可。
|
||||
- 如果文件在管理台之外被改成了服务端无法加载的内容,页面会指出问题。修正后保存,就能避免下次重启失败。
|
||||
+1
-1
@@ -136,7 +136,7 @@ master key 必须长期稳定:
|
||||
|
||||
## 5. 编辑服务器配置
|
||||
|
||||
首次运行时会在 `bd2server` 可执行文件旁生成 `local` 模式的默认配置。开发入口使用 `.build/config/authentication.json`;Docker 镜像默认使用 `/app/data/config/authentication.json`。启用 OAuth 前编辑生成的文件并配置环境变量,然后重启。Discord 和 Google 都启用时:
|
||||
首次运行时会在数据目录的 `config/authentication.json` 生成 `local` 模式的默认配置(默认数据目录为 `bd2server` 旁的 `data/`)。开发入口使用 `.build/config/authentication.json`;Docker 镜像使用 `/app/data/config/authentication.json`。启用 OAuth 前编辑生成的文件(或在 [网页管理台](ADMIN_CONSOLE.md) 中修改)并配置环境变量,然后重启。Discord 和 Google 都启用时:
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
+1
-1
@@ -25,4 +25,4 @@ RUN mkdir -p /app/data && chown 10001:10001 /app/data
|
||||
USER 10001:10001
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/app/bd2server"]
|
||||
CMD ["serve", "--listen", "0.0.0.0:8080", "--data-dir", "/app/data", "--authentication-config", "/app/data/config/authentication.json", "--resource-config", "/app/data/config/resources.json", "--game-config", "/app/data/config/game.json"]
|
||||
CMD ["serve", "--listen", "0.0.0.0:8080", "--data-dir", "/app/data"]
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
`game.json` 是服务端统一的游戏规则配置入口。后续可配置的游戏规则在此按功能分组扩展;认证、资源源、版本清单仍分别使用现有配置文件。
|
||||
|
||||
发布包不包含 `game.json`,首次运行时在 `bd2server.exe`(Linux/macOS 为 `bd2server`)旁生成默认文件。开发入口在 `.build/config/game.json` 生成并读取配置。已有文件不会覆盖,可修改的规则在重启后生效,起始章节只在首次初始化时选择。客户端无需配置此文件。
|
||||
发布包不包含 `game.json`,首次运行时在数据目录的 `config/game.json` 生成默认文件(默认数据目录为 `bd2server.exe` 旁的 `data/`,Linux/macOS 为 `bd2server` 旁)。也可以在 [网页管理台](ADMIN_CONSOLE.md) 中可视化编辑。开发入口在 `.build/config/game.json` 生成并读取配置。已有文件不会覆盖,可修改的规则在重启后生效,起始章节只在首次初始化时选择。客户端无需配置此文件。
|
||||
|
||||
默认内容:
|
||||
|
||||
@@ -243,4 +243,4 @@ Azure 使用资源根地址,自动调用 `2024-09-01` 版 Analyze Text API,
|
||||
|
||||
`schema_version` 当前必须为 `1`。字段拼写错误、未知字段、错误类型(例如字符串 `"true"`)、`null`、格式错误或文件末尾多出的 JSON 都会使服务端拒绝启动,并在错误中给出文件路径。省略 `gacha` 或此布尔开关时使用 `false`。
|
||||
|
||||
缺少文件时服务端会生成默认配置;已有文件保留,格式错误会明确报错。升级时保留服主修改过的配置,新增默认字段可参考本指南。Docker 镜像的默认命令在可写数据目录 `/app/data/config/` 生成和读取三个配置;自定义命令或只读挂载时通过 `--game-config` 指定路径,重启后生效。
|
||||
缺少文件时服务端会生成默认配置;已有文件保留,格式错误会明确报错。升级时保留服主修改过的配置,新增默认字段可参考本指南。Docker 镜像的数据目录为 `/app/data`,因此在 `/app/data/config/` 生成和读取三个配置;需要放在别处时通过 `--game-config`、`--authentication-config`、`--resource-config` 指定路径。以只读方式挂载的配置在网页管理台中只能查看。
|
||||
@@ -76,7 +76,9 @@ BD2 Launcher 是使用 Wails 的独立桌面游戏启动器。Windows 使用系
|
||||
|
||||
服主部署、创建 OAuth 应用、取得 client ID/secret、配置回调地址等完整步骤见 [服主配置指南](AUTHENTICATION.md)。
|
||||
|
||||
`authentication.json`、`resources.json` 和 `game.json` 不随发布包分发,首次运行时在服务端可执行文件旁生成默认文件,已有文件不会覆盖。开发入口使用 `.build/config/` 中的三个配置。游戏规则修改后重启生效,详细见 [服务端游戏规则配置](GAME_CONFIGURATION.md)。
|
||||
`authentication.json`、`resources.json` 和 `game.json` 不随发布包分发,首次运行时在数据目录的 `config/` 下生成默认文件(默认为 `bd2server.exe` 旁的 `data/config/`),已有文件不会覆盖。开发入口使用 `.build/config/` 中的三个配置。配置修改后重启生效,详细见 [服务端游戏规则配置](GAME_CONFIGURATION.md)。
|
||||
|
||||
服务端自带网页管理台,地址为 `<服务器地址>/admin/`,可以可视化修改上述配置、给玩家寄送物品和调整背包容量,详细见 [网页管理台](ADMIN_CONSOLE.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`。
|
||||
|
||||
|
||||
@@ -96,10 +96,25 @@ func Ensure[T any](path string, defaults T, options WriteOptions) error {
|
||||
}
|
||||
|
||||
func stage[T any](path string, value T, options WriteOptions) (string, error) {
|
||||
raw, err := json.MarshalIndent(value, "", " ")
|
||||
raw, err := encode(value)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return stageBytes(path, raw, options)
|
||||
}
|
||||
|
||||
// WriteFile atomically replaces path with raw. The file is created with mode
|
||||
// 0600 and its directory with 0755 when missing.
|
||||
func WriteFile(path string, raw []byte) error {
|
||||
temporary, err := stageBytes(path, raw, WriteOptions{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = os.Remove(temporary) }()
|
||||
return replaceFile(temporary, path)
|
||||
}
|
||||
|
||||
func stageBytes(path string, raw []byte, options WriteOptions) (string, error) {
|
||||
if options.FileMode == 0 {
|
||||
options.FileMode = 0o600
|
||||
}
|
||||
@@ -114,7 +129,7 @@ func stage[T any](path string, value T, options WriteOptions) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
if err = file.Chmod(options.FileMode); err == nil {
|
||||
_, err = file.Write(append(raw, '\n'))
|
||||
_, err = file.Write(raw)
|
||||
}
|
||||
if err == nil {
|
||||
err = file.Sync()
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
// Package configapi exposes a config.Registry as a small JSON HTTP API. It
|
||||
// knows nothing about the documents it serves; authentication, authorization
|
||||
// and CSRF protection belong to the caller that mounts the handler.
|
||||
package configapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
const maxDocumentBytes = 1 << 20
|
||||
|
||||
type Options struct {
|
||||
// Changed is called after a document was written successfully.
|
||||
Changed func(r *http.Request, view config.View)
|
||||
}
|
||||
|
||||
type document struct {
|
||||
config.Description
|
||||
View config.View `json:"view"`
|
||||
}
|
||||
|
||||
// Handler serves, relative to its mount point:
|
||||
//
|
||||
// GET / every document with its description and current view
|
||||
// GET /{name} one document
|
||||
// POST /{name}/check validate a candidate without writing it
|
||||
// PUT /{name} replace the document; If-Match carries the revision read
|
||||
func Handler(registry *config.Registry, options Options) http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
|
||||
entries := registry.Entries()
|
||||
documents := make([]document, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
item, err := describe(entry)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
documents = append(documents, item)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"documents": documents})
|
||||
})
|
||||
mux.HandleFunc("GET /{name}", func(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := lookup(w, registry, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
item, err := describe(entry)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, item)
|
||||
})
|
||||
mux.HandleFunc("POST /{name}/check", func(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := lookup(w, registry, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
raw, ok := readBody(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
problems, advice := entry.CheckJSON(raw)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"problems": nonNil(problems), "advice": nonNil(advice)})
|
||||
})
|
||||
mux.HandleFunc("PUT /{name}", func(w http.ResponseWriter, r *http.Request) {
|
||||
entry, ok := lookup(w, registry, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
expected := config.Revision(r.Header.Get("If-Match"))
|
||||
if expected == "" {
|
||||
writeJSON(w, http.StatusPreconditionRequired, map[string]string{"error": "If-Match revision required"})
|
||||
return
|
||||
}
|
||||
raw, ok := readBody(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
view, err := entry.ReplaceJSON(raw, expected)
|
||||
var problems config.Problems
|
||||
switch {
|
||||
case err == nil:
|
||||
if options.Changed != nil {
|
||||
options.Changed(r, view)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, view)
|
||||
case errors.Is(err, config.ErrConflict):
|
||||
current, viewErr := entry.View()
|
||||
if viewErr != nil {
|
||||
writeError(w, http.StatusInternalServerError, viewErr)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"error": err.Error(), "view": current})
|
||||
case errors.Is(err, config.ErrReadOnly):
|
||||
writeError(w, http.StatusForbidden, err)
|
||||
case errors.As(err, &problems):
|
||||
writeJSON(w, http.StatusUnprocessableEntity, map[string]any{"error": "invalid configuration", "problems": problems})
|
||||
default:
|
||||
writeError(w, http.StatusInternalServerError, err)
|
||||
}
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
func describe(entry config.Entry) (document, error) {
|
||||
description, err := entry.Describe()
|
||||
if err != nil {
|
||||
return document{}, err
|
||||
}
|
||||
view, err := entry.View()
|
||||
return document{Description: description, View: view}, err
|
||||
}
|
||||
|
||||
func lookup(w http.ResponseWriter, registry *config.Registry, r *http.Request) (config.Entry, bool) {
|
||||
entry, ok := registry.Lookup(r.PathValue("name"))
|
||||
if !ok {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown configuration"})
|
||||
}
|
||||
return entry, ok
|
||||
}
|
||||
|
||||
func readBody(w http.ResponseWriter, r *http.Request) ([]byte, bool) {
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, maxDocumentBytes+1))
|
||||
if err != nil || len(raw) > maxDocumentBytes {
|
||||
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "configuration body too large"})
|
||||
return nil, false
|
||||
}
|
||||
return raw, true
|
||||
}
|
||||
|
||||
func nonNil(problems config.Problems) config.Problems {
|
||||
if problems == nil {
|
||||
return config.Problems{}
|
||||
}
|
||||
return problems
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, err error) {
|
||||
writeJSON(w, status, map[string]string{"error": err.Error()})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// Document defines one kind of JSON configuration file: where it lives by
|
||||
// default, what is published when it is missing, how it is decoded and which
|
||||
// values are valid. Packages declare a Document instead of re-implementing the
|
||||
// ensure/load/validate sequence.
|
||||
type Document[T any] struct {
|
||||
// Name is the stable identifier used by generic APIs, such as "game".
|
||||
Name string
|
||||
FileName string
|
||||
// Defaults is written when the file is missing.
|
||||
Defaults func() T
|
||||
// Base is the value a file overlays while decoding. Nil means Defaults;
|
||||
// documents whose omissions must stay empty return the zero value.
|
||||
Base func() T
|
||||
Decode DecodeOptions
|
||||
Schema Schema
|
||||
// Rules adds cross-field validation after the schema's generic checks.
|
||||
Rules func(T) Problems
|
||||
// Advice reports non-blocking warnings about how a valid value would
|
||||
// behave in this process, given the document's absolute path. Startup
|
||||
// still decides; advice only lets editors warn before a restart.
|
||||
Advice func(value T, path string) Problems
|
||||
}
|
||||
|
||||
func (d Document[T]) advise(value T, path string) Problems {
|
||||
if d.Advice == nil {
|
||||
return nil
|
||||
}
|
||||
return d.Advice(value, path)
|
||||
}
|
||||
|
||||
// Validate applies the schema constraints followed by the document rules.
|
||||
func (d Document[T]) Validate(value T) error {
|
||||
problems := d.Schema.Check(value)
|
||||
if d.Rules != nil {
|
||||
problems = append(problems, d.Rules(value)...)
|
||||
}
|
||||
return problems.Err()
|
||||
}
|
||||
|
||||
// Parse decodes one complete document using the document's policies and
|
||||
// validates it. Decoding failures are reported as one document-level problem.
|
||||
func (d Document[T]) Parse(raw []byte) (T, error) {
|
||||
var zero T
|
||||
value, err := Decode(raw, d.base(), d.Decode)
|
||||
if err != nil {
|
||||
return zero, Problems{{Rule: RuleDecode, Message: err.Error()}}
|
||||
}
|
||||
if problems := d.Schema.checkPresence(raw); len(problems) != 0 {
|
||||
return zero, problems
|
||||
}
|
||||
if err := d.Validate(value); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// Load publishes defaults when path is missing, then strictly parses it.
|
||||
func (d Document[T]) Load(path string) (T, error) {
|
||||
value, _, err := d.load(path)
|
||||
return value, err
|
||||
}
|
||||
|
||||
func (d Document[T]) load(path string) (T, []byte, error) {
|
||||
var zero T
|
||||
if err := Ensure(path, d.Defaults(), WriteOptions{}); err != nil {
|
||||
return zero, nil, fmt.Errorf("%s configuration: initialize %s: %w", d.Name, path, err)
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Clean(path))
|
||||
if err != nil {
|
||||
return zero, nil, fmt.Errorf("%s configuration: load %s: %w", d.Name, path, err)
|
||||
}
|
||||
value, err := d.Parse(raw)
|
||||
if err != nil {
|
||||
return zero, nil, fmt.Errorf("%s configuration: %s: %w", d.Name, path, err)
|
||||
}
|
||||
return value, raw, nil
|
||||
}
|
||||
|
||||
// Encode renders value in the canonical on-disk representation.
|
||||
func (d Document[T]) Encode(value T) ([]byte, error) {
|
||||
return encode(value)
|
||||
}
|
||||
|
||||
// Path places the document's file in directory.
|
||||
func (d Document[T]) Path(directory string) string {
|
||||
return filepath.Join(directory, d.FileName)
|
||||
}
|
||||
|
||||
func (d Document[T]) base() T {
|
||||
if d.Base != nil {
|
||||
return d.Base()
|
||||
}
|
||||
return d.Defaults()
|
||||
}
|
||||
|
||||
// Open loads path and keeps it under management. The revision that was loaded
|
||||
// is remembered so callers can tell whether a later edit is already in effect.
|
||||
func (d Document[T]) Open(path string) (*File[T], T, error) {
|
||||
var zero T
|
||||
absolute, err := filepath.Abs(filepath.Clean(path))
|
||||
if err != nil {
|
||||
return nil, zero, fmt.Errorf("%s configuration: resolve %s: %w", d.Name, path, err)
|
||||
}
|
||||
value, raw, err := d.load(absolute)
|
||||
if err != nil {
|
||||
return nil, zero, err
|
||||
}
|
||||
return &File[T]{document: d, path: absolute, loaded: RevisionOf(raw)}, value, nil
|
||||
}
|
||||
|
||||
func encode(value any) ([]byte, error) {
|
||||
raw, err := json.MarshalIndent(value, "", " ")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append(raw, '\n'), nil
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
type sample struct {
|
||||
Mode string `json:"mode"`
|
||||
Limit int `json:"limit"`
|
||||
Tags []string `json:"tags"`
|
||||
Targets map[string]target `json:"targets"`
|
||||
}
|
||||
|
||||
type target struct {
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
}
|
||||
|
||||
var sampleMin, sampleMax = config.Range(1, 10)
|
||||
|
||||
var sampleDocument = config.Document[sample]{
|
||||
Name: "sample",
|
||||
FileName: "sample.json",
|
||||
Defaults: func() sample { return sample{Mode: "a", Limit: 1, Tags: []string{}, Targets: map[string]target{}} },
|
||||
Decode: config.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true, RejectNull: true},
|
||||
Schema: config.Schema{Sections: []config.Section{{ID: "main", Fields: []config.Field{
|
||||
{Path: "mode", Kind: config.KindString, Options: []config.Option{{Value: "a"}, {Value: "b"}}},
|
||||
{Path: "limit", Kind: config.KindInteger, Min: sampleMin, Max: sampleMax, When: &config.Condition{Path: "mode", In: []any{"b"}}},
|
||||
{Path: "tags", Kind: config.KindList, Unique: true},
|
||||
{Path: "targets", Kind: config.KindMap, Keys: []config.Option{{Value: "x"}}},
|
||||
{Path: "targets.*.enabled", Kind: config.KindBool, Required: true},
|
||||
}}}},
|
||||
Rules: func(value sample) config.Problems {
|
||||
var problems config.Problems
|
||||
if value.Mode == "b" && len(value.Tags) == 0 {
|
||||
problems.Add("tags", config.RuleRequired, "is required in mode b")
|
||||
}
|
||||
return problems
|
||||
},
|
||||
}
|
||||
|
||||
func problemPaths(t *testing.T, err error) map[string]string {
|
||||
t.Helper()
|
||||
paths := map[string]string{}
|
||||
for _, problem := range config.AsProblems(err) {
|
||||
paths[problem.Path] = problem.Rule
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
func TestDocumentLocatesSchemaAndRuleProblems(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name, raw string
|
||||
want map[string]string
|
||||
}{
|
||||
{name: "valid defaults", raw: `{"mode":"a","limit":99,"tags":[],"targets":{}}`, want: map[string]string{}},
|
||||
{name: "enum", raw: `{"mode":"c","tags":[],"targets":{}}`, want: map[string]string{"mode": config.RuleEnum}},
|
||||
{name: "range only when condition holds", raw: `{"mode":"b","limit":99,"tags":["t"],"targets":{}}`, want: map[string]string{"limit": config.RuleRange}},
|
||||
{name: "unique list item", raw: `{"mode":"a","tags":["t","t"],"targets":{}}`, want: map[string]string{"tags[1]": config.RuleUnique}},
|
||||
{name: "unsupported map key", raw: `{"mode":"a","tags":[],"targets":{"y":{"enabled":true}}}`, want: map[string]string{"targets.y": config.RuleEnum}},
|
||||
{name: "required field absent from file", raw: `{"mode":"a","tags":[],"targets":{"x":{}}}`, want: map[string]string{"targets.x.enabled": config.RuleRequired}},
|
||||
{name: "cross-field rule", raw: `{"mode":"b","limit":2,"tags":[],"targets":{}}`, want: map[string]string{"tags": config.RuleRequired}},
|
||||
{name: "decode failure", raw: `{"mode":"a","unknown":1}`, want: map[string]string{"": config.RuleDecode}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
_, err := sampleDocument.Parse([]byte(test.raw))
|
||||
got := problemPaths(t, err)
|
||||
if len(got) != len(test.want) {
|
||||
t.Fatalf("problems %v, want %v", got, test.want)
|
||||
}
|
||||
for path, rule := range test.want {
|
||||
if got[path] != rule {
|
||||
t.Fatalf("problems %v, want %v", got, test.want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileReplaceRequiresCurrentRevisionAndHonoursLocks(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "config", "sample.json")
|
||||
file, loaded, err := sampleDocument.Open(path)
|
||||
if err != nil || loaded.Mode != "a" {
|
||||
t.Fatalf("open published defaults: %+v, %v", loaded, err)
|
||||
}
|
||||
first, err := file.Read()
|
||||
if err != nil || first.Pending() || !first.Writable {
|
||||
t.Fatalf("fresh file: %+v, %v", first, err)
|
||||
}
|
||||
|
||||
next := first.Value
|
||||
next.Limit = 5
|
||||
saved, err := file.Replace(next, first.Revision)
|
||||
if err != nil || saved.Value.Limit != 5 || !saved.Pending() {
|
||||
t.Fatalf("replace: %+v, %v", saved, err)
|
||||
}
|
||||
if _, err := file.Replace(first.Value, first.Revision); !errors.Is(err, config.ErrConflict) {
|
||||
t.Fatalf("stale revision accepted: %v", err)
|
||||
}
|
||||
|
||||
file.Lock(config.Lock{Path: "mode", Value: "a", Reason: "fixed"})
|
||||
locked := saved.Value
|
||||
locked.Mode = "b"
|
||||
locked.Tags = []string{"t"}
|
||||
if _, err := file.Replace(locked, saved.Revision); problemPaths(t, err)["mode"] != config.RuleConflict {
|
||||
t.Fatalf("locked value changed: %v", err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(path, []byte(`{"mode":"zz"}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
broken, err := file.Read()
|
||||
if err != nil || problemPaths(t, broken.Problems)["mode"] != config.RuleEnum {
|
||||
t.Fatalf("externally broken file was not reported: %+v, %v", broken, err)
|
||||
}
|
||||
if _, err := file.Replace(loaded, saved.Revision); !errors.Is(err, config.ErrConflict) {
|
||||
t.Fatalf("external edit was overwritten: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrConflict means the file changed after the caller read it.
|
||||
ErrConflict = errors.New("configuration changed since it was read")
|
||||
// ErrReadOnly means the deployment does not allow this process to write the file.
|
||||
ErrReadOnly = errors.New("configuration file is read-only")
|
||||
)
|
||||
|
||||
// Revision identifies file contents. It is empty for a missing file.
|
||||
type Revision string
|
||||
|
||||
func RevisionOf(raw []byte) Revision {
|
||||
if raw == nil {
|
||||
return ""
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
return Revision(hex.EncodeToString(sum[:]))
|
||||
}
|
||||
|
||||
// Lock pins a value that the running process must not change, such as a
|
||||
// choice persisted by first initialization. Editors show Reason and Replace
|
||||
// rejects any document whose value at Path differs from Value.
|
||||
type Lock struct {
|
||||
Path string `json:"path"`
|
||||
Value any `json:"value"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// File is one managed document on disk. Writes are atomic, validated and
|
||||
// conditional on the revision the caller read, so concurrent editors and
|
||||
// manual edits cannot silently overwrite each other.
|
||||
type File[T any] struct {
|
||||
document Document[T]
|
||||
path string
|
||||
loaded Revision
|
||||
|
||||
mu sync.Mutex
|
||||
locks []Lock
|
||||
}
|
||||
|
||||
// Snapshot is the current state of a managed file.
|
||||
type Snapshot[T any] struct {
|
||||
Value T
|
||||
Revision Revision
|
||||
// Loaded is the revision this process applied at startup.
|
||||
Loaded Revision
|
||||
Writable bool
|
||||
// Problems is non-empty when the file was changed outside this process
|
||||
// into an invalid document. Value then holds the best-effort decoding.
|
||||
Problems Problems
|
||||
// Advice holds non-blocking warnings for a valid document.
|
||||
Advice Problems
|
||||
Modified time.Time
|
||||
}
|
||||
|
||||
// Pending reports whether the file differs from the revision in effect.
|
||||
func (s Snapshot[T]) Pending() bool { return s.Revision != s.Loaded }
|
||||
|
||||
func (f *File[T]) Name() string { return f.document.Name }
|
||||
func (f *File[T]) Path() string { return f.path }
|
||||
func (f *File[T]) Document() Document[T] { return f.document }
|
||||
func (f *File[T]) LoadedRevision() Revision { return f.loaded }
|
||||
|
||||
// Lock pins a value for the lifetime of this process.
|
||||
func (f *File[T]) Lock(lock Lock) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.locks = append(f.locks, lock)
|
||||
}
|
||||
|
||||
func (f *File[T]) Locks() []Lock {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return append([]Lock(nil), f.locks...)
|
||||
}
|
||||
|
||||
func (f *File[T]) Read() (Snapshot[T], error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.readLocked()
|
||||
}
|
||||
|
||||
func (f *File[T]) readLocked() (Snapshot[T], error) {
|
||||
snapshot := Snapshot[T]{Loaded: f.loaded, Writable: writable(f.path)}
|
||||
info, err := os.Stat(f.path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
snapshot.Value = f.document.Defaults()
|
||||
return snapshot, nil
|
||||
}
|
||||
if err != nil {
|
||||
return snapshot, err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return snapshot, fmt.Errorf("%s configuration: %s is not a regular file", f.document.Name, f.path)
|
||||
}
|
||||
raw, err := os.ReadFile(f.path)
|
||||
if err != nil {
|
||||
return snapshot, err
|
||||
}
|
||||
snapshot.Revision, snapshot.Modified = RevisionOf(raw), info.ModTime()
|
||||
value, err := f.document.Parse(raw)
|
||||
if err != nil {
|
||||
snapshot.Problems = AsProblems(err)
|
||||
value, _ = Decode(raw, f.document.base(), DecodeOptions{})
|
||||
} else {
|
||||
snapshot.Advice = f.document.advise(value, f.path)
|
||||
}
|
||||
snapshot.Value = value
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
// Check validates value against the document and the process locks.
|
||||
func (f *File[T]) Check(value T) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.checkLocked(value)
|
||||
}
|
||||
|
||||
func (f *File[T]) checkLocked(value T) error {
|
||||
problems := AsProblems(f.document.Validate(value))
|
||||
if len(f.locks) != 0 {
|
||||
document, err := normalize(value)
|
||||
if err != nil {
|
||||
return Problems{{Rule: RuleDecode, Message: err.Error()}}
|
||||
}
|
||||
for _, lock := range f.locks {
|
||||
found := lookup(document, lock.Path)
|
||||
if len(found) != 1 || !sameJSON(found[0].value, lock.Value) {
|
||||
problems.Add(lock.Path, RuleConflict, "is fixed to %s: %s", canonicalJSON(lock.Value), lock.Reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
return problems.Err()
|
||||
}
|
||||
|
||||
// Replace writes value when the file still has the expected revision.
|
||||
func (f *File[T]) Replace(value T, expected Revision) (Snapshot[T], error) {
|
||||
return f.Update(expected, func(current *T) error {
|
||||
*current = value
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// Update applies change to the current value and writes the result when the
|
||||
// file still has the expected revision. An empty expected revision skips the
|
||||
// revision check for read-modify-write callers that hold no prior snapshot.
|
||||
func (f *File[T]) Update(expected Revision, change func(*T) error) (Snapshot[T], error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
current, err := f.readLocked()
|
||||
if err != nil {
|
||||
return current, err
|
||||
}
|
||||
if expected != "" && current.Revision != expected {
|
||||
return current, ErrConflict
|
||||
}
|
||||
if !current.Writable {
|
||||
return current, ErrReadOnly
|
||||
}
|
||||
value := current.Value
|
||||
if err := change(&value); err != nil {
|
||||
return current, err
|
||||
}
|
||||
if err := f.checkLocked(value); err != nil {
|
||||
return current, err
|
||||
}
|
||||
raw, err := encode(value)
|
||||
if err != nil {
|
||||
return current, err
|
||||
}
|
||||
if RevisionOf(raw) != current.Revision {
|
||||
if err := WriteFile(f.path, raw); err != nil {
|
||||
return current, err
|
||||
}
|
||||
}
|
||||
return f.readLocked()
|
||||
}
|
||||
|
||||
// writable probes whether both the file and its directory accept writes,
|
||||
// which the atomic replacement requires. Read-only mounts fail either probe.
|
||||
func writable(path string) bool {
|
||||
directory := filepath.Dir(path)
|
||||
probe, err := os.CreateTemp(directory, ".config-probe-*")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
name := probe.Name()
|
||||
_ = probe.Close()
|
||||
_ = os.Remove(name)
|
||||
file, err := os.OpenFile(path, os.O_WRONLY, 0)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return true
|
||||
}
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return file.Close() == nil
|
||||
}
|
||||
|
||||
// View is the type-erased JSON form of a Snapshot for generic tools.
|
||||
type View struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
Value json.RawMessage `json:"value"`
|
||||
Revision Revision `json:"revision"`
|
||||
Loaded Revision `json:"loaded"`
|
||||
Pending bool `json:"pending"`
|
||||
Writable bool `json:"writable"`
|
||||
Problems Problems `json:"problems,omitempty"`
|
||||
Advice Problems `json:"advice,omitempty"`
|
||||
Modified *time.Time `json:"modified,omitempty"`
|
||||
Locks []Lock `json:"locks,omitempty"`
|
||||
}
|
||||
|
||||
// Description is the static information a generic editor needs.
|
||||
type Description struct {
|
||||
Name string `json:"name"`
|
||||
FileName string `json:"file_name"`
|
||||
Schema Schema `json:"schema"`
|
||||
Defaults json.RawMessage `json:"defaults"`
|
||||
}
|
||||
|
||||
// Entry is a managed document independent of its Go type.
|
||||
type Entry interface {
|
||||
Name() string
|
||||
Describe() (Description, error)
|
||||
View() (View, error)
|
||||
// CheckJSON returns blocking problems and, for a valid candidate, advice.
|
||||
CheckJSON(raw []byte) (problems, advice Problems)
|
||||
ReplaceJSON(raw []byte, expected Revision) (View, error)
|
||||
}
|
||||
|
||||
func (f *File[T]) Describe() (Description, error) {
|
||||
defaults, err := json.Marshal(f.document.Defaults())
|
||||
return Description{Name: f.document.Name, FileName: f.document.FileName, Schema: f.document.Schema, Defaults: defaults}, err
|
||||
}
|
||||
|
||||
func (f *File[T]) View() (View, error) {
|
||||
snapshot, err := f.Read()
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
return f.view(snapshot)
|
||||
}
|
||||
|
||||
func (f *File[T]) view(snapshot Snapshot[T]) (View, error) {
|
||||
value, err := json.Marshal(snapshot.Value)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
view := View{Name: f.document.Name, Path: f.path, Value: value, Revision: snapshot.Revision, Loaded: snapshot.Loaded,
|
||||
Pending: snapshot.Pending(), Writable: snapshot.Writable, Problems: snapshot.Problems, Advice: snapshot.Advice, Locks: f.Locks()}
|
||||
if !snapshot.Modified.IsZero() {
|
||||
modified := snapshot.Modified.UTC()
|
||||
view.Modified = &modified
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
func (f *File[T]) CheckJSON(raw []byte) (Problems, Problems) {
|
||||
value, err := f.document.Parse(raw)
|
||||
if err == nil {
|
||||
err = f.Check(value)
|
||||
}
|
||||
if err != nil {
|
||||
return AsProblems(err), nil
|
||||
}
|
||||
return nil, f.document.advise(value, f.path)
|
||||
}
|
||||
|
||||
func (f *File[T]) ReplaceJSON(raw []byte, expected Revision) (View, error) {
|
||||
value, err := f.document.Parse(raw)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
snapshot, err := f.Replace(value, expected)
|
||||
if err != nil {
|
||||
return View{}, err
|
||||
}
|
||||
return f.view(snapshot)
|
||||
}
|
||||
|
||||
// Registry lists managed documents in presentation order.
|
||||
type Registry struct {
|
||||
entries []Entry
|
||||
}
|
||||
|
||||
func NewRegistry(entries ...Entry) *Registry { return &Registry{entries: entries} }
|
||||
|
||||
func (r *Registry) Entries() []Entry { return append([]Entry(nil), r.entries...) }
|
||||
|
||||
func (r *Registry) Lookup(name string) (Entry, bool) {
|
||||
for _, entry := range r.entries {
|
||||
if entry.Name() == name {
|
||||
return entry, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Problem locates one rejected value inside a configuration document. Path
|
||||
// uses the schema path syntax: dot-separated JSON names, "*" for map keys and
|
||||
// "[]" for list items, with concrete keys and indexes filled in.
|
||||
type Problem struct {
|
||||
Path string `json:"path"`
|
||||
Rule string `json:"rule"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
const (
|
||||
RuleEnum = "enum"
|
||||
RuleRange = "range"
|
||||
RuleRequired = "required"
|
||||
RuleUnique = "unique"
|
||||
RuleFormat = "format"
|
||||
RuleConflict = "conflict"
|
||||
RuleDecode = "decode"
|
||||
RuleCustom = "custom"
|
||||
// RuleEnvironment marks advice about the running process rather than the
|
||||
// document, such as a referenced environment variable that is unset.
|
||||
RuleEnvironment = "environment"
|
||||
// RuleMissingFile marks advice about a referenced file that does not exist.
|
||||
RuleMissingFile = "missing_file"
|
||||
)
|
||||
|
||||
// Problems is a validation result. A non-empty value is an error so existing
|
||||
// Validate() error contracts keep working while callers that render forms can
|
||||
// recover every located problem with AsProblems.
|
||||
type Problems []Problem
|
||||
|
||||
func (p Problems) Error() string {
|
||||
parts := make([]string, len(p))
|
||||
for i, problem := range p {
|
||||
if problem.Path == "" {
|
||||
parts[i] = problem.Message
|
||||
} else {
|
||||
parts[i] = problem.Path + ": " + problem.Message
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
// Add records a problem using fmt formatting for the message.
|
||||
func (p *Problems) Add(path, rule, format string, args ...any) {
|
||||
*p = append(*p, Problem{Path: path, Rule: rule, Message: fmt.Sprintf(format, args...)})
|
||||
}
|
||||
|
||||
// Err returns nil for an empty result so functions can end with problems.Err().
|
||||
func (p Problems) Err() error {
|
||||
if len(p) == 0 {
|
||||
return nil
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Invalid reports one custom problem at path.
|
||||
func Invalid(path, format string, args ...any) error {
|
||||
var problems Problems
|
||||
problems.Add(path, RuleCustom, format, args...)
|
||||
return problems
|
||||
}
|
||||
|
||||
// AsProblems recovers located problems from err. Errors that carry no
|
||||
// location become one document-level problem.
|
||||
func AsProblems(err error) Problems {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
var problems Problems
|
||||
if errors.As(err, &problems) {
|
||||
return problems
|
||||
}
|
||||
return Problems{{Rule: RuleCustom, Message: err.Error()}}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Kind is the JSON shape of a described field.
|
||||
type Kind string
|
||||
|
||||
const (
|
||||
KindBool Kind = "bool"
|
||||
KindInteger Kind = "integer"
|
||||
KindString Kind = "string"
|
||||
KindList Kind = "list"
|
||||
KindMap Kind = "map"
|
||||
)
|
||||
|
||||
// Schema describes a document for generic editors. Generic constraints
|
||||
// (options, ranges, uniqueness and map keys) are enforced by Check, so a
|
||||
// document states each such rule once; cross-field rules remain in the
|
||||
// document's own validation function.
|
||||
type Schema struct {
|
||||
Title string `json:"title"`
|
||||
Summary string `json:"summary,omitempty"`
|
||||
Sections []Section `json:"sections"`
|
||||
}
|
||||
|
||||
type Section struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Help string `json:"help,omitempty"`
|
||||
Fields []Field `json:"fields"`
|
||||
}
|
||||
|
||||
// Field describes one value. Path uses dot-separated JSON names; "*" selects
|
||||
// every map key and "[]" every list item.
|
||||
type Field struct {
|
||||
Path string `json:"path"`
|
||||
Kind Kind `json:"kind"`
|
||||
Label string `json:"label"`
|
||||
Help string `json:"help,omitempty"`
|
||||
Placeholder string `json:"placeholder,omitempty"`
|
||||
// Format is an editor hint such as "duration", "origin", "url", "host",
|
||||
// "listen", "env", "path" or "identifier". It is not enforced generically.
|
||||
Format string `json:"format,omitempty"`
|
||||
// Options lists allowed values. For lists they constrain each item.
|
||||
Options []Option `json:"options,omitempty"`
|
||||
// OpenOptions turns Options into suggestions that do not restrict input.
|
||||
OpenOptions bool `json:"open_options,omitempty"`
|
||||
Min *int64 `json:"min,omitempty"`
|
||||
Max *int64 `json:"max,omitempty"`
|
||||
Unique bool `json:"unique,omitempty"`
|
||||
// Required means the value must be written explicitly in the file; a
|
||||
// default supplied by decoding does not satisfy it.
|
||||
Required bool `json:"required,omitempty"`
|
||||
Keys []Option `json:"keys,omitempty"`
|
||||
Advanced bool `json:"advanced,omitempty"`
|
||||
When *Condition `json:"when,omitempty"`
|
||||
}
|
||||
|
||||
type Option struct {
|
||||
Value any `json:"value"`
|
||||
Label string `json:"label"`
|
||||
Help string `json:"help,omitempty"`
|
||||
}
|
||||
|
||||
// Condition limits a field to documents whose value at Path equals one of In.
|
||||
// Paths are absolute and must not contain wildcards.
|
||||
type Condition struct {
|
||||
Path string `json:"path"`
|
||||
In []any `json:"in"`
|
||||
Not bool `json:"not,omitempty"`
|
||||
}
|
||||
|
||||
// Range returns pointers for Field.Min and Field.Max.
|
||||
func Range(minimum, maximum int64) (*int64, *int64) { return &minimum, &maximum }
|
||||
|
||||
// Fields returns every described field in declaration order.
|
||||
func (s Schema) Fields() []Field {
|
||||
var fields []Field
|
||||
for _, section := range s.Sections {
|
||||
fields = append(fields, section.Fields...)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// Check enforces the generic constraints of every applicable field.
|
||||
func (s Schema) Check(value any) Problems {
|
||||
document, err := normalize(value)
|
||||
if err != nil {
|
||||
return Problems{{Rule: RuleDecode, Message: err.Error()}}
|
||||
}
|
||||
var problems Problems
|
||||
for _, field := range s.Fields() {
|
||||
if field.When != nil && !field.When.holds(document) {
|
||||
continue
|
||||
}
|
||||
for _, found := range lookup(document, field.Path) {
|
||||
field.check(found.path, found.value, &problems)
|
||||
}
|
||||
}
|
||||
return problems
|
||||
}
|
||||
|
||||
// checkPresence reports Required fields absent from a raw document. For
|
||||
// wildcard paths every existing parent must contain the field.
|
||||
func (s Schema) checkPresence(raw []byte) Problems {
|
||||
var document any
|
||||
var problems Problems
|
||||
for _, field := range s.Fields() {
|
||||
if !field.Required {
|
||||
continue
|
||||
}
|
||||
if document == nil {
|
||||
if err := json.Unmarshal(raw, &document); err != nil {
|
||||
return Problems{{Rule: RuleDecode, Message: err.Error()}}
|
||||
}
|
||||
}
|
||||
parentPath, name := "", field.Path
|
||||
if i := strings.LastIndex(field.Path, "."); i >= 0 {
|
||||
parentPath, name = field.Path[:i], field.Path[i+1:]
|
||||
}
|
||||
parents := []located{{value: document}}
|
||||
if parentPath != "" {
|
||||
parents = lookup(document, parentPath)
|
||||
}
|
||||
for _, parent := range parents {
|
||||
if object, ok := parent.value.(map[string]any); ok {
|
||||
if _, exists := object[name]; !exists {
|
||||
problems.Add(join(parent.path, name), RuleRequired, "must be present")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return problems
|
||||
}
|
||||
|
||||
func (c Condition) holds(document any) bool {
|
||||
found := lookup(document, c.Path)
|
||||
matched := len(found) == 1 && slices.ContainsFunc(c.In, func(candidate any) bool { return sameJSON(found[0].value, candidate) })
|
||||
return matched != c.Not
|
||||
}
|
||||
|
||||
func (f Field) check(path string, value any, problems *Problems) {
|
||||
switch f.Kind {
|
||||
case KindList:
|
||||
items, ok := value.([]any)
|
||||
if !ok {
|
||||
problems.Add(path, RuleDecode, "must be a list")
|
||||
return
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for i, item := range items {
|
||||
itemPath := fmt.Sprintf("%s[%d]", path, i)
|
||||
f.checkOption(itemPath, item, problems)
|
||||
if f.Unique {
|
||||
key := canonicalJSON(item)
|
||||
if seen[key] {
|
||||
problems.Add(itemPath, RuleUnique, "duplicate value %s", key)
|
||||
}
|
||||
seen[key] = true
|
||||
}
|
||||
}
|
||||
case KindMap:
|
||||
entries, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
problems.Add(path, RuleDecode, "must be an object")
|
||||
return
|
||||
}
|
||||
if len(f.Keys) == 0 {
|
||||
return
|
||||
}
|
||||
names := make([]string, 0, len(entries))
|
||||
for name := range entries {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
if !slices.ContainsFunc(f.Keys, func(option Option) bool { return sameJSON(name, option.Value) }) {
|
||||
problems.Add(path+"."+name, RuleEnum, "unsupported key %q", name)
|
||||
}
|
||||
}
|
||||
default:
|
||||
f.checkOption(path, value, problems)
|
||||
if f.Min != nil || f.Max != nil {
|
||||
number, ok := value.(float64)
|
||||
if !ok || number != math.Trunc(number) || f.Min != nil && number < float64(*f.Min) || f.Max != nil && number > float64(*f.Max) {
|
||||
problems.Add(path, RuleRange, "must be an integer between %s and %s", bound(f.Min, "-inf"), bound(f.Max, "+inf"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f Field) checkOption(path string, value any, problems *Problems) {
|
||||
if len(f.Options) == 0 || f.OpenOptions {
|
||||
return
|
||||
}
|
||||
if slices.ContainsFunc(f.Options, func(option Option) bool { return sameJSON(value, option.Value) }) {
|
||||
return
|
||||
}
|
||||
allowed := make([]string, len(f.Options))
|
||||
for i, option := range f.Options {
|
||||
allowed[i] = canonicalJSON(option.Value)
|
||||
}
|
||||
problems.Add(path, RuleEnum, "must be one of %s", strings.Join(allowed, ", "))
|
||||
}
|
||||
|
||||
func bound(value *int64, missing string) string {
|
||||
if value == nil {
|
||||
return missing
|
||||
}
|
||||
return fmt.Sprint(*value)
|
||||
}
|
||||
|
||||
type located struct {
|
||||
path string
|
||||
value any
|
||||
}
|
||||
|
||||
// lookup expands a schema path against a normalized JSON document. Absent
|
||||
// values are omitted: optional fields are checked only when present.
|
||||
func lookup(document any, path string) []located {
|
||||
current := []located{{value: document}}
|
||||
for segment := range strings.SplitSeq(path, ".") {
|
||||
list := strings.HasSuffix(segment, "[]")
|
||||
name := strings.TrimSuffix(segment, "[]")
|
||||
var next []located
|
||||
for _, item := range current {
|
||||
object, ok := item.value.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var children []located
|
||||
if name == "*" {
|
||||
keys := make([]string, 0, len(object))
|
||||
for key := range object {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, key := range keys {
|
||||
children = append(children, located{join(item.path, key), object[key]})
|
||||
}
|
||||
} else if child, exists := object[name]; exists {
|
||||
children = append(children, located{join(item.path, name), child})
|
||||
}
|
||||
for _, child := range children {
|
||||
if !list {
|
||||
next = append(next, child)
|
||||
continue
|
||||
}
|
||||
values, ok := child.value.([]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for i, value := range values {
|
||||
next = append(next, located{fmt.Sprintf("%s[%d]", child.path, i), value})
|
||||
}
|
||||
}
|
||||
}
|
||||
current = next
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
func join(parent, name string) string {
|
||||
if parent == "" {
|
||||
return name
|
||||
}
|
||||
return parent + "." + name
|
||||
}
|
||||
|
||||
func normalize(value any) (any, error) {
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var document any
|
||||
return document, json.Unmarshal(raw, &document)
|
||||
}
|
||||
|
||||
func canonicalJSON(value any) string {
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return fmt.Sprint(value)
|
||||
}
|
||||
return string(raw)
|
||||
}
|
||||
|
||||
func sameJSON(a, b any) bool { return canonicalJSON(a) == canonicalJSON(b) }
|
||||
@@ -0,0 +1,644 @@
|
||||
// Package admin serves the server's built-in web console: configuration for
|
||||
// the owner, and mail and inventory tools for the owner and granted members.
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"log/slog"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/common/config/configapi"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/domain/mail"
|
||||
"bd2server/internal/server/gateway/auth"
|
||||
)
|
||||
|
||||
//go:embed web
|
||||
var webFiles embed.FS
|
||||
|
||||
const (
|
||||
sessionCookie = "bd2_admin"
|
||||
loginCookie = "bd2_admin_login"
|
||||
cookiePath = "/admin/"
|
||||
linkTTL = 24 * time.Hour
|
||||
)
|
||||
|
||||
// Identity is the game's OAuth service, absent in local authentication mode.
|
||||
type Identity interface {
|
||||
Providers() []string
|
||||
BeginConsoleLogin(provider, clientIP string) (auth.ConsoleLogin, error)
|
||||
FinishConsoleLogin(id, secret string) (accountID string, complete bool, err error)
|
||||
AdministratorAccountID() (string, error)
|
||||
}
|
||||
|
||||
// Player is a game account visible to console tools.
|
||||
type Player struct {
|
||||
AccountID string `json:"account_id"`
|
||||
UID string `json:"uid"`
|
||||
Name string `json:"name"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
type CapacityLimits struct {
|
||||
Default uint64 `json:"default"`
|
||||
Maximum uint64 `json:"maximum"`
|
||||
}
|
||||
|
||||
// InventoryLimits are the backpack capacities an unlimited override switches between.
|
||||
type InventoryLimits struct {
|
||||
Items CapacityLimits `json:"items"`
|
||||
Equipment CapacityLimits `json:"equipment"`
|
||||
}
|
||||
|
||||
type Options struct {
|
||||
Store *Store
|
||||
Identity Identity
|
||||
// Players lists every game account; it must include local-mode players.
|
||||
Players func(context.Context) ([]Player, error)
|
||||
Catalog func() ([]gamedata.MailCatalogItem, error)
|
||||
MailSpool string
|
||||
Inventory *commonconfig.File[inventory.DevelopmentSettings]
|
||||
Limits InventoryLimits
|
||||
// Configuration is the owner's editable document registry.
|
||||
Configuration *commonconfig.Registry
|
||||
// Server describes the running process for the owner's overview.
|
||||
Server func() any
|
||||
// Secure marks cookies Secure; set when the public origin uses HTTPS.
|
||||
Secure bool
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
type Console struct {
|
||||
options Options
|
||||
config http.Handler
|
||||
|
||||
mu sync.Mutex
|
||||
pending map[string]*pendingLogin
|
||||
links map[string]time.Time
|
||||
}
|
||||
|
||||
type pendingLogin struct {
|
||||
login auth.ConsoleLogin
|
||||
lastPoll time.Time
|
||||
}
|
||||
|
||||
func New(options Options) (*Console, error) {
|
||||
if options.Store == nil || options.Players == nil || options.Catalog == nil || options.MailSpool == "" || options.Inventory == nil || options.Configuration == nil {
|
||||
return nil, errors.New("admin: incomplete console options")
|
||||
}
|
||||
if options.Now == nil {
|
||||
options.Now = time.Now
|
||||
}
|
||||
c := &Console{options: options, pending: map[string]*pendingLogin{}, links: map[string]time.Time{}}
|
||||
c.config = configapi.Handler(options.Configuration, configapi.Options{Changed: func(r *http.Request, view commonconfig.View) {
|
||||
slog.Info("configuration saved from console", "document", view.Name, "path", view.Path, "revision", view.Revision, "pending_restart", view.Pending)
|
||||
}})
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// IssueSignInLink creates a single-use owner sign-in link below base, the
|
||||
// externally visible origin of this server. Whoever can read the server's
|
||||
// output is its operator, so the link needs no other credential.
|
||||
func (c *Console) IssueSignInLink(base string) (string, error) {
|
||||
token, err := randomToken(32)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.links[string(digest(token))] = c.options.Now().Add(linkTTL)
|
||||
c.mu.Unlock()
|
||||
return strings.TrimSuffix(base, "/") + "/admin/sign-in?token=" + url.QueryEscape(token), nil
|
||||
}
|
||||
|
||||
func (c *Console) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
static, _ := fs.Sub(webFiles, "web")
|
||||
files := http.FileServerFS(static)
|
||||
mux.HandleFunc("GET /admin", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/admin/", http.StatusMovedPermanently)
|
||||
})
|
||||
mux.Handle("GET /admin/{$}", http.StripPrefix("/admin", files))
|
||||
mux.Handle("GET /admin/assets/", http.StripPrefix("/admin", files))
|
||||
mux.HandleFunc("GET /admin/sign-in", c.signInLink)
|
||||
mux.HandleFunc("GET /admin/api/session", c.sessionInfo)
|
||||
mux.HandleFunc("POST /admin/api/login/start", c.loginStart)
|
||||
mux.HandleFunc("POST /admin/api/login/poll", c.loginPoll)
|
||||
mux.HandleFunc("POST /admin/api/logout", c.logout)
|
||||
mux.HandleFunc("GET /admin/api/catalog", c.require(RoleMember, c.catalog))
|
||||
mux.HandleFunc("GET /admin/api/players", c.require(RoleMember, c.players))
|
||||
mux.HandleFunc("PUT /admin/api/players/{account}/member", c.require(RoleOwner, c.setMember))
|
||||
mux.HandleFunc("GET /admin/api/players/{account}/inventory", c.require(RoleMember, c.inventory))
|
||||
mux.HandleFunc("PUT /admin/api/players/{account}/inventory", c.require(RoleMember, c.setInventory))
|
||||
mux.HandleFunc("POST /admin/api/players/{account}/mail", c.require(RoleMember, c.sendMail))
|
||||
mux.HandleFunc("GET /admin/api/server", c.require(RoleOwner, func(w http.ResponseWriter, r *http.Request, _ session) {
|
||||
writeJSON(w, http.StatusOK, c.options.Server())
|
||||
}))
|
||||
mux.Handle("/admin/api/config/", c.require(RoleOwner, func(w http.ResponseWriter, r *http.Request, _ session) {
|
||||
http.StripPrefix("/admin/api/config", c.config).ServeHTTP(w, r)
|
||||
}))
|
||||
return securityHeaders(mux)
|
||||
}
|
||||
|
||||
func securityHeaders(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("Referrer-Policy", "same-origin")
|
||||
h.Set("X-Frame-Options", "DENY")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type handler func(http.ResponseWriter, *http.Request, session)
|
||||
|
||||
// require authenticates the session, enforces the minimum role and, for
|
||||
// state-changing methods, the session's CSRF token.
|
||||
func (c *Console) require(minimum Role, next handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
current, ok := c.session(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if minimum == RoleOwner && current.Role != RoleOwner {
|
||||
fail(w, http.StatusForbidden, "forbidden", "owner permission required")
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodGet && r.Method != http.MethodHead {
|
||||
supplied := r.Header.Get("X-CSRF-Token")
|
||||
if !sameOrigin(r) || subtle.ConstantTimeCompare([]byte(supplied), []byte(current.CSRF)) != 1 {
|
||||
fail(w, http.StatusForbidden, "csrf", "console page expired; reload it")
|
||||
return
|
||||
}
|
||||
}
|
||||
next(w, r, current)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Console) session(w http.ResponseWriter, r *http.Request) (session, bool) {
|
||||
cookie, err := r.Cookie(sessionCookie)
|
||||
if err != nil {
|
||||
fail(w, http.StatusUnauthorized, "unauthorized", "sign in required")
|
||||
return session{}, false
|
||||
}
|
||||
current, ok, err := c.options.Store.Session(r.Context(), cookie.Value)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "session unavailable")
|
||||
return session{}, false
|
||||
}
|
||||
if !ok {
|
||||
c.clearCookie(w, sessionCookie)
|
||||
fail(w, http.StatusUnauthorized, "unauthorized", "sign in required")
|
||||
return session{}, false
|
||||
}
|
||||
return current, true
|
||||
}
|
||||
|
||||
// sameOrigin rejects browser requests that a third-party page initiated.
|
||||
func sameOrigin(r *http.Request) bool {
|
||||
site := r.Header.Get("Sec-Fetch-Site")
|
||||
return site == "" || site == "same-origin"
|
||||
}
|
||||
|
||||
func (c *Console) signInLink(w http.ResponseWriter, r *http.Request) {
|
||||
key := string(digest(r.URL.Query().Get("token")))
|
||||
c.mu.Lock()
|
||||
expires, ok := c.links[key]
|
||||
delete(c.links, key)
|
||||
c.mu.Unlock()
|
||||
if !ok || !c.options.Now().Before(expires) {
|
||||
http.Error(w, "This sign-in link is invalid, used or expired. Restart the server to print a new one.", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if err := c.startSession(w, r.Context(), "", RoleOwner); err != nil {
|
||||
http.Error(w, "session unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
slog.Info("console owner signed in with a server link")
|
||||
http.Redirect(w, r, "/admin/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (c *Console) startSession(w http.ResponseWriter, ctx context.Context, accountID string, role Role) error {
|
||||
token, _, err := c.options.Store.CreateSession(ctx, accountID, role)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: token, Path: cookiePath, MaxAge: int(sessionTTL.Seconds()), HttpOnly: true, Secure: c.options.Secure, SameSite: http.SameSiteStrictMode})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Console) clearCookie(w http.ResponseWriter, name string) {
|
||||
http.SetCookie(w, &http.Cookie{Name: name, Value: "", Path: cookiePath, MaxAge: -1, HttpOnly: true, Secure: c.options.Secure, SameSite: http.SameSiteStrictMode})
|
||||
}
|
||||
|
||||
func (c *Console) sessionInfo(w http.ResponseWriter, r *http.Request) {
|
||||
info := map[string]any{"signed_in": false, "mode": "local", "providers": []string{}}
|
||||
if c.options.Identity != nil {
|
||||
info["mode"], info["providers"] = "oauth", c.options.Identity.Providers()
|
||||
}
|
||||
if cookie, err := r.Cookie(sessionCookie); err == nil {
|
||||
current, ok, err := c.options.Store.Session(r.Context(), cookie.Value)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "session unavailable")
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
info["signed_in"], info["role"], info["csrf"] = true, current.Role, current.CSRF
|
||||
if current.AccountID != "" {
|
||||
if player, found, err := c.player(r.Context(), current.AccountID); err == nil && found {
|
||||
info["player"] = player
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, info)
|
||||
}
|
||||
|
||||
func (c *Console) loginStart(w http.ResponseWriter, r *http.Request) {
|
||||
if c.options.Identity == nil {
|
||||
fail(w, http.StatusNotFound, "unsupported", "this server uses local authentication; sign in with the link printed by the server")
|
||||
return
|
||||
}
|
||||
if !sameOrigin(r) || r.Header.Get("X-BD2-Console") != "1" {
|
||||
fail(w, http.StatusForbidden, "csrf", "console page expired; reload it")
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Provider string `json:"provider"`
|
||||
}
|
||||
if !decode(w, r, &request) {
|
||||
return
|
||||
}
|
||||
login, err := c.options.Identity.BeginConsoleLogin(request.Provider, clientIP(r))
|
||||
if errors.Is(err, auth.ErrRateLimited) {
|
||||
fail(w, http.StatusTooManyRequests, "rate_limited", "too many login attempts")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
fail(w, http.StatusBadRequest, "invalid", "login could not be started")
|
||||
return
|
||||
}
|
||||
key, err := randomToken(24)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "login could not be started")
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
now := c.options.Now()
|
||||
for id, pending := range c.pending {
|
||||
if !now.Before(pending.login.Expires) {
|
||||
delete(c.pending, id)
|
||||
}
|
||||
}
|
||||
c.pending[key] = &pendingLogin{login: login}
|
||||
c.mu.Unlock()
|
||||
http.SetCookie(w, &http.Cookie{Name: loginCookie, Value: key, Path: cookiePath, MaxAge: int(login.Expires.Sub(now).Seconds()), HttpOnly: true, Secure: c.options.Secure, SameSite: http.SameSiteStrictMode})
|
||||
writeJSON(w, http.StatusOK, map[string]any{"start_url": login.StartURL, "poll_interval_ms": 2000})
|
||||
}
|
||||
|
||||
func (c *Console) loginPoll(w http.ResponseWriter, r *http.Request) {
|
||||
if c.options.Identity == nil || !sameOrigin(r) || r.Header.Get("X-BD2-Console") != "1" {
|
||||
fail(w, http.StatusForbidden, "csrf", "console page expired; reload it")
|
||||
return
|
||||
}
|
||||
cookie, err := r.Cookie(loginCookie)
|
||||
if err != nil {
|
||||
fail(w, http.StatusGone, "expired", "login expired")
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
pending, ok := c.pending[cookie.Value]
|
||||
now := c.options.Now()
|
||||
throttled := ok && now.Sub(pending.lastPoll) < 1500*time.Millisecond
|
||||
if ok && !throttled {
|
||||
pending.lastPoll = now
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if !ok || !now.Before(pending.login.Expires) {
|
||||
c.clearCookie(w, loginCookie)
|
||||
fail(w, http.StatusGone, "expired", "login expired")
|
||||
return
|
||||
}
|
||||
if throttled {
|
||||
writeJSON(w, http.StatusAccepted, map[string]string{"status": "pending"})
|
||||
return
|
||||
}
|
||||
accountID, complete, err := c.options.Identity.FinishConsoleLogin(pending.login.ID, pending.login.Secret)
|
||||
if err == nil && !complete {
|
||||
writeJSON(w, http.StatusAccepted, map[string]string{"status": "pending"})
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
delete(c.pending, cookie.Value)
|
||||
c.mu.Unlock()
|
||||
c.clearCookie(w, loginCookie)
|
||||
if err != nil || accountID == "" {
|
||||
fail(w, http.StatusForbidden, "rejected", "login was rejected")
|
||||
return
|
||||
}
|
||||
role, err := c.roleOf(r.Context(), accountID)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "login unavailable")
|
||||
return
|
||||
}
|
||||
if role == "" {
|
||||
slog.Info("console login denied for account without access", "account", accountID)
|
||||
fail(w, http.StatusForbidden, "not_granted", "this game account has no console access")
|
||||
return
|
||||
}
|
||||
if err := c.startSession(w, r.Context(), accountID, role); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "login unavailable")
|
||||
return
|
||||
}
|
||||
slog.Info("console signed in", "account", accountID, "role", role)
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "complete"})
|
||||
}
|
||||
|
||||
func (c *Console) roleOf(ctx context.Context, accountID string) (Role, error) {
|
||||
administrator, err := c.options.Identity.AdministratorAccountID()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if administrator != "" && administrator == accountID {
|
||||
return RoleOwner, nil
|
||||
}
|
||||
member, err := c.options.Store.IsMember(ctx, accountID)
|
||||
if err != nil || !member {
|
||||
return "", err
|
||||
}
|
||||
return RoleMember, nil
|
||||
}
|
||||
|
||||
func (c *Console) logout(w http.ResponseWriter, r *http.Request) {
|
||||
if cookie, err := r.Cookie(sessionCookie); err == nil {
|
||||
if !sameOrigin(r) {
|
||||
fail(w, http.StatusForbidden, "csrf", "console page expired; reload it")
|
||||
return
|
||||
}
|
||||
if err := c.options.Store.DeleteSession(r.Context(), cookie.Value); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "sign out failed")
|
||||
return
|
||||
}
|
||||
}
|
||||
c.clearCookie(w, sessionCookie)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (c *Console) catalog(w http.ResponseWriter, _ *http.Request, _ session) {
|
||||
items, err := c.options.Catalog()
|
||||
if err != nil {
|
||||
slog.Error("console mail catalog unavailable", "error", err)
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "mail catalog unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"items": items})
|
||||
}
|
||||
|
||||
type playerView struct {
|
||||
Player
|
||||
Owner bool `json:"owner"`
|
||||
Member bool `json:"member"`
|
||||
Unlimited bool `json:"unlimited_inventory"`
|
||||
}
|
||||
|
||||
func (c *Console) players(w http.ResponseWriter, r *http.Request, current session) {
|
||||
players, err := c.options.Players(r.Context())
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "player directory unavailable")
|
||||
return
|
||||
}
|
||||
members, err := c.options.Store.Members(r.Context())
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "player directory unavailable")
|
||||
return
|
||||
}
|
||||
administrator := ""
|
||||
if c.options.Identity != nil {
|
||||
if administrator, err = c.options.Identity.AdministratorAccountID(); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "player directory unavailable")
|
||||
return
|
||||
}
|
||||
}
|
||||
settings, err := c.options.Inventory.Read()
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "development settings unavailable")
|
||||
return
|
||||
}
|
||||
views := []playerView{}
|
||||
for _, player := range players {
|
||||
if current.Role != RoleOwner && player.AccountID != current.AccountID {
|
||||
continue
|
||||
}
|
||||
views = append(views, playerView{Player: player, Owner: player.AccountID == administrator, Member: members[player.AccountID],
|
||||
Unlimited: settings.Value.Accounts[player.AccountID].Inventory.Unlimited})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"players": views})
|
||||
}
|
||||
|
||||
func (c *Console) player(ctx context.Context, accountID string) (Player, bool, error) {
|
||||
players, err := c.options.Players(ctx)
|
||||
if err != nil {
|
||||
return Player{}, false, err
|
||||
}
|
||||
for _, player := range players {
|
||||
if player.AccountID == accountID {
|
||||
return player, true, nil
|
||||
}
|
||||
}
|
||||
return Player{}, false, nil
|
||||
}
|
||||
|
||||
// target resolves the {account} path value: owners may address any listed
|
||||
// player, members only their own account.
|
||||
func (c *Console) target(w http.ResponseWriter, r *http.Request, current session) (Player, bool) {
|
||||
account := r.PathValue("account")
|
||||
if current.Role != RoleOwner && account != current.AccountID {
|
||||
fail(w, http.StatusForbidden, "forbidden", "members may only manage their own account")
|
||||
return Player{}, false
|
||||
}
|
||||
player, found, err := c.player(r.Context(), account)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "player directory unavailable")
|
||||
return Player{}, false
|
||||
}
|
||||
if !found || !player.Active {
|
||||
fail(w, http.StatusNotFound, "not_found", "player not found or inactive")
|
||||
return Player{}, false
|
||||
}
|
||||
return player, true
|
||||
}
|
||||
|
||||
func (c *Console) setMember(w http.ResponseWriter, r *http.Request, current session) {
|
||||
player, ok := c.target(w, r, current)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Member *bool `json:"member"`
|
||||
}
|
||||
if !decode(w, r, &request) || request.Member == nil {
|
||||
if request.Member == nil {
|
||||
fail(w, http.StatusBadRequest, "invalid", "member flag required")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err := c.options.Store.SetMember(r.Context(), player.AccountID, *request.Member); err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "member update failed")
|
||||
return
|
||||
}
|
||||
slog.Info("console member access changed", "account", player.AccountID, "uid", player.UID, "member", *request.Member)
|
||||
writeJSON(w, http.StatusOK, map[string]bool{"member": *request.Member})
|
||||
}
|
||||
|
||||
func (c *Console) inventory(w http.ResponseWriter, r *http.Request, current session) {
|
||||
player, ok := c.target(w, r, current)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
settings, err := c.options.Inventory.Read()
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "development settings unavailable")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"unlimited": settings.Value.Accounts[player.AccountID].Inventory.Unlimited, "limits": c.options.Limits})
|
||||
}
|
||||
|
||||
func (c *Console) setInventory(w http.ResponseWriter, r *http.Request, current session) {
|
||||
player, ok := c.target(w, r, current)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Unlimited *bool `json:"unlimited"`
|
||||
}
|
||||
if !decode(w, r, &request) {
|
||||
return
|
||||
}
|
||||
if request.Unlimited == nil {
|
||||
fail(w, http.StatusBadRequest, "invalid", "unlimited flag required")
|
||||
return
|
||||
}
|
||||
_, err := c.options.Inventory.Update("", func(settings *inventory.DevelopmentSettings) error {
|
||||
if settings.Accounts == nil {
|
||||
settings.Accounts = map[string]inventory.DevelopmentAccount{}
|
||||
}
|
||||
if *request.Unlimited {
|
||||
settings.Accounts[player.AccountID] = inventory.DevelopmentAccount{Inventory: inventory.DevelopmentInventory{Unlimited: true}}
|
||||
} else {
|
||||
delete(settings.Accounts, player.AccountID)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, commonconfig.ErrReadOnly) {
|
||||
fail(w, http.StatusForbidden, "read_only", "development settings are read-only")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("console inventory override failed", "account", player.AccountID, "error", err)
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "development settings unavailable")
|
||||
return
|
||||
}
|
||||
slog.Info("console inventory override changed", "account", player.AccountID, "uid", player.UID, "unlimited", *request.Unlimited)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"unlimited": *request.Unlimited, "limits": c.options.Limits})
|
||||
}
|
||||
|
||||
func (c *Console) sendMail(w http.ResponseWriter, r *http.Request, current session) {
|
||||
player, ok := c.target(w, r, current)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
ElementType uint64 `json:"element_type"`
|
||||
ID uint64 `json:"id"`
|
||||
Count uint64 `json:"count"`
|
||||
Title string `json:"title"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
if !decode(w, r, &request) {
|
||||
return
|
||||
}
|
||||
items, err := c.options.Catalog()
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "mail catalog unavailable")
|
||||
return
|
||||
}
|
||||
known := false
|
||||
for _, item := range items {
|
||||
if item.ElementType == request.ElementType && item.ID == request.ID {
|
||||
known = true
|
||||
break
|
||||
}
|
||||
}
|
||||
title, body := strings.TrimSpace(request.Title), strings.TrimSpace(request.Body)
|
||||
switch {
|
||||
case !known:
|
||||
fail(w, http.StatusBadRequest, "invalid_item", "item is not in the direct mail catalog")
|
||||
return
|
||||
case request.Count == 0 || request.Count > math.MaxInt32:
|
||||
fail(w, http.StatusBadRequest, "invalid_count", "count must be between 1 and 2147483647")
|
||||
return
|
||||
case title == "" || utf8.RuneCountInString(request.Title) > 500 || body == "" || utf8.RuneCountInString(request.Body) > 5000:
|
||||
fail(w, http.StatusBadRequest, "invalid_text", "title (1-500) and body (1-5000) are required")
|
||||
return
|
||||
}
|
||||
identity, err := randomToken(18)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "mail unavailable")
|
||||
return
|
||||
}
|
||||
identity = "console-" + identity
|
||||
grant := mail.Grant{AccountID: player.AccountID, Identity: identity, Title: request.Title, Body: request.Body, SentAt: c.options.Now().UnixMilli(),
|
||||
Rewards: []mail.GrantReward{{Type: request.ElementType, ID: request.ID, Count: request.Count}}}
|
||||
if err := mail.AppendGrant(c.options.MailSpool, grant); err != nil {
|
||||
slog.Error("console mail grant failed", "account", player.AccountID, "error", err)
|
||||
fail(w, http.StatusInternalServerError, "unavailable", "mail could not be queued")
|
||||
return
|
||||
}
|
||||
slog.Info("console mail queued", "account", player.AccountID, "uid", player.UID, "identity", identity, "type", request.ElementType, "id", request.ID, "count", request.Count, "by", current.AccountID)
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"identity": identity})
|
||||
}
|
||||
|
||||
func decode(w http.ResponseWriter, r *http.Request, target any) bool {
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 64<<10))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(target); err != nil || decoder.More() {
|
||||
fail(w, http.StatusBadRequest, "invalid", "invalid JSON request")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func clientIP(r *http.Request) string {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func fail(w http.ResponseWriter, status int, code, message string) {
|
||||
writeJSON(w, status, map[string]string{"code": code, "error": message})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/gateway/auth"
|
||||
)
|
||||
|
||||
type fakeIdentity struct{ next string }
|
||||
|
||||
func (f *fakeIdentity) Providers() []string { return []string{"discord"} }
|
||||
func (f *fakeIdentity) BeginConsoleLogin(string, string) (auth.ConsoleLogin, error) {
|
||||
return auth.ConsoleLogin{ID: "tx", Secret: "secret", StartURL: "https://example.test/auth/discord/start", Expires: time.Now().Add(time.Minute)}, nil
|
||||
}
|
||||
func (f *fakeIdentity) FinishConsoleLogin(id, secret string) (string, bool, error) {
|
||||
return f.next, true, nil
|
||||
}
|
||||
func (f *fakeIdentity) AdministratorAccountID() (string, error) { return "owner", nil }
|
||||
|
||||
type browser struct {
|
||||
t *testing.T
|
||||
server *httptest.Server
|
||||
client *http.Client
|
||||
csrf string
|
||||
}
|
||||
|
||||
func newConsole(t *testing.T) (*Console, *fakeIdentity, string) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
store, err := OpenStore(filepath.Join(root, "admin.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = store.Close() })
|
||||
settings, _, err := inventory.DevelopmentSettingsDocument.Open(filepath.Join(root, "dev-tools.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
identity := &fakeIdentity{}
|
||||
spool := filepath.Join(root, "mail-grants-spool.json")
|
||||
console, err := New(Options{
|
||||
Store: store, Identity: identity, MailSpool: spool, Inventory: settings, Configuration: commonconfig.NewRegistry(),
|
||||
Players: func(context.Context) ([]Player, error) {
|
||||
return []Player{{AccountID: "owner", UID: "1", Active: true}, {AccountID: "friend", UID: "2", Active: true}, {AccountID: "other", UID: "3", Active: true}}, nil
|
||||
},
|
||||
Catalog: func() ([]gamedata.MailCatalogItem, error) {
|
||||
return []gamedata.MailCatalogItem{{ElementType: 4, Name: "gold", Category: "currency"}}, nil
|
||||
},
|
||||
Server: func() any { return map[string]string{} },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return console, identity, spool
|
||||
}
|
||||
|
||||
func newBrowser(t *testing.T, server *httptest.Server) *browser {
|
||||
jar, err := cookiejar.New(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &browser{t: t, server: server, client: &http.Client{Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
|
||||
}
|
||||
|
||||
func (b *browser) do(method, path string, body any, headers map[string]string) (int, map[string]any) {
|
||||
b.t.Helper()
|
||||
var reader *bytes.Reader
|
||||
if body != nil {
|
||||
raw, _ := json.Marshal(body)
|
||||
reader = bytes.NewReader(raw)
|
||||
} else {
|
||||
reader = bytes.NewReader(nil)
|
||||
}
|
||||
request, err := http.NewRequest(method, b.server.URL+path, reader)
|
||||
if err != nil {
|
||||
b.t.Fatal(err)
|
||||
}
|
||||
request.Header.Set("X-BD2-Console", "1")
|
||||
if b.csrf != "" {
|
||||
request.Header.Set("X-CSRF-Token", b.csrf)
|
||||
}
|
||||
for key, value := range headers {
|
||||
if value == "" {
|
||||
request.Header.Del(key)
|
||||
} else {
|
||||
request.Header.Set(key, value)
|
||||
}
|
||||
}
|
||||
response, err := b.client.Do(request)
|
||||
if err != nil {
|
||||
b.t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = response.Body.Close() }()
|
||||
var value map[string]any
|
||||
_ = json.NewDecoder(response.Body).Decode(&value)
|
||||
return response.StatusCode, value
|
||||
}
|
||||
|
||||
func (b *browser) login(identity *fakeIdentity, account string) int {
|
||||
b.t.Helper()
|
||||
identity.next = account
|
||||
if status, _ := b.do(http.MethodPost, "/admin/api/login/start", map[string]string{"provider": "discord"}, nil); status != http.StatusOK {
|
||||
b.t.Fatalf("login start: %d", status)
|
||||
}
|
||||
status, _ := b.do(http.MethodPost, "/admin/api/login/poll", nil, nil)
|
||||
if status == http.StatusOK {
|
||||
_, session := b.do(http.MethodGet, "/admin/api/session", nil, nil)
|
||||
b.csrf, _ = session["csrf"].(string)
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func TestConsoleRolesFollowAdministratorAndOwnerGrants(t *testing.T) {
|
||||
console, identity, spool := newConsole(t)
|
||||
server := httptest.NewServer(console.Handler())
|
||||
defer server.Close()
|
||||
|
||||
owner := newBrowser(t, server)
|
||||
if status := owner.login(identity, "owner"); status != http.StatusOK {
|
||||
t.Fatalf("administrator login: %d", status)
|
||||
}
|
||||
if status, _ := owner.do(http.MethodGet, "/admin/api/config/", nil, nil); status != http.StatusOK {
|
||||
t.Fatalf("owner configuration access: %d", status)
|
||||
}
|
||||
|
||||
friend := newBrowser(t, server)
|
||||
if status := friend.login(identity, "friend"); status != http.StatusForbidden {
|
||||
t.Fatalf("ungranted account signed in: %d", status)
|
||||
}
|
||||
if status, _ := owner.do(http.MethodPut, "/admin/api/players/friend/member", map[string]bool{"member": true}, nil); status != http.StatusOK {
|
||||
t.Fatalf("grant member: %d", status)
|
||||
}
|
||||
if status := friend.login(identity, "friend"); status != http.StatusOK {
|
||||
t.Fatalf("granted member login: %d", status)
|
||||
}
|
||||
if status, _ := friend.do(http.MethodGet, "/admin/api/config/", nil, nil); status != http.StatusForbidden {
|
||||
t.Fatalf("member reached configuration: %d", status)
|
||||
}
|
||||
if _, value := friend.do(http.MethodGet, "/admin/api/players", nil, nil); len(value["players"].([]any)) != 1 {
|
||||
t.Fatalf("member saw other players: %v", value)
|
||||
}
|
||||
gift := map[string]any{"element_type": 4, "id": 0, "count": 5, "title": "t", "body": "b"}
|
||||
if status, _ := friend.do(http.MethodPost, "/admin/api/players/other/mail", gift, nil); status != http.StatusForbidden {
|
||||
t.Fatalf("member mailed another account: %d", status)
|
||||
}
|
||||
if status, _ := friend.do(http.MethodPost, "/admin/api/players/friend/mail", gift, nil); status != http.StatusCreated {
|
||||
t.Fatalf("member mail to self: %d", status)
|
||||
}
|
||||
raw, err := os.ReadFile(spool)
|
||||
if err != nil || !strings.Contains(string(raw), `"account_id": "friend"`) || strings.Contains(string(raw), `"account_id": "other"`) {
|
||||
t.Fatalf("spool recipients: %s, %v", raw, err)
|
||||
}
|
||||
|
||||
if status, _ := owner.do(http.MethodPut, "/admin/api/players/friend/member", map[string]bool{"member": false}, nil); status != http.StatusOK {
|
||||
t.Fatalf("revoke member: %d", status)
|
||||
}
|
||||
if status, _ := friend.do(http.MethodGet, "/admin/api/players", nil, nil); status != http.StatusUnauthorized {
|
||||
t.Fatalf("revoked member session survived: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsoleStateChangesRequireSessionCSRFAndSameOrigin(t *testing.T) {
|
||||
console, identity, _ := newConsole(t)
|
||||
server := httptest.NewServer(console.Handler())
|
||||
defer server.Close()
|
||||
owner := newBrowser(t, server)
|
||||
owner.login(identity, "owner")
|
||||
change := map[string]bool{"unlimited": true}
|
||||
if status, _ := owner.do(http.MethodPut, "/admin/api/players/other/inventory", change, map[string]string{"X-CSRF-Token": ""}); status != http.StatusForbidden {
|
||||
t.Fatalf("missing CSRF token accepted: %d", status)
|
||||
}
|
||||
if status, _ := owner.do(http.MethodPut, "/admin/api/players/other/inventory", change, map[string]string{"Sec-Fetch-Site": "cross-site"}); status != http.StatusForbidden {
|
||||
t.Fatalf("cross-site request accepted: %d", status)
|
||||
}
|
||||
if status, value := owner.do(http.MethodPut, "/admin/api/players/other/inventory", change, nil); status != http.StatusOK || value["unlimited"] != true {
|
||||
t.Fatalf("inventory override: %d %v", status, value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignInLinkIsSingleUse(t *testing.T) {
|
||||
console, _, _ := newConsole(t)
|
||||
server := httptest.NewServer(console.Handler())
|
||||
defer server.Close()
|
||||
link, err := console.IssueSignInLink(server.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := strings.TrimPrefix(link, server.URL)
|
||||
operator := newBrowser(t, server)
|
||||
if status, _ := operator.do(http.MethodGet, path, nil, nil); status != http.StatusSeeOther {
|
||||
t.Fatalf("sign-in link: %d", status)
|
||||
}
|
||||
if _, session := operator.do(http.MethodGet, "/admin/api/session", nil, nil); session["role"] != string(RoleOwner) {
|
||||
t.Fatalf("link did not sign in the owner: %v", session)
|
||||
}
|
||||
if status, _ := newBrowser(t, server).do(http.MethodGet, path, nil, nil); status != http.StatusForbidden {
|
||||
t.Fatalf("sign-in link reused: %d", status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
// Role is a console permission level.
|
||||
type Role string
|
||||
|
||||
const (
|
||||
// RoleOwner manages the whole server. It belongs to the game's
|
||||
// administrator account and to sign-in links printed by the server.
|
||||
RoleOwner Role = "owner"
|
||||
// RoleMember may use the player tools for its own game account only.
|
||||
RoleMember Role = "member"
|
||||
)
|
||||
|
||||
// Store persists console sessions and member grants in state/admin.db.
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
type session struct {
|
||||
AccountID string
|
||||
Role Role
|
||||
CSRF string
|
||||
Expires time.Time
|
||||
}
|
||||
|
||||
const sessionTTL = 24 * time.Hour
|
||||
|
||||
func OpenStore(path string) (*Store, error) {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return nil, fmt.Errorf("admin: create database directory: %w", err)
|
||||
}
|
||||
db, err := sql.Open("sqlite", filepath.Clean(path))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("admin: open database: %w", err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
for _, statement := range []string{
|
||||
`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000`,
|
||||
`CREATE TABLE IF NOT EXISTS sessions (token_hash BLOB PRIMARY KEY NOT NULL, account_id TEXT NOT NULL, role TEXT NOT NULL CHECK(role IN ('owner','member')), csrf TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL) WITHOUT ROWID`,
|
||||
`CREATE TABLE IF NOT EXISTS members (account_id TEXT PRIMARY KEY NOT NULL CHECK(length(account_id)>0), granted_at INTEGER NOT NULL) WITHOUT ROWID`,
|
||||
} {
|
||||
if _, err := db.Exec(statement); err != nil {
|
||||
_ = db.Close()
|
||||
return nil, fmt.Errorf("admin: initialize database: %w", err)
|
||||
}
|
||||
}
|
||||
if err := os.Chmod(filepath.Clean(path), 0o600); err != nil {
|
||||
_ = db.Close()
|
||||
return nil, fmt.Errorf("admin: restrict database permissions: %w", err)
|
||||
}
|
||||
return &Store{db: db, now: time.Now}, nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() error { return s.db.Close() }
|
||||
|
||||
// CreateSession returns a new session token and its CSRF token.
|
||||
func (s *Store) CreateSession(ctx context.Context, accountID string, role Role) (token, csrf string, err error) {
|
||||
if token, err = randomToken(32); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if csrf, err = randomToken(24); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
now := s.now()
|
||||
if _, err = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE expires_at<=?`, now.Unix()); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
_, err = s.db.ExecContext(ctx, `INSERT INTO sessions VALUES(?,?,?,?,?,?)`, digest(token), accountID, string(role), csrf, now.Unix(), now.Add(sessionTTL).Unix())
|
||||
return token, csrf, err
|
||||
}
|
||||
|
||||
// Session resolves a live session token. Member sessions end as soon as the
|
||||
// grant is revoked, without waiting for expiry.
|
||||
func (s *Store) Session(ctx context.Context, token string) (session, bool, error) {
|
||||
if token == "" {
|
||||
return session{}, false, nil
|
||||
}
|
||||
var result session
|
||||
var role string
|
||||
var expires int64
|
||||
err := s.db.QueryRowContext(ctx, `SELECT s.account_id,s.role,s.csrf,s.expires_at FROM sessions s
|
||||
WHERE s.token_hash=? AND s.expires_at>? AND (s.role='owner' OR EXISTS(SELECT 1 FROM members m WHERE m.account_id=s.account_id))`,
|
||||
digest(token), s.now().Unix()).Scan(&result.AccountID, &role, &result.CSRF, &expires)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return session{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return session{}, false, err
|
||||
}
|
||||
result.Role, result.Expires = Role(role), time.Unix(expires, 0)
|
||||
return result, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteSession(ctx context.Context, token string) error {
|
||||
_, err := s.db.ExecContext(ctx, `DELETE FROM sessions WHERE token_hash=?`, digest(token))
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) Members(ctx context.Context) (map[string]bool, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT account_id FROM members`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
members := map[string]bool{}
|
||||
for rows.Next() {
|
||||
var account string
|
||||
if err := rows.Scan(&account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
members[account] = true
|
||||
}
|
||||
return members, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) IsMember(ctx context.Context, accountID string) (bool, error) {
|
||||
var exists bool
|
||||
err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM members WHERE account_id=?)`, accountID).Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
// SetMember grants or revokes member access. Revocation also ends sessions.
|
||||
func (s *Store) SetMember(ctx context.Context, accountID string, member bool) error {
|
||||
if accountID == "" {
|
||||
return errors.New("admin: member requires an account")
|
||||
}
|
||||
if member {
|
||||
_, err := s.db.ExecContext(ctx, `INSERT INTO members VALUES(?,?) ON CONFLICT(account_id) DO NOTHING`, accountID, s.now().Unix())
|
||||
return err
|
||||
}
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM members WHERE account_id=?`, accountID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM sessions WHERE account_id=? AND role='member'`, accountID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
func randomToken(size int) (string, error) {
|
||||
b := make([]byte, size)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
func digest(token string) []byte {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return sum[:]
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
:root{
|
||||
--paper:#f2efe7;--sheet:#fbfaf6;--ink:#26231d;--ink-2:#5b564b;--muted:#8b8577;--line:#e4dfd3;--line-2:#d2cbbb;
|
||||
--seal:#a5432d;--seal-ink:#fff9f4;--seal-soft:#f4e4dc;--moss:#4b6944;--moss-soft:#e5ebdf;--air:#3d5b78;--amber:#8a6418;--amber-soft:#f5ead2;
|
||||
--sans:system-ui,-apple-system,"Segoe UI","PingFang SC","Microsoft YaHei UI","Microsoft YaHei","Noto Sans SC",sans-serif;
|
||||
--num:"Iowan Old Style","Palatino Linotype",Palatino,Georgia,serif;
|
||||
--mono:ui-monospace,"Cascadia Mono","SF Mono",Consolas,monospace;
|
||||
color-scheme:light dark;
|
||||
}
|
||||
@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;
|
||||
}}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:var(--paper);color:var(--ink);font:14.5px/1.6 var(--sans);-webkit-font-smoothing:antialiased}
|
||||
button,input,select,textarea{font:inherit;color:inherit}
|
||||
:focus-visible{outline:2px solid var(--seal);outline-offset:2px}
|
||||
[hidden]{display:none!important}
|
||||
kbd{font:500 11px/1 var(--mono);color:var(--muted);border:1px solid var(--line-2);border-bottom-width:2px;border-radius:4px;padding:2px 5px;background:var(--sheet)}
|
||||
code{font:12.5px var(--mono)}
|
||||
.muted{color:var(--muted)}
|
||||
.eyebrow{font-size:12px;letter-spacing:.18em;color:var(--muted)}
|
||||
h2{font-size:16px;font-weight:600;margin:0;letter-spacing:.06em}
|
||||
|
||||
/* 顶栏 */
|
||||
.top{max-width:1200px;margin:0 auto;padding:20px 28px 6px;display:flex;align-items:center;gap:28px}
|
||||
.brand{display:flex;align-items:center;gap:10px;font-size:15px;letter-spacing:.04em}
|
||||
.brand b{font-family:var(--num);font-size:19px;letter-spacing:.06em}
|
||||
.brand span{color:var(--muted)}
|
||||
.seal-mark{width:18px;height:18px;border-radius:50%;background:var(--seal);box-shadow:inset 0 0 0 3px var(--seal),inset 0 0 0 4px color-mix(in srgb,var(--seal-ink) 55%,transparent)}
|
||||
.tabs{display:flex;gap:4px;flex:1}
|
||||
.tabs a{color:var(--ink-2);text-decoration:none;padding:6px 14px;border-radius:999px;font-size:14px;transition:background .15s,color .15s;position:relative}
|
||||
.tabs a:hover{color:var(--ink);background:color-mix(in srgb,var(--line) 60%,transparent)}
|
||||
.tabs a[aria-current=page]{background:var(--ink);color:var(--paper)}
|
||||
.tabs a .dot{position:absolute;top:5px;right:6px;width:6px;height:6px;border-radius:50%;background:var(--amber)}
|
||||
.account{display:flex;align-items:center;gap:16px;font-size:13.5px;color:var(--ink-2);margin-left:auto}
|
||||
.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)}
|
||||
|
||||
.desk{max-width:1200px;margin:0 auto;padding:12px 28px 96px}
|
||||
.card{background:var(--sheet);border:1px solid var(--line);border-radius:14px}
|
||||
|
||||
/* 登录 */
|
||||
.sign-in{display:grid;place-items:center;min-height:60vh}
|
||||
.sheet{position:relative;overflow:hidden;width:100%;max-width:400px;padding:36px 32px 28px}
|
||||
.sheet::before,.slip::before{content:"";position:absolute;inset:0 0 auto;height:5px;background:repeating-linear-gradient(-45deg,var(--seal) 0 10px,transparent 10px 16px,var(--air) 16px 26px,transparent 26px 32px)}
|
||||
.sheet h1{font-size:23px;font-weight:600;letter-spacing:.05em;margin:0 0 4px}
|
||||
.providers{display:flex;flex-direction:column;gap:10px;margin-top:22px}
|
||||
.providers .btn{width:100%;padding:11px;font-size:15px}
|
||||
|
||||
/* 表单元素 */
|
||||
input:not([type=checkbox]):not([type=radio]),select,textarea{width:100%;background:var(--sheet);border:1px solid var(--line-2);border-radius:8px;padding:8px 11px;transition:border-color .15s,box-shadow .15s}
|
||||
input:not([type=checkbox]):not([type=radio]):focus,select:focus,textarea:focus{outline:0;border-color:var(--seal);box-shadow:0 0 0 3px color-mix(in srgb,var(--seal) 16%,transparent)}
|
||||
input:disabled,select:disabled,textarea:disabled{opacity:.6;cursor:not-allowed}
|
||||
select{width:auto;cursor:pointer}
|
||||
textarea{resize:vertical;min-height:76px}
|
||||
.btn{border:1px solid var(--line-2);background:var(--sheet);border-radius:9px;padding:8px 16px;cursor:pointer;white-space:nowrap;transition:background .15s,border-color .15s,transform .08s}
|
||||
.btn:hover{border-color:var(--ink-2)}
|
||||
.btn:active{transform:translateY(1px)}
|
||||
.btn.seal{background:var(--seal);border-color:var(--seal);color:var(--seal-ink);font-weight:600}
|
||||
.btn.seal:hover{background:color-mix(in srgb,var(--seal) 88%,var(--ink))}
|
||||
.btn.ghost{background:none;border-color:transparent;color:var(--ink-2)}
|
||||
.btn.ghost:hover{border-color:var(--line-2);color:var(--ink)}
|
||||
.btn:disabled{opacity:.5;cursor:default;transform:none}
|
||||
.btn kbd{margin-left:6px;background:none;color:inherit;opacity:.65;border-color:currentColor}
|
||||
|
||||
/* 收件人 */
|
||||
.recipient{padding:20px 26px;display:grid;grid-template-columns:auto 1fr;gap:6px 40px;align-items:center}
|
||||
.who .eyebrow{display:block}
|
||||
.uid{font-family:var(--num);font-size:34px;line-height:1.15;letter-spacing:.07em;font-variant-numeric:lining-nums tabular-nums;cursor:copy;user-select:all}
|
||||
.uid.none{color:var(--line-2);cursor:default}
|
||||
.who p{margin:2px 0 0;font-size:13px}
|
||||
.recipient-side{justify-self:end;display:flex;flex-direction:column;align-items:flex-end;gap:8px}
|
||||
.player{display:flex;align-items:center;gap:12px;font-size:13px;color:var(--muted)}
|
||||
.player select{min-width:220px}
|
||||
|
||||
/* 工作区 */
|
||||
.work{border:0;padding:0;margin:18px 0 0;min-width:0;position:relative;display:grid;grid-template-columns:minmax(0,1fr) 352px;gap:18px;align-items:start}
|
||||
.work>.catalog,.work>.side{transition:opacity .15s,filter .15s}
|
||||
.work:disabled>.catalog,.work:disabled>.side{opacity:.38;filter:grayscale(.4);pointer-events:none;transition-delay:.25s}
|
||||
.lock{display:none;position:absolute;inset:0;z-index:5;align-items:flex-start;justify-content:center;padding-top:120px}
|
||||
.work:disabled .lock{display:flex;animation:appear .2s .25s both}
|
||||
.lock span{background:var(--ink);color:var(--paper);padding:9px 18px;border-radius:999px;font-size:13.5px;letter-spacing:.04em}
|
||||
@keyframes appear{from{opacity:0}to{opacity:1}}
|
||||
|
||||
/* 目录 */
|
||||
.catalog{padding:18px 18px 12px}
|
||||
.cat-head{display:flex;align-items:baseline;justify-content:space-between;gap:12px;padding:0 4px 12px}
|
||||
#count{font-size:12.5px;font-variant-numeric:tabular-nums}
|
||||
.search{position:relative}
|
||||
.search svg{position:absolute;left:12px;top:50%;translate:0 -50%;color:var(--muted);pointer-events:none}
|
||||
.search input{padding:10px 44px 10px 36px!important;font-size:15px}
|
||||
.search.small input{padding:7px 12px!important;font-size:14px}
|
||||
.search input::-webkit-search-cancel-button{display:none}
|
||||
.search kbd{position:absolute;right:11px;top:50%;translate:0 -50%}
|
||||
.search input:focus~kbd{opacity:0}
|
||||
.chips{display:flex;flex-wrap:wrap;gap:6px;margin:12px 0 4px}
|
||||
.chip{border:1px solid var(--line);background:none;border-radius:999px;padding:3px 11px;font-size:12.5px;color:var(--ink-2);cursor:pointer;transition:all .15s}
|
||||
.chip small{margin-left:6px;color:var(--muted);font-variant-numeric:tabular-nums}
|
||||
.chip:hover{border-color:var(--line-2);color:var(--ink)}
|
||||
.chip[aria-pressed=true]{background:var(--ink);border-color:var(--ink);color:var(--paper)}
|
||||
.chip[aria-pressed=true] small{color:color-mix(in srgb,var(--paper) 65%,transparent)}
|
||||
.chip:disabled{cursor:not-allowed;opacity:.6}
|
||||
.recent{display:flex;align-items:center;flex-wrap:wrap;gap:6px;margin:10px 0 2px;font-size:12.5px}
|
||||
.recent .eyebrow{margin-right:4px;font-size:11.5px}
|
||||
.recent button{border:1px dashed var(--line-2);background:none;border-radius:6px;padding:2px 9px;cursor:pointer;color:var(--ink-2)}
|
||||
.recent button:hover{border-style:solid;border-color:var(--seal);color:var(--seal)}
|
||||
.items{list-style:none;margin:10px 0 0;padding:0;max-height:max(360px,calc(100vh - 400px));overflow:auto;overscroll-behavior:contain;scrollbar-width:thin;scrollbar-color:var(--line-2) transparent}
|
||||
.item{display:grid;grid-template-columns:minmax(0,1fr) auto 86px;column-gap:14px;align-items:baseline;padding:8px 12px;border-radius:8px;cursor:pointer}
|
||||
.item+.item{box-shadow:0 -1px 0 var(--line)}
|
||||
.item.active,.item.active+.item{box-shadow:none}
|
||||
.item.active{background:var(--paper)}
|
||||
.item.chosen{box-shadow:inset 3px 0 0 var(--seal)!important;background:var(--seal-soft)}
|
||||
.item .n{font-weight:500;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.item .c{font-size:12px;color:var(--muted);white-space:nowrap}
|
||||
.item .i{font:12px var(--mono);color:var(--ink-2);text-align:right}
|
||||
.item .i i{font-style:normal;color:var(--muted)}
|
||||
.item .d{grid-column:1/-1;font-size:12px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.items .empty{padding:40px 12px;text-align:center;color:var(--muted)}
|
||||
mark{background:color-mix(in srgb,var(--seal) 22%,transparent);color:inherit;border-radius:2px;padding:0 1px}
|
||||
.keys{margin:10px 4px 0;font-size:12px;display:flex;gap:16px;flex-wrap:wrap}
|
||||
.keys kbd{margin-right:4px}
|
||||
|
||||
/* 包裹单 */
|
||||
.side{position:sticky;top:16px;display:flex;flex-direction:column;gap:14px}
|
||||
.slip{position:relative;overflow:hidden;padding:24px 22px 20px}
|
||||
.slip-head{display:flex;justify-content:space-between;align-items:baseline;padding-bottom:12px;border-bottom:1.5px dashed var(--line-2);margin-bottom:16px}
|
||||
.slip-head .to{font-size:12.5px;color:var(--muted)}
|
||||
.slip-head .to b{font:600 15px var(--num);color:var(--ink);letter-spacing:.05em;margin-left:4px}
|
||||
.parcel{position:relative;border-radius:10px;padding:14px 16px;background:var(--paper);min-height:84px}
|
||||
.parcel.empty{display:grid;place-items:center;text-align:center;background:none;border:1.5px dashed var(--line-2);color:var(--muted);font-size:13px;cursor:pointer}
|
||||
.parcel.empty:hover{border-color:var(--muted)}
|
||||
.parcel.empty p{margin:0}
|
||||
.parcel.empty span{font-size:12px}
|
||||
.parcel.shake{animation:shake .35s}
|
||||
@keyframes shake{25%{translate:-5px}50%{translate:4px}75%{translate:-2px}}
|
||||
.p-name{font-size:17px;font-weight:600;padding-right:28px;line-height:1.35}
|
||||
.p-meta{display:flex;gap:10px;align-items:center;margin-top:4px;font-size:12.5px;color:var(--ink-2)}
|
||||
.p-meta code{font-size:12px;color:var(--muted)}
|
||||
.p-detail{margin:8px 0 0;font-size:12px;color:var(--muted);display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}
|
||||
.p-detail:hover{-webkit-line-clamp:unset}
|
||||
.parcel .x{position:absolute;top:8px;right:8px;width:26px;height:26px;border:0;border-radius:6px;background:none;color:var(--muted);font-size:18px;line-height:1;cursor:pointer}
|
||||
.parcel .x:hover{background:var(--line);color:var(--ink)}
|
||||
.field{margin-top:16px}
|
||||
.field>label{display:flex;justify-content:space-between;align-items:baseline;font-size:12.5px;color:var(--ink-2);margin-bottom:6px}
|
||||
#qty-hint{font-size:12px;color:var(--muted);font-variant-numeric:tabular-nums}
|
||||
#qty-hint.err{color:var(--seal)}
|
||||
#quantity{font:500 22px/1.2 var(--num)!important;letter-spacing:.03em;padding:8px 12px!important;font-variant-numeric:lining-nums tabular-nums}
|
||||
.presets{display:flex;gap:6px;margin-top:8px}
|
||||
.presets button{flex:1;border:1px solid var(--line);background:none;border-radius:7px;padding:4px 0;font:13px var(--num);color:var(--ink-2);cursor:pointer}
|
||||
.presets button:hover{border-color:var(--ink-2);color:var(--ink)}
|
||||
.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-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}
|
||||
.letter input,.letter textarea{margin-top:4px}
|
||||
.send{width:100%;margin-top:18px;padding:11px 16px;font-size:15px;letter-spacing:.3em;display:flex;align-items:center;justify-content:center;gap:12px}
|
||||
.send kbd{letter-spacing:0}
|
||||
.send.done{background:var(--moss);border-color:var(--moss)}
|
||||
|
||||
.status{white-space:pre-wrap;font-size:13px;line-height:1.55;margin:12px 0 0;color:var(--ink-2)}
|
||||
.status:empty{display:none}
|
||||
.status.ok{color:var(--moss);background:var(--moss-soft);padding:9px 12px;border-radius:8px}
|
||||
.status.err{color:var(--seal);background:var(--seal-soft);padding:9px 12px;border-radius:8px}
|
||||
|
||||
.panel{padding:16px 20px}
|
||||
.panel h3{font-size:13px;font-weight:600;margin:0;letter-spacing:.06em;display:flex;justify-content:space-between;align-items:center}
|
||||
.switch{display:inline-flex;align-items:center;gap:10px;cursor:pointer;font-size:13.5px;font-weight:400;letter-spacing:0}
|
||||
.switch input{position:absolute;opacity:0;pointer-events:none}
|
||||
.track{width:34px;height:20px;border-radius:999px;background:var(--line-2);position:relative;transition:background .2s;flex-shrink:0}
|
||||
.track::after{content:"";position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:var(--sheet);box-shadow:0 1px 2px rgba(0,0,0,.2);transition:translate .2s}
|
||||
.switch input:checked+.track{background:var(--moss)}
|
||||
.switch input:checked+.track::after{translate:14px}
|
||||
.switch input:focus-visible+.track{outline:2px solid var(--seal);outline-offset:2px}
|
||||
.switch input:disabled+.track{opacity:.5}
|
||||
.switch:has(input:disabled){cursor:not-allowed}
|
||||
.limits{display:grid;grid-template-columns:auto 1fr 1fr;gap:2px 12px;margin:12px 0 0;font-size:12.5px}
|
||||
.limits:empty{display:none}
|
||||
.limits>*{padding:3px 0}
|
||||
.limits .h{color:var(--muted);font-size:11.5px;text-align:right}
|
||||
.limits b{font:500 14px var(--num);text-align:right;font-variant-numeric:lining-nums tabular-nums;color:var(--muted)}
|
||||
.limits .on,.limits .on+b,.limits .on+b+b{color:var(--ink)}
|
||||
.limits .lab{color:var(--muted)}
|
||||
.limits .lab.on::before{content:"● ";color:var(--moss);font-size:9px;vertical-align:1px}
|
||||
.hint{font-size:12px;color:var(--muted);margin:10px 0 0;line-height:1.55}
|
||||
|
||||
.log{list-style:none;padding:0;margin:10px 0 0;max-height:260px;overflow:auto;scrollbar-width:thin}
|
||||
.log li{padding:8px 0;border-top:1px solid var(--line);font-size:13px;display:grid;grid-template-columns:1fr auto;gap:0 10px}
|
||||
.log li:first-child{border-top:0}
|
||||
.log .what{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.log .what b{font-weight:500}
|
||||
.log .meta{grid-column:1;font-size:11.5px;color:var(--muted)}
|
||||
.log .again{grid-row:1/3;grid-column:2;align-self:center;border:0;background:none;color:var(--muted);font-size:12px;cursor:pointer;padding:4px 6px;border-radius:6px}
|
||||
.log .again:hover{color:var(--seal);background:var(--seal-soft)}
|
||||
.log .ident{grid-column:1/-1;justify-self:start;margin-top:3px;border:0;background:var(--paper);border-radius:5px;padding:1px 7px;font:11px var(--mono);color:var(--muted);cursor:copy;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.log .ident:hover{color:var(--ink)}
|
||||
.log-empty{font-size:12.5px;color:var(--muted);margin:8px 0 0}
|
||||
|
||||
/* 玩家 */
|
||||
.roster{padding:20px 24px}
|
||||
.roster-head{display:flex;justify-content:space-between;align-items:flex-end;gap:24px;margin-bottom:12px}
|
||||
.roster-head p{margin:4px 0 0;font-size:13px}
|
||||
.roster-head .search{width:220px;flex-shrink:0}
|
||||
.roster-table{width:100%;border-collapse:collapse;font-size:13.5px}
|
||||
.roster-table th{font-weight:400;font-size:12px;color:var(--muted);text-align:left;padding:0 10px 8px;border-bottom:1.5px dashed var(--line-2)}
|
||||
.roster-table td{padding:10px;border-bottom:1px solid var(--line);vertical-align:middle}
|
||||
.roster-table tr:last-child td{border-bottom:0}
|
||||
.roster-table .c{text-align:center}
|
||||
.roster-table .uid-cell{font:500 15px var(--num);letter-spacing:.05em;font-variant-numeric:lining-nums tabular-nums}
|
||||
.roster-table tr.inactive td{color:var(--muted)}
|
||||
.roster-table td.act{text-align:right}
|
||||
.pill{display:inline-block;padding:1px 9px;border-radius:999px;font-size:12px;background:var(--paper);color:var(--muted);margin-right:4px}
|
||||
.pill.owner{background:var(--seal-soft);color:var(--seal)}
|
||||
.pill.member{background:var(--moss-soft);color:var(--moss)}
|
||||
.linkish{border:0;background:none;color:var(--seal);cursor:pointer;font-size:13px;padding:2px 4px}
|
||||
.linkish:hover{text-decoration:underline}
|
||||
|
||||
/* 配置 */
|
||||
.config-layout{display:grid;grid-template-columns:230px minmax(0,1fr);gap:18px;align-items:start}
|
||||
.doc-nav{position:sticky;top:16px;padding:10px}
|
||||
.doc-nav button.doc{display:flex;width:100%;align-items:center;gap:8px;border:0;background:none;text-align:left;padding:9px 12px;border-radius:9px;cursor:pointer;color:var(--ink-2)}
|
||||
.doc-nav button.doc:hover{background:var(--paper);color:var(--ink)}
|
||||
.doc-nav button.doc[aria-current=true]{background:var(--ink);color:var(--paper)}
|
||||
.doc-nav button.doc .badge{margin-left:auto;font-size:11px;padding:0 7px;border-radius:999px;background:var(--amber-soft);color:var(--amber)}
|
||||
.doc-nav button.doc[aria-current=true] .badge{background:color-mix(in srgb,var(--paper) 20%,transparent);color:var(--paper)}
|
||||
.doc-nav .toc{list-style:none;margin:4px 0 10px;padding:0 0 0 14px;border-left:1px solid var(--line);margin-left:16px}
|
||||
.doc-nav .toc a{display:block;font-size:12.5px;color:var(--muted);text-decoration:none;padding:3px 8px}
|
||||
.doc-nav .toc a:hover{color:var(--ink)}
|
||||
.doc-nav .toc a.bad{color:var(--seal)}
|
||||
.doc-nav .sep{border-top:1px solid var(--line);margin:8px 4px}
|
||||
.config-main{display:flex;flex-direction:column;gap:14px;min-width:0}
|
||||
.banner{padding:12px 16px;border-radius:12px;font-size:13.5px;display:flex;gap:12px;align-items:flex-start;border:1px solid transparent}
|
||||
.banner b{font-weight:600}
|
||||
.banner p{margin:2px 0 0;font-size:12.5px}
|
||||
.banner.pending{background:var(--amber-soft);color:var(--amber);border-color:color-mix(in srgb,var(--amber) 25%,transparent)}
|
||||
.banner.readonly{background:var(--paper);color:var(--ink-2);border-color:var(--line-2)}
|
||||
.banner.broken{background:var(--seal-soft);color:var(--seal)}
|
||||
.banner ul{margin:6px 0 0;padding-left:18px;font-size:12.5px}
|
||||
.doc-head{padding:20px 24px 4px}
|
||||
.doc-head h2{font-size:19px}
|
||||
.doc-head p{margin:4px 0 0;font-size:13px;color:var(--muted)}
|
||||
.doc-head .path{font:12px var(--mono);color:var(--muted);margin-top:6px;display:flex;gap:10px;flex-wrap:wrap}
|
||||
.config-form{display:flex;flex-direction:column;gap:14px}
|
||||
.config-form fieldset{border:0;padding:0;margin:0;min-width:0}
|
||||
.section{padding:20px 24px 18px;scroll-margin-top:16px}
|
||||
.section>h3{font-size:15px;font-weight:600;margin:0;letter-spacing:.04em}
|
||||
.section>p.help{margin:4px 0 0;font-size:12.5px;color:var(--muted)}
|
||||
.cfield{display:grid;grid-template-columns:200px minmax(0,1fr);gap:6px 24px;padding:14px 0;border-top:1px solid var(--line)}
|
||||
.section>h3+.cfield,.section>.help+.cfield{border-top:0;margin-top:6px}
|
||||
.cfield .label{font-size:13.5px;color:var(--ink);padding-top:6px}
|
||||
.cfield .label small{display:block;font:11px var(--mono);color:var(--muted);margin-top:2px;word-break:break-all}
|
||||
.cfield .control{min-width:0}
|
||||
.cfield .control>.help{font-size:12px;color:var(--muted);margin:6px 0 0}
|
||||
.cfield.changed .label::before{content:"";display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--amber);margin:0 8px 2px -14px}
|
||||
.cfield .msg{font-size:12.5px;margin:6px 0 0;padding:6px 10px;border-radius:7px}
|
||||
.cfield .msg.err{color:var(--seal);background:var(--seal-soft)}
|
||||
.cfield .msg.warn{color:var(--amber);background:var(--amber-soft)}
|
||||
.cfield .msg.lock{color:var(--ink-2);background:var(--paper)}
|
||||
.cfield.invalid input{border-color:var(--seal)}
|
||||
.segmented{display:inline-flex;flex-wrap:wrap;border:1px solid var(--line-2);border-radius:10px;padding:3px;gap:3px;background:var(--paper)}
|
||||
.segmented label{position:relative;cursor:pointer}
|
||||
.segmented input{position:absolute;opacity:0;pointer-events:none}
|
||||
.segmented span{display:block;padding:5px 14px;border-radius:7px;font-size:13.5px;color:var(--ink-2);transition:background .15s,color .15s}
|
||||
.segmented label:hover span{color:var(--ink)}
|
||||
.segmented input:checked+span{background:var(--ink);color:var(--paper)}
|
||||
.segmented input:focus-visible+span{outline:2px solid var(--seal);outline-offset:1px}
|
||||
.segmented input:disabled+span{cursor:not-allowed;opacity:.6}
|
||||
.option-help{font-size:12px;color:var(--muted);margin:6px 0 0}
|
||||
.rows{display:flex;flex-direction:column;gap:6px}
|
||||
.row{display:flex;gap:6px;align-items:center}
|
||||
.row input{font-family:var(--mono);font-size:13px}
|
||||
.row .state{font-size:11.5px;white-space:nowrap}
|
||||
.icon-btn{border:1px solid var(--line);background:none;border-radius:7px;width:30px;height:30px;flex-shrink:0;cursor:pointer;color:var(--muted)}
|
||||
.icon-btn:hover{border-color:var(--seal);color:var(--seal)}
|
||||
.add{align-self:flex-start;border:1px dashed var(--line-2);background:none;border-radius:7px;padding:4px 12px;font-size:12.5px;color:var(--ink-2);cursor:pointer;margin-top:2px}
|
||||
.add:hover{border-style:solid;border-color:var(--ink-2)}
|
||||
.unit-input{display:flex;align-items:center;gap:8px;max-width:260px}
|
||||
.unit-input input{font-family:var(--num);font-size:15px;font-variant-numeric:lining-nums tabular-nums}
|
||||
.unit-input span{color:var(--muted);font-size:12px;white-space:nowrap}
|
||||
.text-input{max-width:520px}
|
||||
.text-input.mono input{font-family:var(--mono);font-size:13px}
|
||||
.map-keys{display:flex;flex-direction:column;gap:10px}
|
||||
.map-entry{border:1px solid var(--line);border-radius:10px;padding:10px 14px}
|
||||
.map-entry .sub{display:grid;grid-template-columns:150px minmax(0,1fr);gap:8px 14px;align-items:center;margin-top:10px}
|
||||
.map-entry .sub label{font-size:12.5px;color:var(--ink-2)}
|
||||
.map-entry .sub .msg{grid-column:2}
|
||||
.advanced{border-top:1px solid var(--line);margin-top:6px}
|
||||
.advanced>summary{cursor:pointer;list-style:none;font-size:12.5px;color:var(--muted);padding:10px 0 4px}
|
||||
.advanced>summary::-webkit-details-marker{display:none}
|
||||
.advanced>summary::before{content:"▸ ";}
|
||||
.advanced[open]>summary::before{content:"▾ ";}
|
||||
.example{font-size:12.5px;color:var(--ink-2);background:var(--paper);border-radius:8px;padding:8px 12px;margin-top:8px}
|
||||
.example b{font:600 14px var(--num)}
|
||||
.overview{padding:18px 24px}
|
||||
.overview h3{font-size:13px;margin:0 0 10px;letter-spacing:.06em}
|
||||
.overview dl{display:grid;grid-template-columns:150px minmax(0,1fr);gap:6px 18px;margin:0;font-size:13px}
|
||||
.overview dt{color:var(--muted)}
|
||||
.overview dd{margin:0;word-break:break-all}
|
||||
.overview dd code{font-size:12px}
|
||||
.savebar{position:fixed;left:50%;bottom:22px;translate:-50% 0;display:flex;align-items:center;gap:8px;background:var(--sheet);border:1px solid var(--line-2);box-shadow:0 14px 40px rgba(30,24,14,.18);border-radius:14px;padding:8px 8px 8px 18px;font-size:13.5px;z-index:20;animation:rise .2s}
|
||||
.savebar #savebar-text{margin-right:10px;color:var(--ink-2)}
|
||||
.savebar #savebar-text.bad{color:var(--seal)}
|
||||
@keyframes rise{from{translate:-50% 14px;opacity:0}}
|
||||
.diff{list-style:none;padding:0;margin:12px 0 0;max-height:50vh;overflow:auto;font-size:13px}
|
||||
.diff li{padding:8px 0;border-top:1px solid var(--line)}
|
||||
.diff li:first-child{border-top:0}
|
||||
.diff .from{color:var(--seal);text-decoration:line-through;font:12px var(--mono)}
|
||||
.diff .to{color:var(--moss);font:12px var(--mono)}
|
||||
.diff small{display:block;color:var(--muted);font:11px var(--mono)}
|
||||
|
||||
dialog.ask{border:1px solid var(--line);border-radius:16px;padding:26px 26px 20px;width:min(460px,calc(100vw - 32px));background:var(--sheet);color:var(--ink);box-shadow:0 24px 70px rgba(20,16,10,.28)}
|
||||
dialog.ask::backdrop{background:rgba(26,22,16,.38);backdrop-filter:blur(2px)}
|
||||
dialog.ask h3{margin:0 0 8px;font-size:17px}
|
||||
dialog.ask p{margin:0;color:var(--ink-2);font-size:13.5px}
|
||||
.ask-value{font:500 30px var(--num);letter-spacing:.07em;margin:14px 0 4px;padding:10px 0;text-align:center;border-block:1.5px dashed var(--line-2)}
|
||||
.ask-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:22px}
|
||||
|
||||
.toast{position:fixed;left:50%;bottom:28px;translate:-50% 12px;opacity:0;background:var(--ink);color:var(--paper);padding:7px 16px;border-radius:999px;font-size:13px;pointer-events:none;transition:all .2s;z-index:30}
|
||||
.toast.show{opacity:1;translate:-50% 0}
|
||||
|
||||
@media (max-width:920px){
|
||||
.top{flex-wrap:wrap;gap:12px 20px}
|
||||
.tabs{order:3;flex-basis:100%}
|
||||
.work,.config-layout{grid-template-columns:1fr}
|
||||
.side,.doc-nav{position:static}
|
||||
.recipient{grid-template-columns:1fr}
|
||||
.recipient-side{justify-self:stretch;align-items:stretch}
|
||||
.items{max-height:50vh}
|
||||
.cfield{grid-template-columns:1fr}
|
||||
.cfield .label{padding-top:0}
|
||||
}
|
||||
@media (max-width:560px){
|
||||
.top,.desk{padding-left:14px;padding-right:14px}
|
||||
.item{grid-template-columns:minmax(0,1fr) 72px}.item .c{display:none}
|
||||
.keys{display:none}
|
||||
.roster-head{flex-direction:column;align-items:stretch}.roster-head .search{width:auto}
|
||||
.savebar{left:12px;right:12px;translate:none;flex-wrap:wrap}
|
||||
}
|
||||
.chip-add{width:180px!important;padding:3px 10px!important;border-radius:999px!important;font-size:12.5px}
|
||||
.chips .muted{font-size:12px;margin-left:4px}
|
||||
@@ -0,0 +1,735 @@
|
||||
'use strict';
|
||||
const $ = id => document.getElementById(id);
|
||||
const state = {session: null, players: [], view: ''};
|
||||
|
||||
/* ---------- 通用 ---------- */
|
||||
const errorText = {
|
||||
unauthorized: '登录已过期,请重新登录。', forbidden: '没有权限执行这个操作。', csrf: '页面已过期,请刷新后重试。',
|
||||
rate_limited: '尝试太频繁,请稍后再试。', expired: '登录已过期,请重新开始。', rejected: '登录被拒绝或已取消。',
|
||||
not_granted: '这个游戏账号还没有管理台权限,请联系服主在“玩家”页授权。', not_found: '玩家不存在或已停用。',
|
||||
invalid_item: '这件物品不在可寄送目录中。', invalid_count: '数量需在 1 到 2,147,483,647 之间。', invalid_text: '邮件标题和正文都不能为空。',
|
||||
read_only: '该文件对服务端只读。', unavailable: '服务暂不可用,请稍后再试。', invalid: '请求无效。',
|
||||
unsupported: '这台服务器使用本地认证,请用服务端启动时打印的一次性链接登录。',
|
||||
};
|
||||
async function api(path, {method = 'GET', body, headers = {}} = {}) {
|
||||
const h = {...headers};
|
||||
if (method !== 'GET') {
|
||||
h['X-BD2-Console'] = '1';
|
||||
if (state.session && state.session.csrf) h['X-CSRF-Token'] = state.session.csrf;
|
||||
}
|
||||
if (body !== undefined && typeof body !== 'string') { h['Content-Type'] = 'application/json'; body = JSON.stringify(body); }
|
||||
const response = await fetch('api/' + path, {method, headers: h, body, credentials: 'same-origin'});
|
||||
const text = await response.text();
|
||||
let value = null;
|
||||
if (text) { try { value = JSON.parse(text); } catch { value = null; } }
|
||||
if (response.status === 401 && path !== 'session') { boot(); }
|
||||
if (!response.ok && response.status !== 202) {
|
||||
const error = new Error((value && errorText[value.code]) || (value && value.error) || '请求失败(' + response.status + ')');
|
||||
error.status = response.status; error.code = value && value.code; error.value = value;
|
||||
throw error;
|
||||
}
|
||||
return {status: response.status, value};
|
||||
}
|
||||
function esc(value) { const e = document.createElement('span'); e.textContent = value == null ? '' : String(value); return e.innerHTML.replace(/"/g, '"'); }
|
||||
function el(tag, attrs = {}, ...children) {
|
||||
const node = document.createElement(tag);
|
||||
for (const [key, value] of Object.entries(attrs)) {
|
||||
if (value == null || value === false) continue;
|
||||
if (key === 'class') node.className = value;
|
||||
else if (key === 'text') node.textContent = value;
|
||||
else if (key.startsWith('on')) node.addEventListener(key.slice(2), value);
|
||||
else if (value === true) node.setAttribute(key, '');
|
||||
else node.setAttribute(key, value);
|
||||
}
|
||||
for (const child of children.flat()) if (child != null && child !== false) node.append(child.nodeType ? child : document.createTextNode(child));
|
||||
return node;
|
||||
}
|
||||
function say(node, text, tone = '') { node.textContent = text; node.className = 'status' + (tone ? ' ' + tone : ''); }
|
||||
let toastTimer;
|
||||
function toast(text) { const t = $('toast'); t.textContent = text; t.classList.add('show'); clearTimeout(toastTimer); toastTimer = setTimeout(() => t.classList.remove('show'), 1800); }
|
||||
async function copy(text, label) { try { await navigator.clipboard.writeText(text); toast(label + '已复制'); } catch { toast('复制失败,请手动选择'); } }
|
||||
function ask({title, body, extra = null, ok = '确定', danger = false}) {
|
||||
const dialog = $('ask');
|
||||
$('ask-title').textContent = title; $('ask-body').textContent = body;
|
||||
$('ask-extra').replaceChildren(...(extra ? [extra] : []));
|
||||
$('ask-ok').textContent = ok; $('ask-ok').classList.toggle('seal', true);
|
||||
return new Promise(resolve => {
|
||||
const done = answer => { $('ask-ok').onclick = $('ask-cancel').onclick = dialog.oncancel = null; dialog.close(); resolve(answer); };
|
||||
$('ask-ok').onclick = () => done(true); $('ask-cancel').onclick = () => done(false);
|
||||
dialog.oncancel = event => { event.preventDefault(); done(false); };
|
||||
dialog.showModal(); (danger ? $('ask-cancel') : $('ask-ok')).focus();
|
||||
});
|
||||
}
|
||||
const clone = value => value === undefined ? undefined : JSON.parse(JSON.stringify(value));
|
||||
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
||||
const fmt = n => Number(n).toLocaleString('zh-CN');
|
||||
const playerLabel = p => p ? (p.uid ? 'UID ' + p.uid : '') + (p.name ? ' · ' + p.name : '') : '';
|
||||
|
||||
/* ---------- 登录与路由 ---------- */
|
||||
let loginTimer;
|
||||
async function boot() {
|
||||
clearTimeout(loginTimer);
|
||||
try {
|
||||
state.session = (await api('session')).value;
|
||||
} catch (error) {
|
||||
showOnly('sign-in'); say($('sign-in-status'), error.message, 'err'); return;
|
||||
}
|
||||
if (!state.session.signed_in) return showSignIn();
|
||||
$('tabs').hidden = false; $('account').hidden = false;
|
||||
const owner = state.session.role === 'owner';
|
||||
document.querySelectorAll('[data-owner]').forEach(a => { a.hidden = !owner; });
|
||||
const player = state.session.player;
|
||||
$('account-name').textContent = player ? playerLabel(player) + (owner ? '(服主)' : '') : '服主';
|
||||
await loadPlayers();
|
||||
route();
|
||||
}
|
||||
function showOnly(view) {
|
||||
document.querySelectorAll('.view').forEach(v => { v.hidden = v.id !== 'view-' + view; });
|
||||
document.querySelectorAll('#tabs a').forEach(a => { if (a.dataset.view === view) a.setAttribute('aria-current', 'page'); else a.removeAttribute('aria-current'); });
|
||||
}
|
||||
function showSignIn() {
|
||||
$('tabs').hidden = true; $('account').hidden = true; showOnly('sign-in');
|
||||
const providers = state.session.providers || [];
|
||||
if (state.session.mode !== 'oauth' || !providers.length) {
|
||||
$('sign-in-lead').textContent = '这台服务器使用本地认证。请打开服务端启动时在控制台打印的一次性登录链接。';
|
||||
$('providers').replaceChildren(); return;
|
||||
}
|
||||
$('sign-in-lead').textContent = '使用你的游戏账号登录。服主账号拥有全部权限,其他玩家需要服主授权。';
|
||||
const names = {discord: 'Discord', google: 'Google'};
|
||||
$('providers').replaceChildren(...providers.map(p => el('button', {type: 'button', class: 'btn' + (p === providers[0] ? ' seal' : ''), onclick: () => startLogin(p)}, '使用 ' + (names[p] || p) + ' 登录')));
|
||||
}
|
||||
async function startLogin(provider) {
|
||||
const popup = window.open('about:blank', 'bd2-console-login');
|
||||
say($('sign-in-status'), '正在打开登录页面……');
|
||||
try {
|
||||
const {value} = await api('login/start', {method: 'POST', body: {provider}});
|
||||
if (popup) { popup.opener = null; popup.location.href = value.start_url; say($('sign-in-status'), '请在新窗口完成登录,完成后这里会自动进入。'); }
|
||||
else { $('sign-in-status').replaceChildren('浏览器拦截了新窗口,请点击:', el('a', {href: value.start_url, target: '_blank', rel: 'noopener'}, '打开登录页面')); }
|
||||
pollLogin(value.poll_interval_ms || 2000);
|
||||
} catch (error) { if (popup) popup.close(); say($('sign-in-status'), error.message, 'err'); }
|
||||
}
|
||||
async function pollLogin(interval) {
|
||||
try {
|
||||
const result = await api('login/poll', {method: 'POST'});
|
||||
if (result.status === 202) { loginTimer = setTimeout(() => pollLogin(interval), interval); return; }
|
||||
say($('sign-in-status'), '登录成功。', 'ok'); boot();
|
||||
} catch (error) { say($('sign-in-status'), error.message, 'err'); }
|
||||
}
|
||||
$('logout').onclick = async () => {
|
||||
if (config.dirty() && !await ask({title: '放弃未保存的配置?', body: '退出会丢弃尚未保存的配置改动。', ok: '退出', danger: true})) return;
|
||||
config.reset();
|
||||
try { await api('logout', {method: 'POST'}); } catch {}
|
||||
state.session = null; boot();
|
||||
};
|
||||
let currentView = '';
|
||||
async function route() {
|
||||
if (!state.session || !state.session.signed_in) return;
|
||||
let view = (location.hash || '#mail').slice(1);
|
||||
if (!['mail', 'players', 'config'].includes(view) || (view !== 'mail' && state.session.role !== 'owner')) view = 'mail';
|
||||
if (currentView === 'config' && view !== 'config' && config.dirty()) {
|
||||
if (!await ask({title: '离开前保存配置?', body: '有尚未保存的配置改动。离开后改动会保留在本页,直到刷新或退出。', ok: '仍然离开'})) { history.replaceState(null, '', '#config'); return; }
|
||||
}
|
||||
currentView = view; showOnly(view);
|
||||
if (view === 'mail') mailTool.open();
|
||||
if (view === 'players') roster.open();
|
||||
if (view === 'config') config.open();
|
||||
}
|
||||
window.addEventListener('hashchange', route);
|
||||
window.addEventListener('beforeunload', event => { if (config.dirty()) { event.preventDefault(); event.returnValue = ''; } });
|
||||
|
||||
async function loadPlayers() {
|
||||
try { state.players = (await api('players')).value.players; } catch (error) { state.players = []; toast(error.message); }
|
||||
}
|
||||
|
||||
/* ---------- 邮件发放 ---------- */
|
||||
const categoryNames = {currency: '货币(直接入账)', resource: '资源', food: '料理', cooking: '烹饪配方', random_box: '随机箱', quest_item: '任务物品', use_item: '使用物品', collection: '收藏品', my_room: '我的房间物品', instant_use: '即时使用物品'};
|
||||
const mailTool = (() => {
|
||||
let all = [], cats = [], category = '', view = [], cursor = -1, chosen = null, byKey = new Map(), target = null, loaded = false, submitting = false, logCount = 0;
|
||||
const keyOf = x => x.element_type + ':' + x.id;
|
||||
const catName = x => categoryNames[x.category] || x.category;
|
||||
function details(x) {
|
||||
if (x.category === 'currency') return '邮件领取后直接叠加到账户余额,不生成背包物品。';
|
||||
if (!x.source_boxes) return '';
|
||||
const parts = ['直接发放此物品(无需开箱)'];
|
||||
if (x.original_name) parts.push('原始资源名:' + x.original_name);
|
||||
if (x.box_name) parts.push('确定性箱名称:' + x.box_name);
|
||||
if (x.product_name) parts.push('商品名:' + x.product_name);
|
||||
const boxes = x.source_boxes.slice(0, 4).join('、') + (x.source_boxes.length > 4 ? ' 等 ' + x.source_boxes.length + ' 个' : '');
|
||||
parts.push('固定箱映射:' + boxes);
|
||||
return parts.join(';');
|
||||
}
|
||||
function highlight(text, term) {
|
||||
if (!term) return esc(text);
|
||||
const at = text.toLowerCase().indexOf(term);
|
||||
if (at < 0) return esc(text);
|
||||
return esc(text.slice(0, at)) + '<mark>' + esc(text.slice(at, at + term.length)) + '</mark>' + esc(text.slice(at + term.length));
|
||||
}
|
||||
const subline = x => x.aliases && x.aliases.length ? '又名 ' + x.aliases.join('、') : details(x);
|
||||
function buildCategories() {
|
||||
const counts = new Map();
|
||||
all.forEach(x => counts.set(x.category, (counts.get(x.category) || 0) + 1));
|
||||
cats = [['', '全部', all.length], ...[...counts].map(([key, n]) => [key, categoryNames[key] || key, n])];
|
||||
$('cats').innerHTML = cats.map(([value, label, n], i) => `<button type="button" class="chip" data-i="${i}" aria-pressed="${value === category}">${esc(label)}<small>${n}</small></button>`).join('');
|
||||
}
|
||||
$('cats').onclick = event => {
|
||||
const chip = event.target.closest('.chip'); if (!chip) return;
|
||||
category = cats[+chip.dataset.i][0];
|
||||
$('cats').querySelectorAll('.chip').forEach(c => c.setAttribute('aria-pressed', c === chip));
|
||||
render(); $('q').focus();
|
||||
};
|
||||
function render() {
|
||||
const terms = $('q').value.toLowerCase().trim().split(/\s+/).filter(Boolean);
|
||||
const matches = all.filter(x => (!category || x.category === category) && terms.every(t => x._h.includes(t)));
|
||||
view = matches.slice(0, 500); cursor = terms.length && view.length ? 0 : -1;
|
||||
$('count').textContent = all.length ? `${matches.length === all.length ? '共' : '匹配 ' + matches.length + ' /'} ${all.length} 项${matches.length > view.length ? ' · 显示前 ' + view.length + ' 项' : ''}` : '';
|
||||
const term = terms.reduce((a, b) => b.length > a.length ? b : a, ''), picked = chosen && keyOf(chosen);
|
||||
$('items').innerHTML = view.map((x, i) => {
|
||||
const sub = subline(x);
|
||||
return `<li role="option" id="opt-${i}" data-i="${i}" class="item${keyOf(x) === picked ? ' chosen' : ''}" aria-selected="${keyOf(x) === picked}"><span class="n">${highlight(x.name, term)}</span><span class="c">${esc(catName(x))}</span><span class="i"><i>${x.element_type}·</i>${highlight(String(x.id), term)}</span>${sub ? `<span class="d" title="${esc(details(x) || sub)}">${highlight(sub, term)}</span>` : ''}</li>`;
|
||||
}).join('') || `<li class="empty">没有匹配的物品${category ? `<br><small>当前只看「${esc(categoryNames[category] || category)}」,可以切回「全部」试试</small>` : ''}</li>`;
|
||||
paintCursor(true); renderRecent(!terms.length);
|
||||
}
|
||||
function paintCursor(scroll) {
|
||||
const old = $('items').querySelector('.active'); if (old) old.classList.remove('active');
|
||||
const row = $('opt-' + cursor);
|
||||
if (row) { row.classList.add('active'); if (scroll) row.scrollIntoView({block: 'nearest'}); }
|
||||
$('q').setAttribute('aria-activedescendant', row ? row.id : '');
|
||||
}
|
||||
$('items').onmousemove = event => { const row = event.target.closest('[data-i]'); if (row && +row.dataset.i !== cursor) { cursor = +row.dataset.i; paintCursor(false); } };
|
||||
$('items').onclick = event => { const row = event.target.closest('[data-i]'); if (row) pick(view[+row.dataset.i]); };
|
||||
$('q').oninput = render;
|
||||
$('q').onkeydown = event => {
|
||||
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { event.preventDefault(); if (!view.length) return; cursor = (cursor + (event.key === 'ArrowDown' ? 1 : -1) + view.length) % view.length; paintCursor(true); }
|
||||
else if (event.key === 'Enter') { event.preventDefault(); const x = view[Math.max(cursor, 0)]; if (x) pick(x); }
|
||||
else if (event.key === 'Escape') { event.preventDefault(); if ($('q').value) { $('q').value = ''; render(); } else $('q').blur(); }
|
||||
};
|
||||
const recentKey = 'bd2-console-recent';
|
||||
function recentList() { try { return JSON.parse(localStorage.getItem(recentKey)) || []; } catch { return []; } }
|
||||
function remember(x) { try { localStorage.setItem(recentKey, JSON.stringify([keyOf(x), ...recentList().filter(k => k !== keyOf(x))].slice(0, 8))); } catch {} }
|
||||
function renderRecent(visible) {
|
||||
const items = recentList().map(k => byKey.get(k)).filter(Boolean), box = $('recent');
|
||||
box.hidden = !visible || !items.length; if (box.hidden) return;
|
||||
box.replaceChildren(box.firstElementChild, ...items.map(x => el('button', {type: 'button', title: catName(x) + ' · ' + keyOf(x), onclick: () => pick(x)}, x.name)));
|
||||
}
|
||||
function pick(x) {
|
||||
chosen = x; paintParcel();
|
||||
$('items').querySelectorAll('.item').forEach(row => { const on = keyOf(view[+row.dataset.i]) === keyOf(x); row.classList.toggle('chosen', on); row.setAttribute('aria-selected', on); });
|
||||
say($('status'), ''); $('quantity').focus(); $('quantity').select();
|
||||
}
|
||||
function unpick() { chosen = null; paintParcel(); $('items').querySelectorAll('.chosen').forEach(row => { row.classList.remove('chosen'); row.setAttribute('aria-selected', false); }); $('q').focus(); }
|
||||
function paintParcel() {
|
||||
const parcel = $('parcel'); parcel.classList.toggle('empty', !chosen);
|
||||
if (!chosen) { parcel.innerHTML = '<p>从目录中挑一件物品放进来<br><span>或按 <kbd>/</kbd> 直接搜索</span></p>'; parcel.onclick = () => $('q').focus(); return; }
|
||||
parcel.onclick = null;
|
||||
const d = details(chosen);
|
||||
parcel.innerHTML = `<div class="p-name">${esc(chosen.name)}</div><div class="p-meta"><span>${esc(catName(chosen))}</span><code>类型 ${chosen.element_type} · ID ${chosen.id}</code></div>${d ? `<p class="p-detail">${esc(d)}</p>` : ''}<button type="button" class="x" aria-label="移出包裹单" title="移出包裹单">×</button>`;
|
||||
parcel.querySelector('.x').onclick = unpick;
|
||||
}
|
||||
const units = {k: 1e3, '千': 1e3, w: 1e4, '万': 1e4, m: 1e6, '百万': 1e6, '亿': 1e8};
|
||||
function quantity() { const m = $('quantity').value.replace(/[\s,,_]/g, '').toLowerCase().match(/^(\d+(?:\.\d+)?)(k|千|w|万|m|百万|亿)?$/); return m ? Math.round(parseFloat(m[1]) * (units[m[2]] || 1)) : NaN; }
|
||||
function checkQuantity() {
|
||||
const n = quantity(), input = $('quantity'), hint = $('qty-hint'); let problem = '';
|
||||
if (!Number.isInteger(n) || n < 1) problem = '请输入正整数'; else if (n > 2147483647) problem = '不能超过 2,147,483,647';
|
||||
input.setCustomValidity(problem);
|
||||
const typed = input.value.trim() !== '';
|
||||
hint.classList.toggle('err', !!problem && typed);
|
||||
hint.textContent = problem && typed ? problem : !problem && String(n) !== input.value.trim() ? '= ' + fmt(n) : '支持 5k、2w、3万';
|
||||
return problem ? NaN : n;
|
||||
}
|
||||
$('quantity').oninput = checkQuantity;
|
||||
$('quantity').onkeydown = event => {
|
||||
if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return;
|
||||
event.preventDefault(); const n = quantity() || 0, step = event.shiftKey ? 10 : 1;
|
||||
$('quantity').value = Math.max(1, n + (event.key === 'ArrowUp' ? step : -step)); checkQuantity();
|
||||
};
|
||||
$('presets').onclick = event => { const b = event.target.closest('[data-q]'); if (!b) return; const add = +b.dataset.q; $('quantity').value = event.shiftKey ? (quantity() || 0) + add : add; checkQuantity(); $('quantity').focus(); };
|
||||
$('title').oninput = () => { $('letter-peek').textContent = $('title').value || '(无标题)'; };
|
||||
document.addEventListener('keydown', event => {
|
||||
if ($('ask').open || currentView !== 'mail' || $('tools').disabled) return;
|
||||
const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement.tagName);
|
||||
if (event.key === '/' && !typing && !event.ctrlKey && !event.metaKey && !event.altKey) { event.preventDefault(); $('q').focus(); $('q').select(); }
|
||||
else if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) { event.preventDefault(); $('form').requestSubmit(); }
|
||||
});
|
||||
function addLog(entry) {
|
||||
const li = el('li', {},
|
||||
el('span', {class: 'what'}, el('b', {}, entry.item.name), ' × ' + fmt(entry.count)),
|
||||
el('span', {class: 'meta'}, entry.time + ' · 寄往 ' + playerLabel(entry.player)),
|
||||
el('button', {type: 'button', class: 'again', title: '把这件物品和数量重新放进包裹单', onclick: () => { pick(entry.item); $('quantity').value = entry.count; checkQuantity(); $('quantity').select(); }}, '再来一份'),
|
||||
el('button', {type: 'button', class: 'ident', title: '点击复制发放标识', onclick: () => copy(entry.identity, '发放标识')}, entry.identity));
|
||||
$('log').prepend(li); $('log-empty').hidden = true; $('log-count').textContent = ++logCount + ' 件';
|
||||
}
|
||||
function showRecipient(player) {
|
||||
const display = $('uid-display');
|
||||
display.textContent = player ? player.uid || '——' : '——'; display.classList.toggle('none', !player);
|
||||
$('slip-uid').textContent = player ? player.uid : '—';
|
||||
$('recipient-note').textContent = player ? (player.name || '') + (state.session.role === 'owner' ? '' : '(只能给自己寄件)') : '还没有可以寄件的玩家。玩家首次登录游戏后会出现在这里。';
|
||||
}
|
||||
$('uid-display').onclick = () => { if (target && target.uid) copy(target.uid, 'UID '); };
|
||||
function showInventory(value) {
|
||||
const on = value.unlimited, l = value.limits;
|
||||
$('unlimited-inventory').checked = on;
|
||||
$('inventory-limits').innerHTML = `<span></span><span class="h">道具</span><span class="h">装备</span><span class="lab${on ? '' : ' on'}">普通容量</span><b>${l.items.default}</b><b>${l.equipment.default}</b><span class="lab${on ? ' on' : ''}">无限模式</span><b>${l.items.maximum}</b><b>${l.equipment.maximum}</b>`;
|
||||
}
|
||||
async function select(accountID) {
|
||||
target = state.players.find(p => p.account_id === accountID) || null;
|
||||
showRecipient(target); $('tools').disabled = true; say($('status'), ''); say($('inventory-status'), '');
|
||||
$('lock-note').textContent = target ? '正在读取玩家设置……' : '没有可以寄件的玩家';
|
||||
if (!target) return;
|
||||
try {
|
||||
const requested = target.account_id;
|
||||
const {value} = await api('players/' + encodeURIComponent(requested) + '/inventory');
|
||||
if (target && target.account_id === requested) { showInventory(value); $('tools').disabled = !loaded; $('lock-note').textContent = loaded ? '' : '正在读取物品目录……'; }
|
||||
} catch (error) { $('lock-note').textContent = error.message; }
|
||||
}
|
||||
$('player').onchange = () => select($('player').value);
|
||||
$('form').onsubmit = async event => {
|
||||
event.preventDefault(); if (submitting || !target) return;
|
||||
if (!chosen) { say($('status'), '请先在目录中挑选要寄出的物品。', 'err'); const parcel = $('parcel'); parcel.classList.remove('shake'); void parcel.offsetWidth; parcel.classList.add('shake'); $('q').focus(); return; }
|
||||
const count = checkQuantity();
|
||||
if (!$('title').checkValidity() || !$('body').checkValidity()) $('letter').open = true;
|
||||
if (!$('form').reportValidity()) return;
|
||||
submitting = true; const send = $('grant-submit'), player = target, item = chosen; send.disabled = true; $('player').disabled = true;
|
||||
try {
|
||||
const {value} = await api('players/' + encodeURIComponent(player.account_id) + '/mail', {method: 'POST', body: {element_type: item.element_type, id: item.id, count, title: $('title').value, body: $('body').value}});
|
||||
say($('status'), `已寄往 UID ${player.uid}。玩家刷新游戏邮箱即可领取,无需重启服务端。`, 'ok');
|
||||
addLog({item, count, player, identity: value.identity, time: new Date().toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'})}); remember(item);
|
||||
send.classList.add('done'); send.firstChild.textContent = '已寄出';
|
||||
setTimeout(() => { send.classList.remove('done'); send.firstChild.textContent = '寄出'; }, 1400);
|
||||
} catch (error) { say($('status'), error.message, 'err'); }
|
||||
finally { submitting = false; send.disabled = false; $('player').disabled = false; }
|
||||
};
|
||||
$('unlimited-inventory').onchange = async event => {
|
||||
const box = event.target, old = !box.checked; box.disabled = true; $('player').disabled = true;
|
||||
try {
|
||||
const {value} = await api('players/' + encodeURIComponent(target.account_id) + '/inventory', {method: 'PUT', body: {unlimited: box.checked}});
|
||||
showInventory(value); target.unlimited_inventory = value.unlimited;
|
||||
say($('inventory-status'), `已保存 UID ${target.uid} 的设置。玩家重新登录游戏后生效。`, 'ok');
|
||||
} catch (error) { box.checked = old; say($('inventory-status'), error.message, 'err'); }
|
||||
finally { box.disabled = false; $('player').disabled = false; }
|
||||
};
|
||||
async function loadCatalog() {
|
||||
try {
|
||||
all = (await api('catalog')).value.items;
|
||||
all.forEach(x => { x._h = [x.id, x.element_type, keyOf(x), x.name, catName(x), ...(x.aliases || []), details(x)].join(' ').toLowerCase(); });
|
||||
byKey = new Map(all.map(x => [keyOf(x), x])); buildCategories(); render(); loaded = true;
|
||||
if (target && $('lock-note').textContent === '正在读取物品目录……') { $('tools').disabled = false; }
|
||||
} catch (error) { $('items').innerHTML = `<li class="empty">${esc(error.message)}</li>`; }
|
||||
}
|
||||
return {
|
||||
open(accountID) {
|
||||
paintParcel();
|
||||
const owner = state.session.role === 'owner';
|
||||
const usable = state.players.filter(p => p.active);
|
||||
$('player-selector').hidden = !owner || usable.length < 2;
|
||||
$('player').replaceChildren(...usable.map(p => new Option(playerLabel(p) + (p.owner ? '(服主)' : ''), p.account_id)));
|
||||
const self = state.session.player && state.session.player.account_id;
|
||||
const initial = accountID || (target && usable.some(p => p.account_id === target.account_id) ? target.account_id : null) || (usable.some(p => p.account_id === self) ? self : usable[0] && usable[0].account_id);
|
||||
if (initial) $('player').value = initial;
|
||||
if (!loaded && !all.length) loadCatalog();
|
||||
select(initial || '');
|
||||
},
|
||||
};
|
||||
})();
|
||||
|
||||
/* ---------- 玩家 ---------- */
|
||||
const roster = (() => {
|
||||
function render() {
|
||||
const q = $('player-q').value.trim().toLowerCase();
|
||||
const rows = state.players.filter(p => !q || (p.uid + ' ' + p.name).toLowerCase().includes(q));
|
||||
$('roster').replaceChildren(...rows.map(p => {
|
||||
const toggle = (checked, disabled, onchange, label) => el('label', {class: 'switch', title: label}, el('input', {type: 'checkbox', role: 'switch', checked, disabled, 'aria-label': label, onchange}), el('span', {class: 'track', 'aria-hidden': 'true'}));
|
||||
const memberSwitch = p.owner ? el('span', {class: 'muted'}, '—') : toggle(p.member, !p.active || state.session.mode !== 'oauth', event => setMember(p, event.target), '管理台成员');
|
||||
return el('tr', {class: p.active ? '' : 'inactive'},
|
||||
el('td', {class: 'uid-cell'}, p.uid || '—'),
|
||||
el('td', {}, p.name || ''),
|
||||
el('td', {}, p.owner ? el('span', {class: 'pill owner'}, '服主') : null, p.member ? el('span', {class: 'pill member'}, '成员') : null, p.active ? null : el('span', {class: 'pill'}, '已停用')),
|
||||
el('td', {class: 'c'}, memberSwitch),
|
||||
el('td', {class: 'c'}, toggle(p.unlimited_inventory, !p.active, event => setInventory(p, event.target), '无限背包容量')),
|
||||
el('td', {class: 'act'}, p.active ? el('button', {type: 'button', class: 'linkish', onclick: () => { location.hash = '#mail'; setTimeout(() => mailTool.open(p.account_id)); }}, '给 TA 寄件 →') : null));
|
||||
}));
|
||||
if (!rows.length) $('roster').replaceChildren(el('tr', {}, el('td', {colspan: 6, class: 'muted'}, state.players.length ? '没有匹配的玩家' : '还没有玩家。玩家首次登录游戏后会出现在这里。')));
|
||||
}
|
||||
async function setMember(player, box) {
|
||||
if (!box.checked && !await ask({title: '撤销管理台权限?', body: `UID ${player.uid} 将立即退出管理台,之后需要重新授权才能登录。`, ok: '撤销', danger: true})) { box.checked = true; return; }
|
||||
box.disabled = true;
|
||||
try {
|
||||
await api('players/' + encodeURIComponent(player.account_id) + '/member', {method: 'PUT', body: {member: box.checked}});
|
||||
player.member = box.checked; render();
|
||||
toast(box.checked ? `已授权 UID ${player.uid},对方可用游戏账号登录管理台` : `已撤销 UID ${player.uid} 的权限`);
|
||||
} catch (error) { box.checked = !box.checked; say($('roster-status'), error.message, 'err'); }
|
||||
finally { box.disabled = false; }
|
||||
}
|
||||
async function setInventory(player, box) {
|
||||
box.disabled = true;
|
||||
try {
|
||||
const {value} = await api('players/' + encodeURIComponent(player.account_id) + '/inventory', {method: 'PUT', body: {unlimited: box.checked}});
|
||||
player.unlimited_inventory = value.unlimited; toast(`UID ${player.uid} ${value.unlimited ? '已开启' : '已关闭'}无限背包,重新登录游戏后生效`);
|
||||
} catch (error) { box.checked = !box.checked; say($('roster-status'), error.message, 'err'); }
|
||||
finally { box.disabled = false; }
|
||||
}
|
||||
$('player-q').oninput = render;
|
||||
return {async open() { say($('roster-status'), ''); await loadPlayers(); render(); }};
|
||||
})();
|
||||
|
||||
/* ---------- 服务器配置(通用编辑器) ---------- */
|
||||
const config = (() => {
|
||||
let docs = [], current = '', drafts = {}, checks = {}, checkTimer, server = null;
|
||||
const doc = () => docs.find(d => d.name === current);
|
||||
const fields = d => d.schema.sections.flatMap(s => s.fields);
|
||||
const dirtyDoc = d => drafts[d.name] !== undefined && !same(drafts[d.name], d.view.value);
|
||||
function getPath(object, path) { return path.split('.').reduce((value, key) => value == null ? undefined : value[key], object); }
|
||||
function setPath(object, path, value) {
|
||||
const keys = path.split('.'); let node = object;
|
||||
keys.slice(0, -1).forEach(key => { if (node[key] == null || typeof node[key] !== 'object') node[key] = {}; node = node[key]; });
|
||||
if (value === undefined) delete node[keys.at(-1)]; else node[keys.at(-1)] = value;
|
||||
}
|
||||
function holds(when, value) {
|
||||
if (!when) return true;
|
||||
const found = getPath(value, when.path);
|
||||
return when.in.some(candidate => same(found, candidate)) !== !!when.not;
|
||||
}
|
||||
// 把问题路径对应到字段:去掉列表下标,按 * 匹配映射键。
|
||||
function fieldFor(d, path) {
|
||||
const bare = path.replace(/\[\d+\]/g, '');
|
||||
const parts = bare.split('.');
|
||||
return fields(d).find(f => {
|
||||
const pattern = f.path.split('.');
|
||||
return pattern.length === parts.length && pattern.every((p, i) => p === '*' || p === parts[i]);
|
||||
}) || fields(d).filter(f => bare.startsWith(f.path + '.') || bare === f.path).sort((a, b) => b.path.length - a.path.length)[0];
|
||||
}
|
||||
const phrases = {
|
||||
'must be a bare host name without scheme, path or port': '只填主机名,不带协议、路径或端口',
|
||||
'must be host:port': '格式应为 主机:端口,例如 0.0.0.0:8444',
|
||||
'plaintext realtime listeners must bind loopback': '明文模式只能监听回环地址',
|
||||
'plaintext realtime public host must be loopback': '明文模式的公开地址必须是回环 IP',
|
||||
'is required unless plaintext loopback development is enabled': '未启用本机明文模式时必填',
|
||||
'must be a nonempty path': '路径不能为空',
|
||||
'is required by an active provider': '启用第三方审核时必填',
|
||||
'is required by the Azure provider': 'Azure 需要填写这一项',
|
||||
'must be a lowercase identifier': '只能使用小写字母、数字和下划线,并以字母开头',
|
||||
'local mode must not configure OAuth': '本地模式下不能配置这一项',
|
||||
'is required in oauth mode': 'OAuth 模式下必填',
|
||||
'oauth mode requires at least one provider': '至少启用一个登录提供方',
|
||||
'must be an absolute origin without path, query, fragment, or user info': '应为不带路径的根地址,例如 https://game.example.com',
|
||||
'must use HTTPS except on localhost': '除 localhost 外必须使用 HTTPS',
|
||||
'must be a positive Go duration': '应为正的时长,例如 15m、720h',
|
||||
'official mode must use the versioned official resource origin': '官方模式只能使用官方地址',
|
||||
'is required in server mode': '自建资源源模式下必填',
|
||||
'must be an absolute HTTP(S) URL without credentials, query, or fragment': '应为完整的 HTTP(S) 地址,不带账号、查询参数或锚点',
|
||||
'must not have a trailing slash': '末尾不能带斜杠',
|
||||
'must use HTTPS outside loopback development': '除回环地址外必须使用 HTTPS',
|
||||
'is required': '必填', 'must be present': '文件中必须写明这一项',
|
||||
};
|
||||
function describe(problem, field, d) {
|
||||
const m = problem.message || '';
|
||||
const item = (problem.path.match(/\[(\d+)\]$/) || [])[1];
|
||||
const prefix = item !== undefined ? `第 ${+item + 1} 项:` : '';
|
||||
let text;
|
||||
if (problem.rule === 'enum' && field && field.options) text = '只能选择:' + field.options.map(o => o.label).join('、');
|
||||
else if (problem.rule === 'enum' && field && field.keys) text = '不支持这一项';
|
||||
else if (problem.rule === 'range' && field) text = `需为 ${fmt(field.min)} 到 ${fmt(field.max)} 之间的整数`;
|
||||
else if (problem.rule === 'unique') text = '有重复项';
|
||||
else if (problem.rule === 'conflict' && m.startsWith('is fixed to')) { const lock = (d.view.locks || []).find(l => l.path === problem.path); text = '已锁定' + (lock ? ':' + lock.reason : ''); }
|
||||
else if (problem.rule === 'environment') { const env = (m.match(/environment variable (\S+)/) || [])[1]; text = m.includes('32-byte') ? `当前服务端进程中环境变量 ${env} 不是有效的 32 字节 base64 密钥,重启后服务端会拒绝启动。` : `当前服务端进程没有设置环境变量 ${env}。保存后重启前,请先在服务端环境中设置它。`; }
|
||||
else if (problem.rule === 'missing_file') text = '服务端当前读不到这个文件:' + m.replace(/ is not readable by this server process$/, '');
|
||||
else if (problem.rule === 'decode') text = '格式错误:' + m;
|
||||
else text = phrases[m] || m;
|
||||
return prefix + text;
|
||||
}
|
||||
function render() {
|
||||
const d = doc(); if (!d) return;
|
||||
const draft = drafts[d.name], readonly = !d.view.writable;
|
||||
renderNav();
|
||||
const form = $('config-form');
|
||||
const box = el('fieldset', {disabled: readonly});
|
||||
box.append(el('section', {class: 'card doc-head'}, el('h2', {}, d.schema.title), d.schema.summary ? el('p', {}, d.schema.summary) : null,
|
||||
el('div', {class: 'path'}, el('span', {}, d.view.path), d.view.modified ? el('span', {}, '修改于 ' + new Date(d.view.modified).toLocaleString('zh-CN')) : null)));
|
||||
for (const section of d.schema.sections) {
|
||||
const own = section.fields.filter(f => !f.path.includes('*'));
|
||||
if (own.every(f => f.advanced && f.path === 'schema_version')) continue;
|
||||
const card = el('section', {class: 'card section', id: 'sec-' + section.id}, el('h3', {}, section.title), section.help ? el('p', {class: 'help'}, section.help) : null);
|
||||
const basic = own.filter(f => !f.advanced), advanced = own.filter(f => f.advanced);
|
||||
basic.forEach(f => card.append(renderField(d, f, draft)));
|
||||
if (advanced.length) {
|
||||
const details = el('details', {class: 'advanced'}, el('summary', {}, '高级选项'));
|
||||
advanced.forEach(f => details.append(renderField(d, f, draft)));
|
||||
card.append(details);
|
||||
}
|
||||
box.append(card);
|
||||
}
|
||||
form.replaceChildren(box);
|
||||
refresh();
|
||||
}
|
||||
function renderField(d, field, draft) {
|
||||
const value = getPath(draft, field.path);
|
||||
const lock = (d.view.locks || []).find(l => l.path === field.path);
|
||||
const wrap = el('div', {class: 'cfield', 'data-path': field.path});
|
||||
wrap.append(el('div', {class: 'label'}, field.label, el('small', {}, field.path)));
|
||||
const control = el('div', {class: 'control'});
|
||||
const update = next => { setPath(drafts[d.name], field.path, next); refresh(); };
|
||||
control.append(widget(field, value, update, lock, d));
|
||||
if (field.help) control.append(el('p', {class: 'help'}, field.help));
|
||||
control.append(el('div', {class: 'msgs'}));
|
||||
if (lock) control.append(el('p', {class: 'msg lock'}, '🔒 已锁定:' + lock.reason));
|
||||
wrap.append(control);
|
||||
return wrap;
|
||||
}
|
||||
function widget(field, value, update, lock, d) {
|
||||
const disabled = !!lock;
|
||||
if (field.kind === 'bool') {
|
||||
return el('label', {class: 'switch'}, el('input', {type: 'checkbox', role: 'switch', checked: !!value, disabled, onchange: e => update(e.target.checked)}), el('span', {class: 'track', 'aria-hidden': 'true'}), value ? '已开启' : '已关闭');
|
||||
}
|
||||
if (field.options && field.kind !== 'list' && !field.open_options) {
|
||||
const options = field.options.filter(o => o.value !== '' || value === '');
|
||||
const name = 'opt-' + field.path;
|
||||
const help = el('p', {class: 'option-help'});
|
||||
const showHelp = v => { const o = field.options.find(x => same(x.value, v)); help.textContent = o && o.help ? o.help : ''; };
|
||||
showHelp(value);
|
||||
const group = el('div', {class: 'segmented', role: 'radiogroup', 'aria-label': field.label}, options.map(o => el('label', {},
|
||||
el('input', {type: 'radio', name, checked: same(o.value, value), disabled, onchange: () => { update(clone(o.value)); showHelp(o.value); }}), el('span', {}, o.label))));
|
||||
const holder = el('div', {}, group, help);
|
||||
const extra = extras[field.path]; if (extra) holder.append(extra(d));
|
||||
return holder;
|
||||
}
|
||||
if (field.kind === 'integer') {
|
||||
const input = el('input', {inputmode: 'numeric', value: value ?? '', disabled, placeholder: field.placeholder || '',
|
||||
oninput: e => { const raw = e.target.value.trim().replace(/[,,_\s]/g, ''); update(/^-?\d+$/.test(raw) ? Number(raw) : raw); }});
|
||||
return el('div', {class: 'unit-input'}, input, field.min != null ? el('span', {}, `${fmt(field.min)} – ${fmt(field.max)}`) : null);
|
||||
}
|
||||
if (field.kind === 'string') {
|
||||
const mono = ['path', 'env', 'url', 'listen', 'host', 'origin', 'duration', 'identifier'].includes(field.format);
|
||||
return el('div', {class: 'text-input' + (mono ? ' mono' : '')}, el('input', {value: value ?? '', disabled, placeholder: field.placeholder || '', spellcheck: 'false', autocomplete: 'off', oninput: e => update(e.target.value)}));
|
||||
}
|
||||
if (field.kind === 'list' && field.options) return chipList(field, value || [], update, disabled);
|
||||
if (field.kind === 'list') return rowList(field, value || [], update, disabled);
|
||||
if (field.kind === 'map') return mapEditor(field, value || {}, update, disabled, d);
|
||||
return el('code', {}, JSON.stringify(value));
|
||||
}
|
||||
function chipList(field, list, update, disabled) {
|
||||
const holder = el('div', {class: 'chips'});
|
||||
const draw = () => {
|
||||
const custom = list.filter(v => !field.options.some(o => o.value === v));
|
||||
holder.replaceChildren(...field.options.map(o => el('button', {type: 'button', class: 'chip', 'aria-pressed': String(list.includes(o.value)), disabled, title: o.value,
|
||||
onclick: () => { list = list.includes(o.value) ? list.filter(v => v !== o.value) : [...list, o.value]; update(list); draw(); }}, o.label)),
|
||||
...custom.map(v => el('button', {type: 'button', class: 'chip', 'aria-pressed': 'true', disabled, title: '点击移除', onclick: () => { list = list.filter(x => x !== v); update(list); draw(); }}, v + ' ×')),
|
||||
field.open_options && !disabled ? el('input', {class: 'chip-add', placeholder: '其他范围,回车添加', spellcheck: 'false',
|
||||
onkeydown: e => { if (e.key !== 'Enter') return; e.preventDefault(); const v = e.target.value.trim(); if (v && !list.includes(v)) { list = [...list, v]; update(list); draw(); } }}) : null,
|
||||
el('span', {class: 'muted'}, `已选 ${list.length} 项`),
|
||||
!disabled ? el('button', {type: 'button', class: 'linkish', onclick: () => { list = field.options.map(o => o.value); update(list); draw(); }}, '全选') : null);
|
||||
};
|
||||
draw();
|
||||
return holder;
|
||||
}
|
||||
function rowList(field, list, update, disabled) {
|
||||
const holder = el('div', {class: 'rows'});
|
||||
const draw = () => {
|
||||
holder.replaceChildren(...list.map((v, i) => el('div', {class: 'row', 'data-item': i},
|
||||
el('input', {value: v, disabled, spellcheck: 'false', placeholder: field.placeholder || '', oninput: e => { list[i] = e.target.value; update([...list]); }}),
|
||||
disabled ? null : el('button', {type: 'button', class: 'icon-btn', title: '移除', 'aria-label': '移除', onclick: () => { list.splice(i, 1); update([...list]); draw(); }}, '×'))),
|
||||
disabled ? null : el('button', {type: 'button', class: 'add', onclick: () => { list.push(''); update([...list]); draw(); holder.querySelector('.row:last-of-type input').focus(); }}, '+ 添加'),
|
||||
!list.length ? el('span', {class: 'muted'}, '(空)') : null);
|
||||
};
|
||||
draw();
|
||||
return holder;
|
||||
}
|
||||
function mapEditor(field, map, update, disabled, d) {
|
||||
const children = fields(d).filter(f => f.path.startsWith(field.path + '.*.'));
|
||||
const holder = el('div', {class: 'map-keys'});
|
||||
const draw = () => {
|
||||
holder.replaceChildren(...(field.keys || Object.keys(map).map(k => ({value: k, label: k}))).map(k => {
|
||||
const enabled = Object.hasOwn(map, k.value);
|
||||
const entry = el('div', {class: 'map-entry', 'data-key': k.value},
|
||||
el('label', {class: 'switch'}, el('input', {type: 'checkbox', role: 'switch', checked: enabled, disabled, onchange: e => {
|
||||
// 重新启用时恢复文件中已保存的值,避免误关后要重新填写。
|
||||
if (e.target.checked) map[k.value] = clone(getPath(d.view.value, field.path + '.' + k.value)) || Object.fromEntries(children.map(c => [c.path.split('.').at(-1), '']));
|
||||
else delete map[k.value];
|
||||
update({...map}); draw(); }}), el('span', {class: 'track', 'aria-hidden': 'true'}), k.label));
|
||||
if (enabled) {
|
||||
const sub = el('div', {class: 'sub'});
|
||||
children.forEach(c => {
|
||||
const name = c.path.split('.').at(-1), path = field.path + '.' + k.value + '.' + name;
|
||||
sub.append(el('label', {}, c.label), el('div', {class: 'text-input mono', 'data-path': path}, el('input', {value: map[k.value][name] ?? '', disabled, spellcheck: 'false', autocomplete: 'off',
|
||||
oninput: e => { map[k.value][name] = e.target.value; update({...map}); }})), el('div', {class: 'msgs', 'data-msgs': path}));
|
||||
});
|
||||
entry.append(sub);
|
||||
}
|
||||
return entry;
|
||||
}));
|
||||
};
|
||||
draw();
|
||||
return holder;
|
||||
}
|
||||
// 字段专属的小提示:根据当前草稿实时给出例子。
|
||||
const extras = {
|
||||
'purchases.diamond_recharge.currency': d => {
|
||||
const box = el('div', {class: 'example'});
|
||||
box.dataset.example = 'recharge';
|
||||
return box;
|
||||
},
|
||||
};
|
||||
function paintExamples() {
|
||||
const box = document.querySelector('[data-example=recharge]'); if (!box) return;
|
||||
const r = (drafts.game || {}).purchases?.diamond_recharge || {};
|
||||
const n = 100;
|
||||
const text = r.currency === 'gold' ? ['充值 100 付费钻石档位:消耗 ', fmt(n * (r.gold_per_paid_diamond || 0)), ' 金币']
|
||||
: r.currency === 'diamonds' ? ['充值 100 付费钻石档位:消耗 ', fmt(n * (r.diamonds_per_paid_diamond || 0)), ' 普通钻石']
|
||||
: r.currency === 'free' ? ['充值 100 付费钻石档位:', '免费', '']
|
||||
: ['付费钻石充值:', '已禁止', ''];
|
||||
box.replaceChildren(text[0], el('b', {}, text[1]), text[2]);
|
||||
}
|
||||
function refresh() {
|
||||
const d = doc(); if (!d) return;
|
||||
const draft = drafts[d.name];
|
||||
document.querySelectorAll('#config-form .cfield').forEach(node => {
|
||||
const field = fields(d).find(f => f.path === node.dataset.path);
|
||||
node.hidden = !holds(field.when, draft);
|
||||
node.classList.toggle('changed', !same(getPath(draft, field.path), getPath(d.view.value, field.path)));
|
||||
});
|
||||
document.querySelectorAll('#config-form .section').forEach(card => { card.hidden = [...card.querySelectorAll('.cfield')].every(n => n.hidden); });
|
||||
document.querySelectorAll('#config-form .switch').forEach(s => { const input = s.querySelector('input'); const last = s.lastChild; if (last && last.nodeType === 3 && (last.textContent === '已开启' || last.textContent === '已关闭')) last.textContent = input.checked ? '已开启' : '已关闭'; });
|
||||
paintExamples(); renderBar(); renderNav();
|
||||
clearTimeout(checkTimer);
|
||||
checkTimer = setTimeout(check, 300);
|
||||
}
|
||||
async function check() {
|
||||
const d = doc(); if (!d) return;
|
||||
const name = d.name, draft = drafts[name];
|
||||
try {
|
||||
const {value} = await api('config/' + encodeURIComponent(name) + '/check', {method: 'POST', body: draft});
|
||||
if (!same(drafts[name], draft)) return;
|
||||
checks[name] = value; paintMessages(); renderBar(); renderNav(); renderBanners();
|
||||
} catch (error) { toast(error.message); }
|
||||
}
|
||||
function paintMessages() {
|
||||
const d = doc(); if (!d) return;
|
||||
document.querySelectorAll('#config-form .msgs').forEach(n => n.replaceChildren());
|
||||
document.querySelectorAll('#config-form .cfield').forEach(n => n.classList.remove('invalid'));
|
||||
const result = checks[d.name] || {problems: [], advice: []};
|
||||
const place = (problem, tone) => {
|
||||
const field = fieldFor(d, problem.path);
|
||||
const target = document.querySelector(`#config-form [data-msgs="${CSS.escape(problem.path)}"]`) || (field && document.querySelector(`#config-form .cfield[data-path="${CSS.escape(field.path)}"] .msgs`));
|
||||
if (!target) return false;
|
||||
target.append(el('p', {class: 'msg ' + tone}, describe(problem, field, d)));
|
||||
if (tone === 'err') target.closest('.cfield')?.classList.add('invalid');
|
||||
const advanced = target.closest('details.advanced'); if (advanced && tone === 'err') advanced.open = true;
|
||||
return true;
|
||||
};
|
||||
result.problems.forEach(p => place(p, 'err'));
|
||||
result.advice.forEach(p => place(p, 'warn'));
|
||||
}
|
||||
function renderBanners() {
|
||||
const d = doc(); if (!d) return;
|
||||
const banners = [];
|
||||
const pending = docs.filter(x => x.view.pending);
|
||||
if (pending.length) banners.push(el('div', {class: 'banner pending'}, el('div', {}, el('b', {}, '已保存,等待重启生效'),
|
||||
el('p', {}, pending.map(x => x.schema.title).join('、') + ' 的改动已经写入文件,但当前运行的服务端还在使用旧配置。重启服务端进程后生效。'))));
|
||||
if (!d.view.writable) banners.push(el('div', {class: 'banner readonly'}, el('div', {}, el('b', {}, '只读'), el('p', {}, '服务端没有这个文件的写权限(例如部署方以只读方式挂载),这里只能查看。'))));
|
||||
if (d.view.problems && d.view.problems.length) banners.push(el('div', {class: 'banner broken'}, el('div', {}, el('b', {}, '磁盘上的文件当前无效'),
|
||||
el('p', {}, '文件在管理台之外被改成了服务端无法加载的内容,下次重启会失败。修正下面的问题后保存即可。'),
|
||||
el('ul', {}, d.view.problems.map(p => el('li', {}, (p.path ? p.path + ':' : '') + describe(p, fieldFor(d, p.path || ''), d)))))));
|
||||
const docProblems = ((checks[d.name] || {}).problems || []).filter(p => !p.path);
|
||||
if (docProblems.length) banners.push(el('div', {class: 'banner broken'}, el('div', {}, el('b', {}, '无法校验'), el('ul', {}, docProblems.map(p => el('li', {}, describe(p, null, d)))))));
|
||||
$('config-banners').replaceChildren(...banners);
|
||||
}
|
||||
function renderNav() {
|
||||
const nav = $('doc-nav');
|
||||
const items = [];
|
||||
docs.forEach(d => {
|
||||
const changed = dirtyDoc(d);
|
||||
items.push(el('button', {type: 'button', class: 'doc', 'aria-current': String(d.name === current), onclick: () => { current = d.name; render(); renderBanners(); window.scrollTo({top: 0}); }},
|
||||
d.schema.title, changed ? el('span', {class: 'badge'}, '未保存') : d.view.pending ? el('span', {class: 'badge'}, '待重启') : !d.view.writable ? el('span', {class: 'badge'}, '只读') : null));
|
||||
if (d.name === current) {
|
||||
const bad = new Set(((checks[d.name] || {}).problems || []).map(p => { const f = fieldFor(d, p.path); return f && d.schema.sections.find(s => s.fields.includes(f))?.id; }));
|
||||
items.push(el('ul', {class: 'toc'}, d.schema.sections.filter(s => document.getElementById('sec-' + s.id) && !document.getElementById('sec-' + s.id).hidden).map(s =>
|
||||
el('li', {}, el('a', {href: '#config', class: bad.has(s.id) ? 'bad' : '', onclick: e => { e.preventDefault(); document.getElementById('sec-' + s.id).scrollIntoView({behavior: 'smooth', block: 'start'}); }}, s.title)))));
|
||||
}
|
||||
});
|
||||
items.push(el('div', {class: 'sep'}), el('button', {type: 'button', class: 'doc', onclick: () => $('overview').scrollIntoView({behavior: 'smooth'})}, '服务器概览'));
|
||||
nav.replaceChildren(...items);
|
||||
}
|
||||
function changes(d) {
|
||||
const out = [];
|
||||
const walk = (a, b, path) => {
|
||||
if (same(a, b)) return;
|
||||
const objectish = v => v && typeof v === 'object' && !Array.isArray(v);
|
||||
if (objectish(a) && objectish(b)) { new Set([...Object.keys(a), ...Object.keys(b)]).forEach(k => walk(a[k], b[k], path ? path + '.' + k : k)); return; }
|
||||
out.push({path, from: a, to: b});
|
||||
};
|
||||
walk(d.view.value, drafts[d.name], '');
|
||||
return out;
|
||||
}
|
||||
function renderBar() {
|
||||
const dirty = docs.filter(dirtyDoc);
|
||||
$('savebar').hidden = currentView !== 'config' || !dirty.length;
|
||||
if (!dirty.length) return;
|
||||
const problems = dirty.reduce((n, d) => n + ((checks[d.name] || {}).problems || []).length, 0);
|
||||
const count = dirty.reduce((n, d) => n + changes(d).length, 0);
|
||||
const text = $('savebar-text');
|
||||
text.textContent = problems ? `${problems} 处需要修正` : `${count} 处改动未保存` + (dirty.length > 1 ? `(${dirty.length} 个文件)` : '');
|
||||
text.classList.toggle('bad', !!problems);
|
||||
$('save').disabled = !!problems;
|
||||
}
|
||||
const show = v => v === undefined ? '(未设置)' : JSON.stringify(v);
|
||||
$('show-diff').onclick = () => {
|
||||
const list = el('ul', {class: 'diff'});
|
||||
docs.filter(dirtyDoc).forEach(d => changes(d).forEach(c => {
|
||||
const f = fieldFor(d, c.path);
|
||||
list.append(el('li', {}, d.schema.title + ' · ' + (f ? f.label : c.path), el('small', {}, c.path), el('div', {}, el('span', {class: 'from'}, show(c.from)), ' → ', el('span', {class: 'to'}, show(c.to)))));
|
||||
}));
|
||||
ask({title: '尚未保存的改动', body: '保存后需要重启服务端才会生效。', extra: list, ok: '知道了'});
|
||||
};
|
||||
$('discard').onclick = async () => {
|
||||
if (!await ask({title: '放弃全部改动?', body: '未保存的配置改动会被丢弃。', ok: '放弃', danger: true})) return;
|
||||
docs.forEach(d => { drafts[d.name] = clone(d.view.value); }); checks = {}; render(); renderBanners();
|
||||
};
|
||||
async function save() {
|
||||
const dirty = docs.filter(dirtyDoc);
|
||||
if (!dirty.length || $('save').disabled) return;
|
||||
const ok = await ask({title: '保存配置?', body: `将写入 ${dirty.map(d => d.file_name).join('、')}。改动在服务端重启后生效,重启前请确认配置无误。`, ok: '保存'});
|
||||
if (!ok) return;
|
||||
$('save').disabled = true;
|
||||
for (const d of dirty) {
|
||||
try {
|
||||
const {value} = await api('config/' + encodeURIComponent(d.name), {method: 'PUT', headers: {'If-Match': d.view.revision}, body: JSON.stringify(drafts[d.name], null, 2)});
|
||||
d.view = value; drafts[d.name] = clone(value.value); checks[d.name] = {problems: [], advice: value.advice || []};
|
||||
toast(d.schema.title + ' 已保存,重启服务端后生效');
|
||||
} catch (error) {
|
||||
if (error.status === 409) {
|
||||
const reload = await ask({title: '文件已被修改', body: `${d.file_name} 在你编辑期间被其他人或其他程序修改了。载入最新版本会丢弃你在这个文件上的改动。`, ok: '载入最新版本', danger: true});
|
||||
if (reload) { d.view = error.value.view; drafts[d.name] = clone(d.view.value); }
|
||||
} else if (error.status === 422) {
|
||||
checks[d.name] = {problems: error.value.problems || [], advice: []}; current = d.name; toast('有需要修正的地方');
|
||||
} else toast(d.schema.title + ':' + error.message);
|
||||
}
|
||||
}
|
||||
render(); renderBanners(); renderOverview();
|
||||
}
|
||||
$('save').onclick = save;
|
||||
document.addEventListener('keydown', event => {
|
||||
if (currentView === 'config' && (event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') { event.preventDefault(); save(); }
|
||||
});
|
||||
async function renderOverview() {
|
||||
try { server = (await api('server')).value; } catch { server = null; }
|
||||
if (!server) { $('overview').replaceChildren(); return; }
|
||||
const rows = [['服务端版本', server.server_version], ['游戏版本', server.game_version], ['GameData', server.game_data_version], ['资源包', server.bundle_version],
|
||||
['认证模式', server.auth_mode === 'oauth' ? 'OAuth 联机' : '本地单人'], ['监听地址', server.listen], ['启动时间', server.started_at && new Date(server.started_at).toLocaleString('zh-CN')],
|
||||
['数据目录', server.data_dir], ['邮件队列', server.mail_spool], ['开发覆盖', server.dev_tools]];
|
||||
$('overview').replaceChildren(el('h3', {}, '服务器概览'), el('dl', {}, rows.filter(r => r[1]).flatMap(([k, v]) => [el('dt', {}, k), el('dd', {}, /[\\/]/.test(v) ? el('code', {}, v) : v)])));
|
||||
}
|
||||
return {
|
||||
async open() {
|
||||
try {
|
||||
if (!docs.length) {
|
||||
docs = (await api('config/')).value.documents;
|
||||
docs.forEach(d => { if (drafts[d.name] === undefined) drafts[d.name] = clone(d.view.value); });
|
||||
current = current || (docs[0] && docs[0].name);
|
||||
}
|
||||
render(); renderBanners(); renderOverview();
|
||||
} catch (error) { $('config-form').replaceChildren(el('p', {class: 'status err'}, error.message)); }
|
||||
},
|
||||
dirty: () => docs.some(dirtyDoc),
|
||||
reset() { docs = []; drafts = {}; checks = {}; current = ''; },
|
||||
};
|
||||
})();
|
||||
|
||||
boot();
|
||||
@@ -0,0 +1,138 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>BD2 管理台</title>
|
||||
<link rel="stylesheet" href="assets/app.css">
|
||||
<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>
|
||||
<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>
|
||||
</nav>
|
||||
<div class="account" id="account" hidden><span class="user" id="account-name"></span><button type="button" id="logout">退出</button></div>
|
||||
</header>
|
||||
|
||||
<main class="desk">
|
||||
<!-- 登录 -->
|
||||
<section class="view sign-in" id="view-sign-in" hidden>
|
||||
<div class="card sheet">
|
||||
<h1>进入管理台</h1>
|
||||
<p class="muted" id="sign-in-lead">正在读取服务器信息……</p>
|
||||
<div class="providers" id="providers"></div>
|
||||
<p id="sign-in-status" class="status" aria-live="polite"></p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 邮件发放 -->
|
||||
<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>
|
||||
<p id="recipient-note" class="muted"></p>
|
||||
</div>
|
||||
<div class="recipient-side">
|
||||
<label id="player-selector" class="player" hidden>切换玩家<select id="player"></select></label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<fieldset id="tools" class="work" disabled>
|
||||
<div class="lock"><span id="lock-note">正在读取……</span></div>
|
||||
<section class="card catalog">
|
||||
<div class="cat-head"><h2>物品目录</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">
|
||||
<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>
|
||||
</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="parcel empty" id="parcel"></div>
|
||||
<div class="field">
|
||||
<label for="quantity">数量 <span id="qty-hint">支持 5k、2w、3万</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>
|
||||
</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>
|
||||
</details>
|
||||
<button id="grant-submit" class="btn seal send">寄出<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>
|
||||
<div id="inventory-limits" class="limits"></div>
|
||||
<p class="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>
|
||||
<ol class="log" id="log"></ol>
|
||||
<p class="log-empty" id="log-empty">寄出的物品会记在这里,点击发放标识可复制。</p>
|
||||
</section>
|
||||
</aside>
|
||||
</fieldset>
|
||||
</section>
|
||||
|
||||
<!-- 玩家 -->
|
||||
<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>
|
||||
<table class="roster-table">
|
||||
<thead><tr><th>UID</th><th>名称</th><th>身份</th><th class="c">管理台成员</th><th class="c">无限背包</th><th></th></tr></thead>
|
||||
<tbody id="roster"></tbody>
|
||||
</table>
|
||||
<p id="roster-status" class="status" aria-live="polite"></p>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<!-- 服务器配置 -->
|
||||
<section class="view" id="view-config" hidden>
|
||||
<div class="config-layout">
|
||||
<nav class="card doc-nav" id="doc-nav" aria-label="配置文件"></nav>
|
||||
<div class="config-main">
|
||||
<div id="config-banners"></div>
|
||||
<form id="config-form" class="config-form" novalidate></form>
|
||||
<section class="card overview" id="overview"></section>
|
||||
</div>
|
||||
</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>
|
||||
</div>
|
||||
</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>
|
||||
</dialog>
|
||||
<div class="toast" id="toast" role="status"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,6 +1,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gameconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
@@ -42,6 +43,9 @@ type configuration struct {
|
||||
versions versionconfig.Config
|
||||
calendars *calendar.Set
|
||||
gameRules gameconfig.Config
|
||||
gameFile *commonconfig.File[gameconfig.Config]
|
||||
authFile *commonconfig.File[authconfig.Config]
|
||||
resourceFile *commonconfig.File[resourcepolicy.Config]
|
||||
textModerator *textmoderation.Service
|
||||
authentication authconfig.Config
|
||||
authRuntime authconfig.Runtime
|
||||
@@ -56,9 +60,9 @@ func loadConfiguration(args []string) (result *configuration, loadErr error) {
|
||||
logLevel := fs.String("log-level", "", "log threshold: trace, debug, info, warn, error (default BD2_LOG_LEVEL or info)")
|
||||
logColor := fs.String("log-color", "", "level colors: auto, always, never (default BD2_LOG_COLOR or auto)")
|
||||
versionConfigPath := fs.String("version-config", "", "repository versions.json override")
|
||||
authConfigPath := fs.String("authentication-config", "", "authentication.json override for development")
|
||||
resourceConfigPath := fs.String("resource-config", "", "resources.json override for development")
|
||||
gameConfigPath := fs.String("game-config", "", "game.json server gameplay configuration override")
|
||||
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)")
|
||||
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)")
|
||||
@@ -67,7 +71,7 @@ func loadConfiguration(args []string) (result *configuration, loadErr error) {
|
||||
playerSeed := fs.String("player-seed", "", "versioned starter inventory and characters")
|
||||
readonlySeed := fs.String("readonly-seed", "", "versioned static protocol defaults")
|
||||
mailSeed := fs.String("mail-seed", "", "versioned starter mailbox")
|
||||
mailGrantSpool := fs.String("mail-grant-spool", "", "optional local JSON spool for idempotent dynamic system mail")
|
||||
mailGrantSpool := fs.String("mail-grant-spool", "", "JSON spool for idempotent dynamic system mail (default DATA_DIR/mail-grants-spool.json)")
|
||||
stateDirectory := fs.String("state-dir", "", "player and shared state directory")
|
||||
deckSeed := fs.String("deck-seed", "", "versioned starter deck")
|
||||
worldSeed := fs.String("world-seed", "", "versioned starter world")
|
||||
@@ -108,45 +112,6 @@ func loadConfiguration(args []string) (result *configuration, loadErr error) {
|
||||
return nil, errors.New("project calendars require regular content and monster hunt schedules")
|
||||
}
|
||||
slog.Info("project calendars loaded", "directory", calendarDirectory, "revisions", calendars.Revisions, "events", len(calendars.Events))
|
||||
if *gameConfigPath == "" {
|
||||
*gameConfigPath, err = gameconfig.BesideExecutable()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
gameRules, err := gameconfig.Load(*gameConfigPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if *authConfigPath == "" {
|
||||
*authConfigPath, err = authconfig.BesideExecutable()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
authentication, err := authconfig.Load(*authConfigPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authRuntime, err := authentication.ResolveEnvironment()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if result == nil {
|
||||
clear(authRuntime.MasterKey)
|
||||
}
|
||||
}()
|
||||
if *resourceConfigPath == "" {
|
||||
*resourceConfigPath, err = resourcepolicy.BesideExecutable()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
resources, err := resourcepolicy.Load(*resourceConfigPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if *dataDir == "" {
|
||||
executable, executableErr := os.Executable()
|
||||
if executableErr != nil {
|
||||
@@ -158,7 +123,44 @@ func loadConfiguration(args []string) (result *configuration, loadErr error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve server data directory: %w", err)
|
||||
}
|
||||
configDirectory := filepath.Join(*dataDir, "config")
|
||||
if *gameConfigPath == "" {
|
||||
*gameConfigPath = gameconfig.Document.Path(configDirectory)
|
||||
}
|
||||
gameFile, gameRules, err := gameconfig.Document.Open(*gameConfigPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
*gameConfigPath = gameFile.Path()
|
||||
if *authConfigPath == "" {
|
||||
*authConfigPath = authconfig.Document.Path(configDirectory)
|
||||
}
|
||||
authFile, authentication, err := authconfig.Document.Open(*authConfigPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
*authConfigPath = authFile.Path()
|
||||
authRuntime, err := authentication.ResolveEnvironment()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if result == nil {
|
||||
clear(authRuntime.MasterKey)
|
||||
}
|
||||
}()
|
||||
if *resourceConfigPath == "" {
|
||||
*resourceConfigPath = resourcepolicy.Document.Path(configDirectory)
|
||||
}
|
||||
resourceFile, resources, err := resourcepolicy.Document.Open(*resourceConfigPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
*resourceConfigPath = resourceFile.Path()
|
||||
*devToolsConfig = resolveDevelopmentSettingsPath(*dataDir, *devToolsConfig)
|
||||
if *mailGrantSpool == "" {
|
||||
*mailGrantSpool = filepath.Join(*dataDir, "mail-grants-spool.json")
|
||||
}
|
||||
gameData := filepath.Join(*dataDir, "resources", "GameData")
|
||||
if *stateDirectory == "" {
|
||||
*stateDirectory = filepath.Join(*dataDir, "state")
|
||||
@@ -220,6 +222,6 @@ func loadConfiguration(args []string) (result *configuration, loadErr error) {
|
||||
deckSeed: *deckSeed,
|
||||
worldSeed: *worldSeed,
|
||||
devToolsConfig: *devToolsConfig,
|
||||
versions: versions, calendars: calendars, gameRules: gameRules, authentication: authentication, authRuntime: authRuntime, publicResources: publicResources, bootstrap: cfg, gameData: gameData, verifiedGameData: verifiedGameData,
|
||||
versions: versions, calendars: calendars, gameRules: gameRules, gameFile: gameFile, authFile: authFile, resourceFile: resourceFile, authentication: authentication, authRuntime: authRuntime, publicResources: publicResources, bootstrap: cfg, gameData: gameData, verifiedGameData: verifiedGameData,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/server/admin"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/gateway/auth"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
identitystore "bd2server/internal/server/storage/identity"
|
||||
)
|
||||
|
||||
// openConsole assembles the administration website from the running server's
|
||||
// configuration files, identity directory and GameData.
|
||||
func openConsole(c *configuration, design *designCatalog, seeds *seedCatalog, authService *auth.Service, authStore *identitystore.Store, instanceID string) (*admin.Console, *admin.Store, error) {
|
||||
store, err := admin.OpenStore(filepath.Join(c.stateDirectory, "admin.db"))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
developmentSettings, _, err := inventory.DevelopmentSettingsDocument.Open(c.devToolsConfig)
|
||||
if err != nil {
|
||||
_ = store.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
players := func(ctx context.Context) ([]admin.Player, error) {
|
||||
if authStore == nil {
|
||||
owner, _, err := wire.Varint(seeds.login.UserInfo, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []admin.Player{{AccountID: "local-owner", UID: strconv.FormatUint(owner, 10), Name: "本地玩家", Active: true}}, nil
|
||||
}
|
||||
profiles, err := authStore.Players(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]admin.Player, len(profiles))
|
||||
for i, profile := range profiles {
|
||||
out[i] = admin.Player{AccountID: profile.AccountID, UID: strconv.FormatInt(profile.OwnerIndex, 10), Name: profile.UserID, Active: profile.Active}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
catalog := sync.OnceValues(func() ([]gamedata.MailCatalogItem, error) {
|
||||
items, err := gamedata.LoadMailCatalog(c.gameData, c.gameDataVersion)
|
||||
if err == nil {
|
||||
gamedata.SortMailCatalog(items)
|
||||
}
|
||||
return items, err
|
||||
})
|
||||
slots := design.slotDesign
|
||||
started := time.Now().UTC()
|
||||
options := admin.Options{
|
||||
Store: store, Players: players, Catalog: catalog, MailSpool: c.mailGrantSpool, Inventory: developmentSettings,
|
||||
Limits: admin.InventoryLimits{
|
||||
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),
|
||||
Secure: c.authentication.Mode == "oauth" && c.authRuntime.PublicURLParsed != nil && c.authRuntime.PublicURLParsed.Scheme == "https",
|
||||
Server: func() any {
|
||||
return map[string]any{
|
||||
"server_version": c.versions.ServerVersion, "game_version": c.versions.GameVersion, "game_data_version": c.gameDataVersion,
|
||||
"bundle_version": c.versions.BundleVersion, "auth_mode": c.authentication.Mode, "listen": c.listen, "data_dir": c.dataDir,
|
||||
"instance_id": instanceID, "started_at": started, "mail_spool": c.mailGrantSpool, "dev_tools": c.devToolsConfig,
|
||||
}
|
||||
},
|
||||
}
|
||||
if authService != nil {
|
||||
options.Identity = authService
|
||||
}
|
||||
console, err := admin.New(options)
|
||||
if err != nil {
|
||||
_ = store.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return console, store, nil
|
||||
}
|
||||
|
||||
// consoleOrigin is the externally visible origin for printed console links.
|
||||
func consoleOrigin(c *configuration) string {
|
||||
if c.authentication.Mode == "oauth" {
|
||||
return c.authentication.PublicURL
|
||||
}
|
||||
host, port, err := net.SplitHostPort(c.listen)
|
||||
if err != nil {
|
||||
return "http://" + c.listen
|
||||
}
|
||||
if ip := net.ParseIP(host); host == "" || ip != nil && ip.IsUnspecified() {
|
||||
host = "127.0.0.1"
|
||||
}
|
||||
return (&url.URL{Scheme: "http", Host: net.JoinHostPort(host, port)}).String()
|
||||
}
|
||||
@@ -4,11 +4,11 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/server/design/gameconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
eventplay "bd2server/internal/server/domain/events/play"
|
||||
"bd2server/internal/server/gateway/realtime"
|
||||
@@ -58,10 +58,10 @@ func openRealtime(c *configuration, registry *playerRegistry, game *session.Serv
|
||||
},
|
||||
}
|
||||
resolve := func(path string) string {
|
||||
if path == "" || filepath.IsAbs(path) {
|
||||
if path == "" {
|
||||
return path
|
||||
}
|
||||
return filepath.Join(filepath.Dir(c.gameConfigPath), path)
|
||||
return gameconfig.ResolvePath(c.gameConfigPath, path)
|
||||
}
|
||||
chatDesign, err := gamedata.LoadChatDesign(c.gameData, c.gameDataVersion)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/gateway/auth"
|
||||
"bd2server/internal/server/gateway/session"
|
||||
@@ -58,6 +59,7 @@ func Serve(args []string) (serveErr error) {
|
||||
if err := lockServerState(c.stateDirectory, c.gameRules.Story.StartPackID); err != nil {
|
||||
return err
|
||||
}
|
||||
c.gameFile.Lock(commonconfig.Lock{Path: "story.start_pack_id", Value: c.gameRules.Story.StartPackID, Reason: "首次初始化后已永久保存于服务器状态,不能再更改"})
|
||||
shared, err := openSharedRuntime(context.Background(), c, design)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -108,12 +110,17 @@ func Serve(args []string) (serveErr error) {
|
||||
realtimeDone = realtime.done
|
||||
realtimeTickets = realtime.tickets
|
||||
}
|
||||
console, consoleStore, err := openConsole(c, design, seeds, authService, authStore, instanceID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open administration console: %w", err)
|
||||
}
|
||||
defer func() { serveErr = errors.Join(serveErr, consoleStore.Close()) }()
|
||||
dispatcher := transport.Bootstrap{Config: c.bootstrap}
|
||||
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},
|
||||
StoryCheckpoints: storyCheckpoints{game: game, players: registry}, Console: console.Handler(),
|
||||
}.Handler()
|
||||
server := &http.Server{
|
||||
Addr: c.listen,
|
||||
@@ -127,6 +134,11 @@ func Serve(args []string) (serveErr error) {
|
||||
slog.Info("BD2 server listening", "address", c.listen, "instance_id", instanceID, "server_version", c.versions.ServerVersion, "game_version", c.bootstrap.Version, "bundle", c.bootstrap.BundleVer, "resourceMode", c.publicResources.Mode, "gameData", c.verifiedGameData.ArchivePath, "gameDataEntries", c.verifiedGameData.EntryCount, "accountSeed", c.accountSeed)
|
||||
serveResult := make(chan error, 1)
|
||||
go func() { serveResult <- server.ListenAndServe() }()
|
||||
if link, err := console.IssueSignInLink(consoleOrigin(c)); err != nil {
|
||||
slog.Warn("administration console sign-in link unavailable", "error", err)
|
||||
} else {
|
||||
slog.Info("administration console owner sign-in link (single use, 24 hours)", "url", link)
|
||||
}
|
||||
signals := make(chan os.Signal, 1)
|
||||
signal.Notify(signals, lifecycle.ShutdownSignals()...)
|
||||
defer signal.Stop(signals)
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
package gameconfig
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
)
|
||||
@@ -37,48 +37,50 @@ type TextModerationProviderConfig struct {
|
||||
SeverityThreshold int `json:"severity_threshold"`
|
||||
}
|
||||
|
||||
// TextScopes are the input entry points currently connected to moderation.
|
||||
var TextScopes = []string{
|
||||
"nickname", "greeting", "master_title", "preset_name", "equipment_preset_name", "equipment_mark",
|
||||
"monster_hunt_preset_name", "guild_raid_preset_name", "colosseum_preset_name",
|
||||
"guild_name", "guild_message", "guild_notice", "room_name", "chat",
|
||||
}
|
||||
|
||||
func DefaultTextModeration() TextModerationConfig {
|
||||
return TextModerationConfig{RuleFiles: []string{}, Provider: TextModerationProviderConfig{
|
||||
Type: "off", APIKeyHeader: "Authorization", Scopes: []string{
|
||||
"nickname", "greeting", "master_title", "preset_name", "equipment_preset_name", "equipment_mark",
|
||||
"monster_hunt_preset_name", "guild_raid_preset_name", "colosseum_preset_name",
|
||||
"guild_name", "guild_message", "guild_notice", "room_name", "chat",
|
||||
},
|
||||
Type: "off", APIKeyHeader: "Authorization", Scopes: append([]string(nil), TextScopes...),
|
||||
TimeoutMS: 1500, FailurePolicy: "deny", SeverityThreshold: 4,
|
||||
}}
|
||||
}
|
||||
|
||||
// Validate checks the moderation group as it would appear in game.json.
|
||||
func (c TextModerationConfig) Validate() error {
|
||||
if slices.Contains(c.RuleFiles, "") {
|
||||
return fmt.Errorf("text_moderation.rule_files must contain nonempty paths")
|
||||
config := Default()
|
||||
config.TextModeration = c
|
||||
return Document.Validate(config)
|
||||
}
|
||||
|
||||
func textModerationRules(c TextModerationConfig, problems *commonconfig.Problems) {
|
||||
for i, file := range c.RuleFiles {
|
||||
if file == "" {
|
||||
problems.Add(indexed("text_moderation.rule_files", i), commonconfig.RuleRequired, "must be a nonempty path")
|
||||
}
|
||||
}
|
||||
p := c.Provider
|
||||
if p.Type != "off" && p.Type != "http_json" && p.Type != "azure_content_safety" {
|
||||
return fmt.Errorf("text_moderation.provider.type must be off, http_json, or azure_content_safety")
|
||||
}
|
||||
if p.TimeoutMS < 10 || p.TimeoutMS > 30000 {
|
||||
return fmt.Errorf("text_moderation.provider.timeout_ms must be between 10 and 30000")
|
||||
}
|
||||
if p.FailurePolicy != "allow" && p.FailurePolicy != "deny" {
|
||||
return fmt.Errorf("text_moderation.provider.failure_policy must be allow or deny")
|
||||
}
|
||||
if p.SeverityThreshold < 0 || p.SeverityThreshold > 7 {
|
||||
return fmt.Errorf("text_moderation.provider.severity_threshold must be between 0 and 7")
|
||||
}
|
||||
if p.Type != "off" && (p.Endpoint == "" || len(p.Scopes) == 0) {
|
||||
return fmt.Errorf("text_moderation active provider requires endpoint and scopes")
|
||||
if p.Type != "off" {
|
||||
if p.Endpoint == "" {
|
||||
problems.Add("text_moderation.provider.endpoint", commonconfig.RuleRequired, "is required by an active provider")
|
||||
}
|
||||
if len(p.Scopes) == 0 {
|
||||
problems.Add("text_moderation.provider.scopes", commonconfig.RuleRequired, "is required by an active provider")
|
||||
}
|
||||
}
|
||||
if p.Type == "azure_content_safety" && p.APIKeyEnv == "" {
|
||||
return fmt.Errorf("text_moderation Azure provider requires api_key_env")
|
||||
problems.Add("text_moderation.provider.api_key_env", commonconfig.RuleRequired, "is required by the Azure provider")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, scope := range p.Scopes {
|
||||
if !ValidTextScope(scope) || seen[scope] {
|
||||
return fmt.Errorf("text_moderation.provider.scopes must contain unique lowercase identifiers")
|
||||
for i, scope := range p.Scopes {
|
||||
if !ValidTextScope(scope) {
|
||||
problems.Add(indexed("text_moderation.provider.scopes", i), commonconfig.RuleFormat, "must be a lowercase identifier")
|
||||
}
|
||||
seen[scope] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidTextScope(scope string) bool {
|
||||
@@ -122,50 +124,61 @@ func Default() Config {
|
||||
return Config{SchemaVersion: 1, Story: StoryConfig{StartPackID: 21}, Purchases: PurchasesConfig{DiamondRecharge: DiamondRechargeConfig{Currency: "free", GoldPerPaidDiamond: 1000, DiamondsPerPaidDiamond: 1}}, TextModeration: DefaultTextModeration()}
|
||||
}
|
||||
|
||||
// Document is game.json. Omitted gameplay groups keep their defaults, but the
|
||||
// format version is required even when every group is omitted.
|
||||
var Document = commonconfig.Document[Config]{
|
||||
Name: "game",
|
||||
FileName: FileName,
|
||||
Defaults: Default,
|
||||
Base: func() Config {
|
||||
defaults := Default()
|
||||
defaults.SchemaVersion = 0
|
||||
return defaults
|
||||
},
|
||||
Decode: commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true, RejectNull: true},
|
||||
Schema: schema,
|
||||
Rules: func(c Config) commonconfig.Problems {
|
||||
var problems commonconfig.Problems
|
||||
realtimeRules(c.Realtime, &problems)
|
||||
textModerationRules(c.TextModeration, &problems)
|
||||
return problems
|
||||
},
|
||||
Advice: func(c Config, path string) commonconfig.Problems {
|
||||
var advice commonconfig.Problems
|
||||
missing := func(field, file string) {
|
||||
if file == "" {
|
||||
return
|
||||
}
|
||||
if _, err := os.Stat(ResolvePath(path, file)); err != nil {
|
||||
advice.Add(field, commonconfig.RuleMissingFile, "%s is not readable by this server process", file)
|
||||
}
|
||||
}
|
||||
for i, file := range c.TextModeration.RuleFiles {
|
||||
missing(indexed("text_moderation.rule_files", i), file)
|
||||
}
|
||||
if c.Realtime.Enabled && !c.Realtime.DevelopmentPlainLoopback {
|
||||
missing("realtime.tls_cert_file", c.Realtime.TLSCertFile)
|
||||
missing("realtime.tls_key_file", c.Realtime.TLSKeyFile)
|
||||
}
|
||||
p := c.TextModeration.Provider
|
||||
if p.Type != "off" && p.APIKeyEnv != "" && strings.TrimSpace(os.Getenv(p.APIKeyEnv)) == "" {
|
||||
advice.Add("text_moderation.provider.api_key_env", commonconfig.RuleEnvironment, "environment variable %s is empty in this server process", p.APIKeyEnv)
|
||||
}
|
||||
return advice
|
||||
},
|
||||
}
|
||||
|
||||
// ResolvePath resolves a file referenced by game.json relative to its directory.
|
||||
func ResolvePath(configPath, file string) string {
|
||||
if filepath.IsAbs(file) {
|
||||
return filepath.Clean(file)
|
||||
}
|
||||
return filepath.Join(filepath.Dir(configPath), file)
|
||||
}
|
||||
|
||||
// Load generates defaults when missing and strictly validates existing files.
|
||||
func Load(path string) (Config, error) {
|
||||
if err := commonconfig.Ensure(path, Default(), commonconfig.WriteOptions{}); err != nil {
|
||||
return Config{}, fmt.Errorf("game configuration: initialize %s: %w", path, err)
|
||||
}
|
||||
defaults := Default()
|
||||
// The format version is required even when gameplay sections are omitted.
|
||||
defaults.SchemaVersion = 0
|
||||
cfg, err := commonconfig.Load(path, defaults, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true, RejectNull: true})
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("game configuration: load %s: %w", path, err)
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return Config{}, fmt.Errorf("game configuration: %s: %w", path, err)
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
func Load(path string) (Config, error) { return Document.Load(path) }
|
||||
|
||||
func (c Config) Validate() error {
|
||||
if err := c.Realtime.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if c.SchemaVersion != 1 {
|
||||
return fmt.Errorf("unsupported schema_version %d (expected 1)", c.SchemaVersion)
|
||||
}
|
||||
if c.Story.StartPackID != 1 && c.Story.StartPackID != 21 {
|
||||
return fmt.Errorf("story.start_pack_id must be 1 or 21, got %d", c.Story.StartPackID)
|
||||
}
|
||||
r := c.Purchases.DiamondRecharge
|
||||
switch r.Currency {
|
||||
case "free", "gold", "diamonds", "ban", "":
|
||||
default:
|
||||
return fmt.Errorf("purchases.diamond_recharge.currency must be free, gold, diamonds, ban, or an empty string")
|
||||
}
|
||||
if r.GoldPerPaidDiamond < 1 || r.GoldPerPaidDiamond > 1_000_000_000 || r.DiamondsPerPaidDiamond < 1 || r.DiamondsPerPaidDiamond > 1_000_000_000 {
|
||||
return fmt.Errorf("purchases.diamond_recharge conversion rates must be integers between 1 and 1000000000")
|
||||
}
|
||||
return c.TextModeration.Validate()
|
||||
}
|
||||
func (c Config) Validate() error { return Document.Validate(c) }
|
||||
|
||||
func BesideExecutable() (string, error) {
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("game configuration: resolve server executable: %w", err)
|
||||
}
|
||||
return filepath.Join(filepath.Dir(executable), FileName), nil
|
||||
}
|
||||
func indexed(path string, index int) string { return path + "[" + strconv.Itoa(index) + "]" }
|
||||
@@ -0,0 +1,50 @@
|
||||
package gameconfig
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
func TestGameConfigurationProblemsAreLocatedByField(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
raw string
|
||||
want []string
|
||||
}{
|
||||
{name: "omitted groups keep defaults", raw: `{"schema_version":1}`},
|
||||
{name: "deployed server configuration", raw: `{"schema_version":1,"gacha":{"include_collaboration_ur_weapons":false},"story":{"start_pack_id":21},
|
||||
"purchases":{"diamond_recharge":{"currency":"free","gold_per_paid_diamond":1000,"diamonds_per_paid_diamond":1}},
|
||||
"realtime":{"enabled":true,"tcp_listen":"0.0.0.0:8444","udp_listen":"0.0.0.0:8444","public_host":"game.example.com","tcp_port":8444,"udp_port":8444,
|
||||
"tls_cert_file":"/app/tls/server.crt","tls_key_file":"/app/tls/server.key","development_plain_loopback":false},
|
||||
"text_moderation":{"rule_files":["moderation/words.txt"]}}`},
|
||||
{name: "format version is required", raw: `{}`, want: []string{"schema_version"}},
|
||||
{name: "empty currency still forbids recharge", raw: `{"schema_version":1,"purchases":{"diamond_recharge":{"currency":""}}}`},
|
||||
{name: "start pack and rates", raw: `{"schema_version":1,"story":{"start_pack_id":2},"purchases":{"diamond_recharge":{"currency":"gold","gold_per_paid_diamond":0}}}`,
|
||||
want: []string{"story.start_pack_id", "purchases.diamond_recharge.gold_per_paid_diamond"}},
|
||||
{name: "disabled realtime ignores incomplete fields", raw: `{"schema_version":1,"realtime":{"enabled":false,"tcp_port":0}}`},
|
||||
{name: "enabled realtime requires its listeners and TLS", raw: `{"schema_version":1,"realtime":{"enabled":true,"public_host":"a b","tcp_port":70000,"udp_port":8444,"tcp_listen":"bad","udp_listen":"0.0.0.0:8444"}}`,
|
||||
want: []string{"realtime.public_host", "realtime.tcp_port", "realtime.tcp_listen", "realtime.tls_cert_file", "realtime.tls_key_file"}},
|
||||
{name: "plaintext development binds loopback", raw: `{"schema_version":1,"realtime":{"enabled":true,"development_plain_loopback":true,"public_host":"game.example.com","tcp_port":1,"udp_port":1,"tcp_listen":"0.0.0.0:1","udp_listen":"127.0.0.1:1"}}`,
|
||||
want: []string{"realtime.public_host", "realtime.tcp_listen"}},
|
||||
{name: "moderation provider", raw: `{"schema_version":1,"text_moderation":{"rule_files":[""],"provider":{"type":"azure_content_safety","scopes":["chat","chat","Bad"],"timeout_ms":5,"failure_policy":"deny","severity_threshold":4}}}`,
|
||||
want: []string{"text_moderation.rule_files[0]", "text_moderation.provider.endpoint", "text_moderation.provider.api_key_env",
|
||||
"text_moderation.provider.scopes[1]", "text_moderation.provider.scopes[2]", "text_moderation.provider.timeout_ms"}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
_, err := Document.Parse([]byte(test.raw))
|
||||
got := map[string]bool{}
|
||||
for _, problem := range commonconfig.AsProblems(err) {
|
||||
got[problem.Path] = true
|
||||
}
|
||||
for _, path := range test.want {
|
||||
if !got[path] {
|
||||
t.Errorf("missing problem at %s; got %v", path, err)
|
||||
}
|
||||
}
|
||||
if len(got) != len(test.want) {
|
||||
t.Errorf("problems %v, want exactly %v", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
package gameconfig
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
type RealtimeConfig struct {
|
||||
@@ -18,28 +19,35 @@ type RealtimeConfig struct {
|
||||
DevelopmentPlainLoopback bool `json:"development_plain_loopback"`
|
||||
}
|
||||
|
||||
func (c RealtimeConfig) Validate() error {
|
||||
// Port ranges are schema constraints; these rules cover dependent fields.
|
||||
func realtimeRules(c RealtimeConfig, problems *commonconfig.Problems) {
|
||||
if !c.Enabled {
|
||||
return nil
|
||||
return
|
||||
}
|
||||
if c.PublicHost == "" || strings.ContainsAny(c.PublicHost, "/\\@?# \t\r\n") || c.TCPPort < 1 || c.TCPPort > 65535 || c.UDPPort < 1 || c.UDPPort > 65535 {
|
||||
return errors.New("realtime requires a public host and valid TCP/UDP ports")
|
||||
if c.PublicHost == "" {
|
||||
problems.Add("realtime.public_host", commonconfig.RuleRequired, "is required")
|
||||
} else if strings.ContainsAny(c.PublicHost, "/\\@?# \t\r\n") {
|
||||
problems.Add("realtime.public_host", commonconfig.RuleFormat, "must be a bare host name without scheme, path or port")
|
||||
}
|
||||
for _, address := range []string{c.TCPListen, c.UDPListen} {
|
||||
host, port, err := net.SplitHostPort(address)
|
||||
for _, listener := range [...]struct{ path, address string }{{"realtime.tcp_listen", c.TCPListen}, {"realtime.udp_listen", c.UDPListen}} {
|
||||
path := listener.path
|
||||
host, port, err := net.SplitHostPort(listener.address)
|
||||
if err != nil || port == "" {
|
||||
return errors.New("realtime listener must be host:port")
|
||||
}
|
||||
if c.DevelopmentPlainLoopback && !net.ParseIP(host).IsLoopback() {
|
||||
return errors.New("plaintext realtime listeners must bind loopback")
|
||||
problems.Add(path, commonconfig.RuleFormat, "must be host:port")
|
||||
} else if c.DevelopmentPlainLoopback && !net.ParseIP(host).IsLoopback() {
|
||||
problems.Add(path, commonconfig.RuleConflict, "plaintext realtime listeners must bind loopback")
|
||||
}
|
||||
}
|
||||
if c.DevelopmentPlainLoopback {
|
||||
if !net.ParseIP(c.PublicHost).IsLoopback() {
|
||||
return errors.New("plaintext realtime public host must be loopback")
|
||||
problems.Add("realtime.public_host", commonconfig.RuleConflict, "plaintext realtime public host must be loopback")
|
||||
}
|
||||
} else if c.TLSCertFile == "" || c.TLSKeyFile == "" {
|
||||
return errors.New("realtime TLS certificate and private key paths are required")
|
||||
return
|
||||
}
|
||||
if c.TLSCertFile == "" {
|
||||
problems.Add("realtime.tls_cert_file", commonconfig.RuleRequired, "is required unless plaintext loopback development is enabled")
|
||||
}
|
||||
if c.TLSKeyFile == "" {
|
||||
problems.Add("realtime.tls_key_file", commonconfig.RuleRequired, "is required unless plaintext loopback development is enabled")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package gameconfig
|
||||
|
||||
import commonconfig "bd2server/internal/common/config"
|
||||
|
||||
var (
|
||||
rateMin, rateMax = commonconfig.Range(1, 1_000_000_000)
|
||||
portMin, portMax = commonconfig.Range(1, 65535)
|
||||
timeoutMin, timeoutMax = commonconfig.Range(10, 30000)
|
||||
severityMin, severityMax = commonconfig.Range(0, 7)
|
||||
)
|
||||
|
||||
var realtimeEnabled = &commonconfig.Condition{Path: "realtime.enabled", In: []any{true}}
|
||||
var providerActive = &commonconfig.Condition{Path: "text_moderation.provider.type", In: []any{"off"}, Not: true}
|
||||
|
||||
var schema = commonconfig.Schema{
|
||||
Title: "游戏规则",
|
||||
Summary: "服务端统一的玩法规则。修改后重启服务端生效。",
|
||||
Sections: []commonconfig.Section{
|
||||
{ID: "story", Title: "开局章节", Help: "首次成功初始化后永久保存在服务器状态中,之后不能更改;不能通过删除数据库切换开局。", Fields: []commonconfig.Field{
|
||||
{Path: "story.start_pack_id", Kind: commonconfig.KindInteger, Label: "起始章节", Options: []commonconfig.Option{
|
||||
{Value: 21, Label: "店长篇", Help: "当前客户端默认的开局,使用该篇的任务和教学流程。"},
|
||||
{Value: 1, Label: "旧主线第一章", Help: "使用当前 GameData 中该章的开场剧情、初始任务及购卡奖励。"},
|
||||
}},
|
||||
}},
|
||||
{ID: "gacha", Title: "抽卡", Fields: []commonconfig.Field{
|
||||
{Path: "gacha.include_collaboration_ur_weapons", Kind: commonconfig.KindBool, Label: "UR 必得装备券加入联动专武",
|
||||
Help: "在原池中加入 14 种联动角色 UR 专武(装备 943200–943213),沿用同星级单件权重;只改变券池候选,不直接发放装备。"},
|
||||
}},
|
||||
{ID: "purchases", Title: "付费钻石充值", Help: "普通现金商品固定消耗付费钻石,价格由 GameData 换算;这里只设置付费钻石充值本身的兑换方式。", Fields: []commonconfig.Field{
|
||||
{Path: "purchases.diamond_recharge.currency", Kind: commonconfig.KindString, Label: "充值方式", Options: []commonconfig.Option{
|
||||
{Value: "free", Label: "免费", Help: "不扣货币,直接发放所选充值商品的原始奖励。"},
|
||||
{Value: "gold", Label: "金币兑换", Help: "每单位常规付费钻石消耗设定数量的金币。"},
|
||||
{Value: "diamonds", Label: "普通钻石兑换", Help: "每单位常规付费钻石消耗设定数量的普通钻石。"},
|
||||
{Value: "ban", Label: "禁止充值", Help: "禁止购买付费钻石充值商品,不影响玩家已有付费钻石。"},
|
||||
{Value: "", Label: "禁止充值(空字符串)", Help: "与 ban 相同的旧写法。"},
|
||||
}},
|
||||
{Path: "purchases.diamond_recharge.gold_per_paid_diamond", Kind: commonconfig.KindInteger, Label: "金币 / 付费钻石", Min: rateMin, Max: rateMax,
|
||||
Help: "金币兑换时每单位常规付费钻石的费用。即使未选用也必须合法。"},
|
||||
{Path: "purchases.diamond_recharge.diamonds_per_paid_diamond", Kind: commonconfig.KindInteger, Label: "普通钻石 / 付费钻石", Min: rateMin, Max: rateMax,
|
||||
Help: "普通钻石兑换时每单位常规付费钻石的费用。即使未选用也必须合法。"},
|
||||
}},
|
||||
{ID: "realtime", Title: "实时联机", Help: "动作小游戏、联机钓鱼与随机防御使用的原生 TCP/UDP 连接。关闭时不监听实时端口,会影响玩家体验。", Fields: []commonconfig.Field{
|
||||
{Path: "realtime.enabled", Kind: commonconfig.KindBool, Label: "启用实时联机"},
|
||||
{Path: "realtime.public_host", Kind: commonconfig.KindString, Label: "公开主机名", Format: "host", Placeholder: "game.example.com", When: realtimeEnabled,
|
||||
Help: "玩家能够访问的主机名,不带协议、路径或端口。"},
|
||||
{Path: "realtime.tcp_port", Kind: commonconfig.KindInteger, Label: "公开 TCP 端口", Min: portMin, Max: portMax, When: realtimeEnabled},
|
||||
{Path: "realtime.udp_port", Kind: commonconfig.KindInteger, Label: "公开 UDP 端口", Min: portMin, Max: portMax, When: realtimeEnabled},
|
||||
{Path: "realtime.tcp_listen", Kind: commonconfig.KindString, Label: "TCP 监听地址", Format: "listen", Placeholder: "0.0.0.0:8444", When: realtimeEnabled,
|
||||
Help: "公开端口可以与监听端口不同,适用于端口映射。"},
|
||||
{Path: "realtime.udp_listen", Kind: commonconfig.KindString, Label: "UDP 监听地址", Format: "listen", Placeholder: "0.0.0.0:8444", When: realtimeEnabled},
|
||||
{Path: "realtime.tls_cert_file", Kind: commonconfig.KindString, Label: "TLS 证书", Format: "path", When: realtimeEnabled,
|
||||
Help: "与公开主机名匹配且受客户端信任的证书。相对路径以 game.json 所在目录为基准;更新后新握手自动载入。"},
|
||||
{Path: "realtime.tls_key_file", Kind: commonconfig.KindString, Label: "TLS 私钥", Format: "path", When: realtimeEnabled,
|
||||
Help: "私钥只留在服务端,须允许服务进程读取。"},
|
||||
{Path: "realtime.development_plain_loopback", Kind: commonconfig.KindBool, Label: "本机开发明文模式", Advanced: true, When: realtimeEnabled,
|
||||
Help: "仅限本机开发:监听地址和公开地址都必须是回环 IP,此时不需要证书。"},
|
||||
}},
|
||||
{ID: "text_moderation", Title: "文本审核", Help: "本地规则先执行,通过后才调用第三方。已有昵称和简介不会在登录时重新审核。", Fields: []commonconfig.Field{
|
||||
{Path: "text_moderation.rule_files", Kind: commonconfig.KindList, Label: "本地词库文件", Format: "path",
|
||||
Help: "UTF-8 的 .txt(每行一个词,子串匹配)或 .json(逐条指定匹配方式与范围),单文件最多 4 MiB。相对路径以 game.json 所在目录为基准。"},
|
||||
{Path: "text_moderation.provider.type", Kind: commonconfig.KindString, Label: "第三方审核", Options: []commonconfig.Option{
|
||||
{Value: "off", Label: "关闭"},
|
||||
{Value: "http_json", Label: "通用 HTTP JSON", Help: "接入自建审核服务或第三方适配网关。"},
|
||||
{Value: "azure_content_safety", Label: "Azure AI Content Safety"},
|
||||
}},
|
||||
{Path: "text_moderation.provider.endpoint", Kind: commonconfig.KindString, Label: "审核地址", Format: "url", When: providerActive,
|
||||
Help: "使用 HTTPS,只有回环地址允许 HTTP,不跟随重定向。Azure 填资源根地址。"},
|
||||
{Path: "text_moderation.provider.api_key_env", Kind: commonconfig.KindString, Label: "密钥环境变量", Format: "env", When: providerActive,
|
||||
Help: "服务端从这个环境变量读取密钥,配置文件里不保存密钥本身。"},
|
||||
{Path: "text_moderation.provider.api_key_header", Kind: commonconfig.KindString, Label: "密钥请求头", Advanced: true,
|
||||
When: &commonconfig.Condition{Path: "text_moderation.provider.type", In: []any{"http_json"}},
|
||||
Help: "Authorization 头会发送 Bearer <密钥>,其他头名原样传递密钥。"},
|
||||
{Path: "text_moderation.provider.scopes", Kind: commonconfig.KindList, Label: "审核范围", Unique: true, OpenOptions: true,
|
||||
Help: "第三方只审核明确列出的输入入口。", Options: []commonconfig.Option{
|
||||
{Value: "nickname", Label: "玩家昵称"}, {Value: "greeting", Label: "个人简介"}, {Value: "master_title", Label: "主角称呼"},
|
||||
{Value: "preset_name", Label: "配队预设名"}, {Value: "equipment_preset_name", Label: "装备预设名"}, {Value: "equipment_mark", Label: "装备标记"},
|
||||
{Value: "monster_hunt_preset_name", Label: "魔兽追踪者预设名"}, {Value: "guild_raid_preset_name", Label: "公会战预设名"},
|
||||
{Value: "colosseum_preset_name", Label: "斗兽场预设名"}, {Value: "guild_name", Label: "公会名称"}, {Value: "guild_message", Label: "公会介绍"},
|
||||
{Value: "guild_notice", Label: "公会公告"}, {Value: "room_name", Label: "房间名称"}, {Value: "chat", Label: "联机聊天"},
|
||||
}},
|
||||
{Path: "text_moderation.provider.timeout_ms", Kind: commonconfig.KindInteger, Label: "超时(毫秒)", Min: timeoutMin, Max: timeoutMax, Advanced: true},
|
||||
{Path: "text_moderation.provider.failure_policy", Kind: commonconfig.KindString, Label: "接口故障时", Advanced: true, Options: []commonconfig.Option{
|
||||
{Value: "deny", Label: "暂不接受修改", Help: "客户端提示审核暂时不可用。"},
|
||||
{Value: "allow", Label: "放行", Help: "放行已通过本地规则的文本;明确拒绝的结果不会被放行。"},
|
||||
}},
|
||||
{Path: "text_moderation.provider.severity_threshold", Kind: commonconfig.KindInteger, Label: "Azure 拒绝阈值", Min: severityMin, Max: severityMax, Advanced: true,
|
||||
Help: "任一类别达到该严重程度即拒绝;0 表示连严重程度 0 的结果也拒绝。"},
|
||||
}},
|
||||
{ID: "format", Title: "格式", Fields: []commonconfig.Field{
|
||||
{Path: "schema_version", Kind: commonconfig.KindInteger, Label: "格式版本", Advanced: true, Options: []commonconfig.Option{{Value: 1, Label: "1"}}},
|
||||
}},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package gamedata
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
// MailCatalogItem is one attachment an operator can send through the dynamic
|
||||
// mail spool. Category is a stable key; presentation text belongs to clients.
|
||||
type MailCatalogItem struct {
|
||||
ElementType uint64 `json:"element_type"`
|
||||
ID uint64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Category string `json:"category"`
|
||||
Aliases []string `json:"aliases,omitempty"`
|
||||
// Set when a deterministic RandomBox wraps this item: the catalog offers
|
||||
// the contained item directly instead of the box.
|
||||
SourceBoxes []uint64 `json:"source_boxes,omitempty"`
|
||||
OriginalName string `json:"original_name,omitempty"`
|
||||
BoxName string `json:"box_name,omitempty"`
|
||||
ProductName string `json:"product_name,omitempty"`
|
||||
|
||||
sourceTable string
|
||||
resourceType uint64
|
||||
}
|
||||
|
||||
type mailItemSource struct {
|
||||
table string
|
||||
elementType uint64
|
||||
idField, nameField int
|
||||
category, textTable string
|
||||
}
|
||||
|
||||
// ItemDBInfo-backed tables and their text namespaces. Item names use distinct
|
||||
// GameData text tables, so the owning namespace is part of this mapping.
|
||||
var mailItemSources = []mailItemSource{
|
||||
{"ResourceTable", 8, 4, 7, "resource", "NameTextTable"},
|
||||
{"FoodTable", 5, 7, 10, "food", "NameTextTable"},
|
||||
{"CookingTable", 7, 3, 11, "cooking", "NameTextTable"},
|
||||
{"RandomBoxTable", 9, 4, 7, "random_box", "RandomBoxTextTable"},
|
||||
{"QuestItemTable", 13, 2, 5, "quest_item", "NameTextTable"},
|
||||
{"UseItemTable", 14, 3, 6, "use_item", "NameTextTable"},
|
||||
{"CollectionTable", 17, 3, 7, "collection", "NameTextTable"},
|
||||
{"MyRoomItemTable", 27, 7, 17, "my_room", "NameTextTable"},
|
||||
{"InstantUseItemTable", 29, 1, 3, "instant_use", "NameTextTable"},
|
||||
}
|
||||
|
||||
// MailCurrencyTypes are the account currencies whose mail claim is credited
|
||||
// directly; their reward ID is zero.
|
||||
var MailCurrencyTypes = []uint64{2, 3, 4, 12, 20}
|
||||
|
||||
// LoadMailCatalog returns every safe direct-mail attachment in GameData.
|
||||
func LoadMailCatalog(root, version string) ([]MailCatalogItem, error) {
|
||||
var items []MailCatalogItem
|
||||
err := WithDatabase(root, version, "common", func(db *sql.DB) error {
|
||||
var err error
|
||||
items, err = loadMailCatalog(db)
|
||||
return err
|
||||
})
|
||||
return items, err
|
||||
}
|
||||
|
||||
func loadMailCatalog(db *sql.DB) ([]MailCatalogItem, error) {
|
||||
names := map[string]map[uint64]string{}
|
||||
for _, table := range []string{"NameTextTable", "RandomBoxTextTable", "LocalTextTable"} {
|
||||
values, err := localizedNames(db, table)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names[table] = values
|
||||
}
|
||||
var items []MailCatalogItem
|
||||
for _, source := range mailItemSources {
|
||||
err := eachRow(db, source.table, "ORDER BY id", func(rowID uint64, proto []byte) error {
|
||||
id := singleVarint(proto, source.idField)
|
||||
if id == 0 {
|
||||
id = rowID
|
||||
}
|
||||
item := MailCatalogItem{ElementType: source.elementType, ID: id, Category: source.category, sourceTable: source.table,
|
||||
Name: names[source.textTable][singleVarint(proto, source.nameField)]}
|
||||
if source.table == "ResourceTable" {
|
||||
item.resourceType = singleVarint(proto, 13)
|
||||
}
|
||||
items = append(items, item)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
err := eachRow(db, "CurrencyTable", "ORDER BY id", func(rowID uint64, proto []byte) error {
|
||||
elementType := singleVarint(proto, 3)
|
||||
if elementType == 0 {
|
||||
elementType = rowID
|
||||
}
|
||||
if slices.Contains(MailCurrencyTypes, elementType) {
|
||||
items = append(items, MailCatalogItem{ElementType: elementType, Category: "currency", Name: names["NameTextTable"][singleVarint(proto, 5)]})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(items) == 0 {
|
||||
return nil, errors.New("gamedata: mail catalog tables are empty")
|
||||
}
|
||||
fixedBoxes, err := fixedRandomBoxes(db, items)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
productNames := map[uint64]map[string]int{}
|
||||
err = eachRow(db, "CashProductTable", "", func(_ uint64, proto []byte) error {
|
||||
box := singleVarint(proto, 14)
|
||||
name := names["LocalTextTable"][singleVarint(proto, 11)]
|
||||
if _, fixed := fixedBoxes[box]; box != 0 && name != "" && fixed {
|
||||
if productNames[box] == nil {
|
||||
productNames[box] = map[string]int{}
|
||||
}
|
||||
productNames[box][name]++
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return directMailItems(items, fixedBoxes, productNames), nil
|
||||
}
|
||||
|
||||
type boxReward struct{ elementType, id uint64 }
|
||||
|
||||
// fixedRandomBoxes follows only one-entry RewardGroupTable definitions: a
|
||||
// deterministic GameData relationship rather than an invented unpack result.
|
||||
func fixedRandomBoxes(db *sql.DB, items []MailCatalogItem) (map[uint64]boxReward, error) {
|
||||
known := map[boxReward]bool{}
|
||||
for _, item := range items {
|
||||
known[boxReward{item.ElementType, item.ID}] = true
|
||||
}
|
||||
groups := map[uint64]boxReward{}
|
||||
err := eachRow(db, "RewardGroupTable", "", func(groupID uint64, proto []byte) error {
|
||||
ids, idErr := packedInts(proto, 5)
|
||||
types, typeErr := packedInts(proto, 6)
|
||||
counts, countErr := packedInts(proto, 4)
|
||||
if err := errors.Join(idErr, typeErr, countErr); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) != 1 || len(types) != 1 || len(counts) != 1 || types[0] == 0 || counts[0] == 0 {
|
||||
return nil
|
||||
}
|
||||
currency := slices.Contains(MailCurrencyTypes, types[0])
|
||||
if currency != (ids[0] == 0) {
|
||||
return nil
|
||||
}
|
||||
groups[groupID] = boxReward{types[0], ids[0]}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
boxes := map[uint64]boxReward{}
|
||||
err = eachRow(db, "RandomBoxTable", "", func(boxID uint64, proto []byte) error {
|
||||
if reward, ok := groups[singleVarint(proto, 9)]; ok && known[reward] {
|
||||
boxes[boxID] = reward
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return boxes, err
|
||||
}
|
||||
|
||||
// directMailItems hides deterministic boxes and exposes their contained item
|
||||
// directly. The quantity an operator enters is the final material count.
|
||||
func directMailItems(items []MailCatalogItem, fixedBoxes map[uint64]boxReward, productNames map[uint64]map[string]int) []MailCatalogItem {
|
||||
index := map[boxReward]int{}
|
||||
for i, item := range items {
|
||||
index[boxReward{item.ElementType, item.ID}] = i
|
||||
}
|
||||
type wrapping struct {
|
||||
boxes []uint64
|
||||
boxNames map[string]int
|
||||
productNames map[string]int
|
||||
}
|
||||
wrapped := map[int]*wrapping{}
|
||||
boxIDs := make([]uint64, 0, len(fixedBoxes))
|
||||
for id := range fixedBoxes {
|
||||
boxIDs = append(boxIDs, id)
|
||||
}
|
||||
slices.Sort(boxIDs)
|
||||
for _, boxID := range boxIDs {
|
||||
target, ok := index[fixedBoxes[boxID]]
|
||||
box, boxOK := index[boxReward{9, boxID}]
|
||||
if !ok || !boxOK {
|
||||
continue
|
||||
}
|
||||
w := wrapped[target]
|
||||
if w == nil {
|
||||
w = &wrapping{boxNames: map[string]int{}, productNames: map[string]int{}}
|
||||
wrapped[target] = w
|
||||
}
|
||||
w.boxes = append(w.boxes, boxID)
|
||||
if usableName(items[box].Name) {
|
||||
w.boxNames[items[box].Name]++
|
||||
}
|
||||
for name, count := range productNames[boxID] {
|
||||
if usableName(name) {
|
||||
w.productNames[name] += count
|
||||
}
|
||||
}
|
||||
}
|
||||
for target, w := range wrapped {
|
||||
item := &items[target]
|
||||
original := item.Name
|
||||
product := mostFrequent(w.productNames)
|
||||
box := ""
|
||||
if len(w.boxNames) == 1 {
|
||||
for name := range w.boxNames {
|
||||
box = name
|
||||
}
|
||||
}
|
||||
// A single agreed wrapper name is the most specific label for a
|
||||
// generic resource row; product names are only a fallback because
|
||||
// some describe expiry or conversion behavior.
|
||||
if usableName(original) && box != "" && box != original {
|
||||
item.Name = box
|
||||
} else if !usableName(original) && product != "" {
|
||||
item.Name = product
|
||||
}
|
||||
for _, alias := range []string{original, box, product} {
|
||||
if usableName(alias) && alias != item.Name && !slices.Contains(item.Aliases, alias) {
|
||||
item.Aliases = append(item.Aliases, alias)
|
||||
}
|
||||
}
|
||||
item.SourceBoxes = w.boxes
|
||||
if original != item.Name && usableName(original) {
|
||||
item.OriginalName = original
|
||||
}
|
||||
if box != item.Name {
|
||||
item.BoxName = box
|
||||
}
|
||||
if product != item.Name {
|
||||
item.ProductName = product
|
||||
}
|
||||
}
|
||||
safe := items[:0]
|
||||
for _, item := range items {
|
||||
// RandomBox needs a second protocol and its entered count is not the
|
||||
// final reward count. ResourceTable Type=2 rows are field-object
|
||||
// presentation sentinels that crash the client's item popup.
|
||||
if item.ElementType == 9 || item.sourceTable == "ResourceTable" && item.resourceType == 2 || !usableName(item.Name) {
|
||||
continue
|
||||
}
|
||||
safe = append(safe, item)
|
||||
}
|
||||
return safe
|
||||
}
|
||||
|
||||
func mostFrequent(values map[string]int) string {
|
||||
best := ""
|
||||
for value, count := range values {
|
||||
if best == "" || count > values[best] || count == values[best] &&
|
||||
(utf8.RuneCountInString(value) < utf8.RuneCountInString(best) || utf8.RuneCountInString(value) == utf8.RuneCountInString(best) && value > best) {
|
||||
best = value
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
func usableName(value string) bool {
|
||||
return value != "" && value != "(不使用)" && value != "(不使用)"
|
||||
}
|
||||
|
||||
// localizedNames reads the common localized-text protobuf shape.
|
||||
func localizedNames(db *sql.DB, table string) (map[uint64]string, error) {
|
||||
names := map[uint64]string{}
|
||||
err := eachRow(db, table, "", func(rowID uint64, proto []byte) error {
|
||||
textID := singleVarint(proto, 2)
|
||||
if textID == 0 {
|
||||
textID = rowID
|
||||
}
|
||||
for _, field := range []int{4, 5, 3} {
|
||||
if name := singleText(proto, field); name != "" {
|
||||
names[textID] = name
|
||||
break
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return names, err
|
||||
}
|
||||
|
||||
func eachRow(db *sql.DB, table, order string, visit func(uint64, []byte) error) error {
|
||||
rows, err := db.Query(fmt.Sprintf(`SELECT id, ProtoBuf FROM "%s" %s`, strings.ReplaceAll(table, `"`, `""`), order))
|
||||
if err != nil {
|
||||
return fmt.Errorf("gamedata: read %s: %w", table, err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
var proto []byte
|
||||
if err := rows.Scan(&id, &proto); err != nil {
|
||||
return fmt.Errorf("gamedata: read %s: %w", table, err)
|
||||
}
|
||||
if id < 0 {
|
||||
return fmt.Errorf("gamedata: %s has negative id %d", table, id)
|
||||
}
|
||||
if err := visit(uint64(id), proto); err != nil {
|
||||
return fmt.Errorf("gamedata: %s row %d: %w", table, id, err)
|
||||
}
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
// singleVarint returns a scalar varint field, or zero when it is absent,
|
||||
// repeated or not encoded as a plain varint.
|
||||
func singleVarint(proto []byte, number int) uint64 {
|
||||
var value uint64
|
||||
count := 0
|
||||
_ = wire.Walk(proto, func(field wire.Field) error {
|
||||
if field.Number == number {
|
||||
count++
|
||||
if field.Type == 0 {
|
||||
value, _ = binary.Uvarint(field.Value)
|
||||
} else {
|
||||
count = 2
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if count != 1 {
|
||||
return 0
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func singleText(proto []byte, number int) string {
|
||||
var value []byte
|
||||
count := 0
|
||||
_ = wire.Walk(proto, func(field wire.Field) error {
|
||||
if field.Number == number {
|
||||
count++
|
||||
if field.Type == 2 {
|
||||
value = field.Value
|
||||
} else {
|
||||
count = 2
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if count != 1 || !utf8.Valid(value) {
|
||||
return ""
|
||||
}
|
||||
return string(value)
|
||||
}
|
||||
|
||||
// SortMailCatalog orders items by category position and ID for stable display.
|
||||
func SortMailCatalog(items []MailCatalogItem) {
|
||||
order := map[string]int{"currency": 0}
|
||||
for i, source := range mailItemSources {
|
||||
order[source.category] = i + 1
|
||||
}
|
||||
sort.SliceStable(items, func(i, j int) bool {
|
||||
a, b := items[i], items[j]
|
||||
if order[a.Category] != order[b.Category] {
|
||||
return order[a.Category] < order[b.Category]
|
||||
}
|
||||
if a.ElementType != b.ElementType {
|
||||
return a.ElementType < b.ElementType
|
||||
}
|
||||
return a.ID < b.ID
|
||||
})
|
||||
}
|
||||
@@ -436,3 +436,7 @@ func (s *Service) AuthorizeAdministrator(token string) (string, error) {
|
||||
}
|
||||
return accountID, nil
|
||||
}
|
||||
|
||||
// AdministratorAccountID returns the first registered account, or "" before
|
||||
// any account exists.
|
||||
func (s *Service) AdministratorAccountID() (string, error) { return s.store.AdministratorAccountID() }
|
||||
@@ -1,21 +1,18 @@
|
||||
package inventory
|
||||
|
||||
import (
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
)
|
||||
|
||||
const developmentSettingsVersion = 2
|
||||
|
||||
type InventorySlotCounts struct {
|
||||
Items uint64 `json:"items"`
|
||||
Storage uint64 `json:"storage"`
|
||||
@@ -28,15 +25,45 @@ type inventorySlotSnapshot struct {
|
||||
InventorySlotCounts
|
||||
}
|
||||
|
||||
type developmentSettings struct {
|
||||
Version int `json:"version"`
|
||||
Accounts map[string]*developmentAccountSettings `json:"accounts"`
|
||||
// DevelopmentSettings is the operator's per-account development overrides
|
||||
// file. It is read at each login, so edits apply on the next login.
|
||||
type DevelopmentSettings struct {
|
||||
Version int `json:"version"`
|
||||
Accounts map[string]DevelopmentAccount `json:"accounts"`
|
||||
}
|
||||
|
||||
type developmentAccountSettings struct {
|
||||
Inventory *struct {
|
||||
Unlimited *bool `json:"unlimited"`
|
||||
} `json:"inventory"`
|
||||
type DevelopmentAccount struct {
|
||||
Inventory DevelopmentInventory `json:"inventory"`
|
||||
}
|
||||
|
||||
type DevelopmentInventory struct {
|
||||
Unlimited bool `json:"unlimited"`
|
||||
}
|
||||
|
||||
var DevelopmentSettingsDocument = commonconfig.Document[DevelopmentSettings]{
|
||||
Name: "dev-tools",
|
||||
FileName: "dev-tools.json",
|
||||
Defaults: func() DevelopmentSettings {
|
||||
return DevelopmentSettings{Version: 2, Accounts: map[string]DevelopmentAccount{}}
|
||||
},
|
||||
Base: func() DevelopmentSettings { return DevelopmentSettings{} },
|
||||
Decode: commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true, RejectNull: true},
|
||||
Schema: commonconfig.Schema{Title: "开发覆盖", Sections: []commonconfig.Section{{ID: "format", Title: "格式", Fields: []commonconfig.Field{
|
||||
{Path: "version", Kind: commonconfig.KindInteger, Label: "格式版本", Required: true, Options: []commonconfig.Option{{Value: 2, Label: "2"}}},
|
||||
{Path: "accounts", Kind: commonconfig.KindMap, Label: "账号", Required: true},
|
||||
{Path: "accounts.*.inventory", Kind: commonconfig.KindMap, Label: "背包", Required: true},
|
||||
{Path: "accounts.*.inventory.unlimited", Kind: commonconfig.KindBool, Label: "无限背包容量", Required: true},
|
||||
}}}},
|
||||
Rules: func(settings DevelopmentSettings) commonconfig.Problems {
|
||||
var problems commonconfig.Problems
|
||||
if settings.Accounts == nil {
|
||||
problems.Add("accounts", commonconfig.RuleRequired, "is required")
|
||||
}
|
||||
if _, ok := settings.Accounts[""]; ok {
|
||||
problems.Add("accounts", commonconfig.RuleFormat, "account IDs must be nonempty")
|
||||
}
|
||||
return problems
|
||||
},
|
||||
}
|
||||
|
||||
type inventorySlotReply struct {
|
||||
@@ -151,28 +178,11 @@ func loadUnlimitedInventory(path, accountID string) (bool, error) {
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("player: read development settings: %w", err)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
decoder.DisallowUnknownFields()
|
||||
var settings developmentSettings
|
||||
if err := decoder.Decode(&settings); err != nil {
|
||||
return false, errors.New("player: malformed development settings")
|
||||
settings, err := DevelopmentSettingsDocument.Parse(data)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("player: malformed development settings: %w", err)
|
||||
}
|
||||
if err := decoder.Decode(&struct{}{}); err != io.EOF {
|
||||
return false, errors.New("player: malformed development settings")
|
||||
}
|
||||
if settings.Version != developmentSettingsVersion {
|
||||
return false, errors.New("player: unsupported development settings version")
|
||||
}
|
||||
if settings.Accounts == nil {
|
||||
return false, errors.New("player: malformed development settings")
|
||||
}
|
||||
for id, account := range settings.Accounts {
|
||||
if id == "" || account == nil || account.Inventory == nil || account.Inventory.Unlimited == nil {
|
||||
return false, errors.New("player: malformed development settings")
|
||||
}
|
||||
}
|
||||
account := settings.Accounts[accountID]
|
||||
return account != nil && *account.Inventory.Unlimited, nil
|
||||
return settings.Accounts[accountID].Inventory.Unlimited, nil
|
||||
}
|
||||
|
||||
func inventorySlotPrice(rule gamedata.InventorySlotRule, current, count uint64) (uint64, error) {
|
||||
|
||||
@@ -10,9 +10,11 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
)
|
||||
@@ -85,6 +87,38 @@ func (s *Service) AttachGrantSpoolPath(ctx command.Context, path string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
var spoolWriter sync.Mutex
|
||||
|
||||
// AppendGrant atomically adds one grant to the spool at path. The complete
|
||||
// result is decoded with the mailbox's own rules before it replaces the file,
|
||||
// so this process never publishes a spool that /MailInfo would reject.
|
||||
func AppendGrant(path string, grant Grant) error {
|
||||
spoolWriter.Lock()
|
||||
defer spoolWriter.Unlock()
|
||||
spool := GrantSpool{Version: 2, Grants: []Grant{}}
|
||||
raw, err := os.ReadFile(path)
|
||||
switch {
|
||||
case err == nil:
|
||||
if _, err := decodeGrantSpool(raw, grant.AccountID); err != nil {
|
||||
return fmt.Errorf("mail: reject existing grant spool: %w", err)
|
||||
}
|
||||
if err := json.Unmarshal(raw, &spool); err != nil {
|
||||
return err
|
||||
}
|
||||
case !os.IsNotExist(err):
|
||||
return fmt.Errorf("mail: read grant spool: %w", err)
|
||||
}
|
||||
spool.Grants = append(spool.Grants, grant)
|
||||
encoded, err := json.MarshalIndent(spool, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := decodeGrantSpool(encoded, grant.AccountID); err != nil {
|
||||
return err
|
||||
}
|
||||
return commonconfig.WriteFile(path, append(encoded, '\n'))
|
||||
}
|
||||
|
||||
func readGrantSpool(path, accountID string) ([]compensation, error) {
|
||||
if strings.TrimSpace(accountID) == "" {
|
||||
return nil, errors.New("mail: grant spool requires command account identity")
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ConsoleLogin is a provider login started for the server's own web console.
|
||||
// The device secret never leaves the server process.
|
||||
type ConsoleLogin struct {
|
||||
ID string
|
||||
Secret string
|
||||
StartURL string
|
||||
Expires time.Time
|
||||
}
|
||||
|
||||
// Providers lists the enabled login providers in display order.
|
||||
func (s *Service) Providers() []string { return s.config.Public().Providers }
|
||||
|
||||
// BeginConsoleLogin starts the same device transaction the game client uses.
|
||||
func (s *Service) BeginConsoleLogin(provider, clientIP string) (ConsoleLogin, error) {
|
||||
if !s.limits.allow("create:"+clientIP, s.identity.Now(), time.Minute, 10) {
|
||||
return ConsoleLogin{}, ErrRateLimited
|
||||
}
|
||||
device, err := s.identity.CreateDevice(provider, clientIP)
|
||||
if err != nil {
|
||||
return ConsoleLogin{}, err
|
||||
}
|
||||
return ConsoleLogin{ID: device.ID, Secret: device.Secret, StartURL: s.startURL(provider, device), Expires: s.identity.Now().Add(s.config.DeviceTTL)}, nil
|
||||
}
|
||||
|
||||
// FinishConsoleLogin polls a console login. Once the provider completes it,
|
||||
// the issued game tokens are revoked at once: the console keeps its own
|
||||
// session and needs only the verified account.
|
||||
func (s *Service) FinishConsoleLogin(id, secret string) (accountID string, complete bool, err error) {
|
||||
result, err := s.identity.Poll(id, secret)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
switch result.Status {
|
||||
case "pending":
|
||||
return "", false, nil
|
||||
case "complete":
|
||||
accountID, err = s.identity.ValidateAccess(result.Tokens.AccessToken)
|
||||
revokeErr := s.identity.Revoke(result.Tokens.AccessToken)
|
||||
if err != nil {
|
||||
return "", false, err
|
||||
}
|
||||
return accountID, true, revokeErr
|
||||
default:
|
||||
return "", false, ErrLoginRejected
|
||||
}
|
||||
}
|
||||
|
||||
// AdministratorAccountID returns the first registered game account.
|
||||
func (s *Service) AdministratorAccountID() (string, error) {
|
||||
return s.identity.AdministratorAccountID()
|
||||
}
|
||||
|
||||
var (
|
||||
ErrRateLimited = errors.New("auth: too many login attempts")
|
||||
ErrLoginRejected = errors.New("auth: login was rejected")
|
||||
)
|
||||
@@ -151,13 +151,16 @@ func (s *Service) createDevice(w http.ResponseWriter, r *http.Request) {
|
||||
writeFailure(w, err, "could not create transaction")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"transaction_id": result.ID, "device_secret": result.Secret, "start_url": s.startURL(request.Provider, result), "expires_in": int64(s.config.DeviceTTL.Seconds()), "poll_interval": 2})
|
||||
}
|
||||
func (s *Service) startURL(provider string, device identity.CreatedDevice) string {
|
||||
start := *s.config.PublicURLParsed
|
||||
start.Path = "/auth/" + request.Provider + "/start"
|
||||
start.Path = "/auth/" + provider + "/start"
|
||||
query := start.Query()
|
||||
query.Set("transaction_id", result.ID)
|
||||
query.Set("ticket", result.StartTicket)
|
||||
query.Set("transaction_id", device.ID)
|
||||
query.Set("ticket", device.StartTicket)
|
||||
start.RawQuery = query.Encode()
|
||||
writeJSON(w, http.StatusCreated, map[string]any{"transaction_id": result.ID, "device_secret": result.Secret, "start_url": start.String(), "expires_in": int64(s.config.DeviceTTL.Seconds()), "poll_interval": 2})
|
||||
return start.String()
|
||||
}
|
||||
func (s *Service) start(w http.ResponseWriter, r *http.Request) {
|
||||
provider := r.PathValue("provider")
|
||||
@@ -233,7 +236,7 @@ func (s *Service) callback(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'")
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, `<!doctype html><meta charset="utf-8"><title>BD2 login</title><p>Login complete. You can return to the game.</p>`)
|
||||
_, _ = io.WriteString(w, `<!doctype html><meta charset="utf-8"><title>BD2 login</title><p>Login complete. You can close this page and return to the game or console.</p>`)
|
||||
}
|
||||
func (s *Service) poll(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
|
||||
@@ -3,11 +3,9 @@ package authconfig
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -16,8 +14,6 @@ import (
|
||||
|
||||
const FileName = "authentication.json"
|
||||
|
||||
// TODO: Replace the executable-adjacent file with a small authenticated
|
||||
// configuration API while keeping this policy server-authoritative.
|
||||
type Config struct {
|
||||
Mode string `json:"mode"`
|
||||
PublicURL string `json:"public_url,omitempty"`
|
||||
@@ -54,75 +50,127 @@ type Public struct {
|
||||
|
||||
func Default() Config { return Config{Mode: "local"} }
|
||||
|
||||
func Load(path string) (Config, error) {
|
||||
path, err := filepath.Abs(filepath.Clean(path))
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("authconfig: resolve path: %w", err)
|
||||
}
|
||||
if err := commonconfig.Ensure(path, Default(), commonconfig.WriteOptions{}); err != nil {
|
||||
return Config{}, fmt.Errorf("authconfig: initialize %s: %w", path, err)
|
||||
}
|
||||
config, err := commonconfig.Load(path, Config{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true})
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("authconfig: load %s: %w", path, err)
|
||||
}
|
||||
if err := config.Validate(); err != nil {
|
||||
return Config{}, fmt.Errorf("authconfig: %s: %w", path, err)
|
||||
}
|
||||
return config, nil
|
||||
var oauth = &commonconfig.Condition{Path: "mode", In: []any{"oauth"}}
|
||||
|
||||
// Document is authentication.json. Omitted values stay empty rather than
|
||||
// taking defaults so that a local-mode file cannot silently gain OAuth.
|
||||
var Document = commonconfig.Document[Config]{
|
||||
Name: "authentication",
|
||||
FileName: FileName,
|
||||
Defaults: Default,
|
||||
Base: func() Config { return Config{} },
|
||||
Decode: commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true},
|
||||
Schema: commonconfig.Schema{
|
||||
Title: "登录与认证",
|
||||
Summary: "玩家登录方式。修改后重启服务端生效;密钥只从环境变量读取,不写入此文件。",
|
||||
Sections: []commonconfig.Section{
|
||||
{ID: "mode", Title: "认证模式", Fields: []commonconfig.Field{
|
||||
{Path: "mode", Kind: commonconfig.KindString, Label: "模式", Options: []commonconfig.Option{
|
||||
{Value: "local", Label: "本地单人", Help: "无需登录,只有一个本地玩家。"},
|
||||
{Value: "oauth", Label: "OAuth 联机", Help: "玩家通过 Discord 或 Google 登录,服务器可供多人使用。"},
|
||||
}},
|
||||
{Path: "public_url", Kind: commonconfig.KindString, Label: "公开地址", Format: "origin", Placeholder: "https://game.example.com", When: oauth,
|
||||
Help: "玩家和 OAuth 回调访问的根地址,不带路径;除 localhost 外必须使用 HTTPS。"},
|
||||
{Path: "master_key_env", Kind: commonconfig.KindString, Label: "主密钥环境变量", Format: "env", When: oauth,
|
||||
Help: "该环境变量须为 base64 编码的 32 字节密钥,用于加密登录数据。"},
|
||||
}},
|
||||
{ID: "providers", Title: "登录提供方", Help: "回调地址为 公开地址/auth/<提供方>/callback。", Fields: []commonconfig.Field{
|
||||
{Path: "providers", Kind: commonconfig.KindMap, Label: "启用的提供方", When: oauth, Keys: []commonconfig.Option{
|
||||
{Value: "discord", Label: "Discord"}, {Value: "google", Label: "Google"},
|
||||
}},
|
||||
{Path: "providers.*.client_id", Kind: commonconfig.KindString, Label: "Client ID", When: oauth},
|
||||
{Path: "providers.*.client_secret_env", Kind: commonconfig.KindString, Label: "Client secret 环境变量", Format: "env", When: oauth},
|
||||
}},
|
||||
{ID: "session", Title: "会话时长", Help: "使用 Go 时长格式,例如 15m、720h。留空使用默认值。", Fields: []commonconfig.Field{
|
||||
{Path: "session.access_ttl", Kind: commonconfig.KindString, Label: "访问令牌有效期", Format: "duration", Placeholder: "15m", Advanced: true},
|
||||
{Path: "session.refresh_ttl", Kind: commonconfig.KindString, Label: "刷新令牌有效期", Format: "duration", Placeholder: "720h", Advanced: true},
|
||||
{Path: "session.device_transaction_ttl", Kind: commonconfig.KindString, Label: "登录事务有效期", Format: "duration", Placeholder: "10m", Advanced: true},
|
||||
}},
|
||||
},
|
||||
},
|
||||
Rules: rules,
|
||||
Advice: func(c Config, _ string) commonconfig.Problems {
|
||||
var advice commonconfig.Problems
|
||||
if c.Mode != "oauth" {
|
||||
return advice
|
||||
}
|
||||
if c.MasterKeyEnv != "" {
|
||||
if key, err := base64.StdEncoding.DecodeString(os.Getenv(c.MasterKeyEnv)); err != nil || len(key) != 32 {
|
||||
advice.Add("master_key_env", commonconfig.RuleEnvironment, "environment variable %s is not a base64-encoded 32-byte key in this server process", c.MasterKeyEnv)
|
||||
}
|
||||
}
|
||||
for _, name := range providerNames(c) {
|
||||
if env := c.Providers[name].ClientSecretEnv; env != "" && strings.TrimSpace(os.Getenv(env)) == "" {
|
||||
advice.Add("providers."+name+".client_secret_env", commonconfig.RuleEnvironment, "environment variable %s is empty in this server process", env)
|
||||
}
|
||||
}
|
||||
return advice
|
||||
},
|
||||
}
|
||||
|
||||
func BesideExecutable() (string, error) {
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("authconfig: resolve executable: %w", err)
|
||||
}
|
||||
return filepath.Join(filepath.Dir(executable), FileName), nil
|
||||
}
|
||||
|
||||
func (c Config) Validate() error {
|
||||
if c.Mode != "local" && c.Mode != "oauth" {
|
||||
return errors.New("mode must be local or oauth")
|
||||
}
|
||||
func rules(c Config) commonconfig.Problems {
|
||||
var problems commonconfig.Problems
|
||||
if c.Mode == "local" {
|
||||
if c.PublicURL != "" || c.MasterKeyEnv != "" || len(c.Providers) != 0 {
|
||||
return errors.New("local mode must not configure OAuth")
|
||||
if c.PublicURL != "" {
|
||||
problems.Add("public_url", commonconfig.RuleConflict, "local mode must not configure OAuth")
|
||||
}
|
||||
return validateTTLs(c.Session)
|
||||
}
|
||||
if c.MasterKeyEnv == "" || c.PublicURL == "" || len(c.Providers) == 0 {
|
||||
return errors.New("oauth mode requires public_url, master_key_env, and providers")
|
||||
}
|
||||
publicURL, err := url.Parse(c.PublicURL)
|
||||
if err != nil || publicURL.Host == "" || publicURL.User != nil || publicURL.RawQuery != "" || publicURL.Fragment != "" || publicURL.Path != "" {
|
||||
return errors.New("public_url must be an absolute origin without path, query, fragment, or user info")
|
||||
}
|
||||
localhost := publicURL.Hostname() == "127.0.0.1" || publicURL.Hostname() == "localhost" || publicURL.Hostname() == "::1"
|
||||
if publicURL.Scheme != "https" && !(localhost && publicURL.Scheme == "http") { //nolint:staticcheck // QF1001
|
||||
return errors.New("public_url must use HTTPS except on localhost")
|
||||
}
|
||||
for name, provider := range c.Providers {
|
||||
if name != "discord" && name != "google" {
|
||||
return fmt.Errorf("unsupported provider %q", name)
|
||||
if c.MasterKeyEnv != "" {
|
||||
problems.Add("master_key_env", commonconfig.RuleConflict, "local mode must not configure OAuth")
|
||||
}
|
||||
if provider.ClientID == "" || provider.ClientSecretEnv == "" {
|
||||
return fmt.Errorf("provider %q requires client_id and client_secret_env", name)
|
||||
if len(c.Providers) != 0 {
|
||||
problems.Add("providers", commonconfig.RuleConflict, "local mode must not configure OAuth")
|
||||
}
|
||||
}
|
||||
return validateTTLs(c.Session)
|
||||
}
|
||||
|
||||
func validateTTLs(session SessionConfig) error {
|
||||
for name, raw := range map[string]string{"access_ttl": session.AccessTTL, "refresh_ttl": session.RefreshTTL, "device_transaction_ttl": session.DeviceTransactionTTL} {
|
||||
if raw != "" {
|
||||
if value, err := time.ParseDuration(raw); err != nil || value <= 0 {
|
||||
return fmt.Errorf("%s must be a positive Go duration", name)
|
||||
if c.Mode == "oauth" {
|
||||
if c.MasterKeyEnv == "" {
|
||||
problems.Add("master_key_env", commonconfig.RuleRequired, "is required in oauth mode")
|
||||
}
|
||||
if len(c.Providers) == 0 {
|
||||
problems.Add("providers", commonconfig.RuleRequired, "oauth mode requires at least one provider")
|
||||
}
|
||||
if c.PublicURL == "" {
|
||||
problems.Add("public_url", commonconfig.RuleRequired, "is required in oauth mode")
|
||||
} else if publicURL, err := url.Parse(c.PublicURL); err != nil || publicURL.Host == "" || publicURL.User != nil || publicURL.RawQuery != "" || publicURL.Fragment != "" || publicURL.Path != "" {
|
||||
problems.Add("public_url", commonconfig.RuleFormat, "must be an absolute origin without path, query, fragment, or user info")
|
||||
} else if localhost := publicURL.Hostname() == "127.0.0.1" || publicURL.Hostname() == "localhost" || publicURL.Hostname() == "::1"; publicURL.Scheme != "https" && (!localhost || publicURL.Scheme != "http") {
|
||||
problems.Add("public_url", commonconfig.RuleFormat, "must use HTTPS except on localhost")
|
||||
}
|
||||
for _, name := range providerNames(c) {
|
||||
provider := c.Providers[name]
|
||||
if provider.ClientID == "" {
|
||||
problems.Add("providers."+name+".client_id", commonconfig.RuleRequired, "is required")
|
||||
}
|
||||
if provider.ClientSecretEnv == "" {
|
||||
problems.Add("providers."+name+".client_secret_env", commonconfig.RuleRequired, "is required")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
for _, ttl := range [...]struct{ path, value string }{
|
||||
{"session.access_ttl", c.Session.AccessTTL}, {"session.refresh_ttl", c.Session.RefreshTTL}, {"session.device_transaction_ttl", c.Session.DeviceTransactionTTL},
|
||||
} {
|
||||
if ttl.value != "" {
|
||||
if value, err := time.ParseDuration(ttl.value); err != nil || value <= 0 {
|
||||
problems.Add(ttl.path, commonconfig.RuleFormat, "must be a positive Go duration")
|
||||
}
|
||||
}
|
||||
}
|
||||
return problems
|
||||
}
|
||||
|
||||
func providerNames(c Config) []string {
|
||||
var names []string
|
||||
for _, name := range []string{"discord", "google"} {
|
||||
if _, ok := c.Providers[name]; ok {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func Load(path string) (Config, error) { return Document.Load(path) }
|
||||
|
||||
func (c Config) Validate() error { return Document.Validate(c) }
|
||||
|
||||
func (c Config) ResolveEnvironment() (Runtime, error) {
|
||||
if err := c.Validate(); err != nil {
|
||||
return Runtime{}, err
|
||||
@@ -157,11 +205,5 @@ func (c Config) ResolveEnvironment() (Runtime, error) {
|
||||
}
|
||||
|
||||
func (c Config) Public() Public {
|
||||
view := Public{Mode: c.Mode, Providers: []string{}}
|
||||
for _, name := range []string{"discord", "google"} {
|
||||
if _, ok := c.Providers[name]; ok {
|
||||
view.Providers = append(view.Providers, name)
|
||||
}
|
||||
}
|
||||
return view
|
||||
return Public{Mode: c.Mode, Providers: append([]string{}, providerNames(c)...)}
|
||||
}
|
||||
@@ -114,6 +114,8 @@ type HTTP struct {
|
||||
CommerceManifest func() any
|
||||
RealtimeTickets http.Handler
|
||||
StoryCheckpoints http.Handler
|
||||
// Console is the built-in administration website below /admin/.
|
||||
Console http.Handler
|
||||
}
|
||||
|
||||
func (h HTTP) Handler() http.Handler {
|
||||
@@ -133,6 +135,10 @@ func (h HTTP) Handler() http.Handler {
|
||||
if h.AuthenticationHandler != nil {
|
||||
mux.Handle("/auth/", h.withAvailability(h.AuthenticationHandler))
|
||||
}
|
||||
if h.Console != nil {
|
||||
mux.Handle("/admin", h.Console)
|
||||
mux.Handle("/admin/", h.Console)
|
||||
}
|
||||
mux.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) })
|
||||
mux.HandleFunc("/game/", h.game)
|
||||
mux.HandleFunc("/livez", func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -3,11 +3,8 @@ package resourcepolicy
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
@@ -48,54 +45,64 @@ func Default() Config {
|
||||
}
|
||||
}
|
||||
|
||||
// Load reads one explicit resources.json. Unknown fields and trailing JSON are
|
||||
// rejected so a misspelled URL key cannot silently fall back to another CDN.
|
||||
func Load(path string) (Config, error) {
|
||||
if err := commonconfig.Ensure(path, Default(), commonconfig.WriteOptions{}); err != nil {
|
||||
return Config{}, fmt.Errorf("resource policy: initialize %s: %w", path, err)
|
||||
}
|
||||
cfg, err := commonconfig.Load(path, Config{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true})
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("resource policy: load %s: %w", path, err)
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return Config{}, fmt.Errorf("resource policy: %s: %w", path, err)
|
||||
}
|
||||
return cfg, nil
|
||||
// Document is resources.json. Unknown fields and trailing JSON are rejected
|
||||
// so a misspelled URL key cannot silently fall back to another CDN.
|
||||
var Document = commonconfig.Document[Config]{
|
||||
Name: "resources",
|
||||
FileName: FileName,
|
||||
Defaults: Default,
|
||||
Base: func() Config { return Config{} },
|
||||
Decode: commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true},
|
||||
Schema: commonconfig.Schema{
|
||||
Title: "客户端资源",
|
||||
Summary: "客户端下载 ServerData 与 GameData 的来源。修改后重启服务端生效;版本号来自 versions.json,不在此配置。",
|
||||
Sections: []commonconfig.Section{{ID: "source", Title: "资源来源", Fields: []commonconfig.Field{
|
||||
{Path: "mode", Kind: commonconfig.KindString, Label: "模式", Options: []commonconfig.Option{
|
||||
{Value: ModeOfficial, Label: "官方 CDN", Help: "使用当前版本的官方资源地址。"},
|
||||
{Value: ModeServer, Label: "自建资源源", Help: "从服主提供的静态 CDN 或缓存反代下载。"},
|
||||
}},
|
||||
{Path: "server_data_url", Kind: commonconfig.KindString, Label: "ServerData 地址", Format: "url", Placeholder: OfficialServerDataURL,
|
||||
When: &commonconfig.Condition{Path: "mode", In: []any{ModeServer}}, Help: "绝对 HTTP(S) 地址,末尾不带斜杠;除回环地址外必须使用 HTTPS。"},
|
||||
{Path: "game_data_url", Kind: commonconfig.KindString, Label: "GameData 地址", Format: "url", Placeholder: OfficialGameDataURL,
|
||||
When: &commonconfig.Condition{Path: "mode", In: []any{ModeServer}}, Help: "绝对 HTTP(S) 地址,末尾不带斜杠;除回环地址外必须使用 HTTPS。"},
|
||||
}}},
|
||||
},
|
||||
Rules: rules,
|
||||
}
|
||||
|
||||
// BesideExecutable returns the production configuration location.
|
||||
func BesideExecutable() (string, error) {
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resource policy: resolve server executable: %w", err)
|
||||
}
|
||||
return filepath.Join(filepath.Dir(executable), FileName), nil
|
||||
}
|
||||
func Load(path string) (Config, error) { return Document.Load(path) }
|
||||
|
||||
func (c Config) Validate() error {
|
||||
func (c Config) Validate() error { return Document.Validate(c) }
|
||||
|
||||
func rules(c Config) commonconfig.Problems {
|
||||
var problems commonconfig.Problems
|
||||
switch c.Mode {
|
||||
case ModeOfficial:
|
||||
if c.ServerDataURL == "" {
|
||||
c.ServerDataURL = OfficialServerDataURL
|
||||
if c.ServerDataURL != "" && c.ServerDataURL != OfficialServerDataURL {
|
||||
problems.Add("server_data_url", commonconfig.RuleConflict, "official mode must use the versioned official resource origin")
|
||||
}
|
||||
if c.GameDataURL == "" {
|
||||
c.GameDataURL = OfficialGameDataURL
|
||||
}
|
||||
if c.ServerDataURL != OfficialServerDataURL || c.GameDataURL != OfficialGameDataURL {
|
||||
return errors.New("official mode must use the versioned official resource origins")
|
||||
if c.GameDataURL != "" && c.GameDataURL != OfficialGameDataURL {
|
||||
problems.Add("game_data_url", commonconfig.RuleConflict, "official mode must use the versioned official resource origin")
|
||||
}
|
||||
case ModeServer:
|
||||
if c.ServerDataURL == "" || c.GameDataURL == "" {
|
||||
return errors.New("server_data_url and game_data_url are required")
|
||||
if c.ServerDataURL == "" {
|
||||
problems.Add("server_data_url", commonconfig.RuleRequired, "is required in server mode")
|
||||
}
|
||||
if c.GameDataURL == "" {
|
||||
problems.Add("game_data_url", commonconfig.RuleRequired, "is required in server mode")
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unsupported mode %q", c.Mode)
|
||||
return problems
|
||||
}
|
||||
if err := validateBaseURL("server_data_url", c.serverDataURL()); err != nil {
|
||||
return err
|
||||
for _, origin := range [...]struct{ path, value string }{{"server_data_url", c.serverDataURL()}, {"game_data_url", c.gameDataURL()}} {
|
||||
if origin.value == "" {
|
||||
continue
|
||||
}
|
||||
if err := validateBaseURL(origin.value); err != nil {
|
||||
problems.Add(origin.path, commonconfig.RuleFormat, "%s", err.Error())
|
||||
}
|
||||
}
|
||||
return validateBaseURL("game_data_url", c.gameDataURL())
|
||||
return problems
|
||||
}
|
||||
|
||||
func (c Config) Public(bundleVersion, gameDataVersion string) Public {
|
||||
@@ -122,17 +129,17 @@ func (c Config) gameDataURL() string {
|
||||
return c.GameDataURL
|
||||
}
|
||||
|
||||
func validateBaseURL(name, raw string) error {
|
||||
func validateBaseURL(raw string) error {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" ||
|
||||
(u.Scheme != "http" && u.Scheme != "https") {
|
||||
return fmt.Errorf("%s must be an absolute HTTP(S) URL without credentials, query, or fragment", name)
|
||||
return errors.New("must be an absolute HTTP(S) URL without credentials, query, or fragment")
|
||||
}
|
||||
if strings.HasSuffix(u.Path, "/") {
|
||||
return fmt.Errorf("%s must not have a trailing slash", name)
|
||||
return errors.New("must not have a trailing slash")
|
||||
}
|
||||
if u.Scheme == "http" && !isLoopbackHost(u.Hostname()) {
|
||||
return fmt.Errorf("%s must use HTTPS outside loopback development", name)
|
||||
return errors.New("must use HTTPS outside loopback development")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -37,3 +37,29 @@ func (s *Store) AccountForOwner(ctx context.Context, owner uint64) (string, erro
|
||||
}
|
||||
return account, err
|
||||
}
|
||||
|
||||
// Player is one game profile as listed by operator tools.
|
||||
type Player struct {
|
||||
AccountID string
|
||||
OwnerIndex int64
|
||||
UserID string
|
||||
Active bool
|
||||
}
|
||||
|
||||
// Players lists every account that has a public game profile, by UID.
|
||||
func (s *Store) Players(ctx context.Context) ([]Player, error) {
|
||||
rows, err := s.db.QueryContext(ctx, `SELECT p.account_id,p.owner_index,p.user_id,a.status='active' FROM game_profiles p JOIN accounts a ON a.id=p.account_id ORDER BY p.owner_index`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
var out []Player
|
||||
for rows.Next() {
|
||||
var player Player
|
||||
if err := rows.Scan(&player.AccountID, &player.OwnerIndex, &player.UserID, &player.Active); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, player)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
Reference in new issue
Block a user