Compare commits
24 Commits
a7bf3c7bb1
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 654a08add4 | |||
| 81becaf7c8 | |||
| 295defb89f | |||
| 5c4b77d957 | |||
| f4b71f58fd | |||
| ef639679d1 | |||
| 8c4dc0ee93 | |||
| 2301c57768 | |||
| cfe9ec9017 | |||
| 5f50b881ca | |||
| 05e192ca70 | |||
| 480423090a | |||
| 2e386a9d5c | |||
| 21a1462e62 | |||
| 41811d40af | |||
| 8e018a01e9 | |||
| 7e4177c6c0 | |||
| ecdaf9171b | |||
| f23b9030ed | |||
| 31497c38b2 | |||
| 21b9920f80 | |||
| 7224b9b834 | |||
| 45bb8b0de4 | |||
|
|
6138ba8c65 |
41
.gitea/ISSUE_TEMPLATE/bug_report.md
Normal file
41
.gitea/ISSUE_TEMPLATE/bug_report.md
Normal file
@@ -0,0 +1,41 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Report something that is broken or behaving unexpectedly
|
||||
title: "[bug] "
|
||||
labels:
|
||||
- bug
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
<!-- A clear, concise description of the bug. -->
|
||||
|
||||
## Steps to reproduce
|
||||
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
## Expected behavior
|
||||
|
||||
<!-- What you expected to happen. -->
|
||||
|
||||
## Actual behavior
|
||||
|
||||
<!-- What actually happened. Include exact error messages and logs if you have them. -->
|
||||
|
||||
## Environment
|
||||
|
||||
- Component / repo:
|
||||
- Version or commit:
|
||||
- OS / runtime (Node, Rust, ServUO, browser…):
|
||||
- Deployment (Docker Compose, local dev, bare metal…):
|
||||
|
||||
## Additional context
|
||||
|
||||
<!-- Screenshots, config (with secrets redacted), anything else that helps. -->
|
||||
|
||||
<!--
|
||||
Security issue? Do NOT file it here. See SECURITY.md and email
|
||||
whitlocktech@gmail.com instead.
|
||||
-->
|
||||
5
.gitea/ISSUE_TEMPLATE/config.yaml
Normal file
5
.gitea/ISSUE_TEMPLATE/config.yaml
Normal file
@@ -0,0 +1,5 @@
|
||||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: Security vulnerability
|
||||
url: https://gitea.whitlocktech.com/RunicGateway/link/src/branch/main/SECURITY.md
|
||||
about: Please do not open a public issue for security problems — report them privately by email instead (see SECURITY.md).
|
||||
23
.gitea/ISSUE_TEMPLATE/feature_request.md
Normal file
23
.gitea/ISSUE_TEMPLATE/feature_request.md
Normal file
@@ -0,0 +1,23 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea, enhancement, or new capability
|
||||
title: "[feature] "
|
||||
labels:
|
||||
- enhancement
|
||||
---
|
||||
|
||||
## Problem / motivation
|
||||
|
||||
<!-- What are you trying to do? What's missing or painful today? -->
|
||||
|
||||
## Proposed solution
|
||||
|
||||
<!-- What you'd like to see happen. -->
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
<!-- Other approaches you thought about, and why you prefer the one above. -->
|
||||
|
||||
## Additional context
|
||||
|
||||
<!-- Mockups, links, related issues, affected component/repo, etc. -->
|
||||
33
.gitea/PULL_REQUEST_TEMPLATE.md
Normal file
33
.gitea/PULL_REQUEST_TEMPLATE.md
Normal file
@@ -0,0 +1,33 @@
|
||||
<!--
|
||||
Thanks for contributing to Runic Gateway!
|
||||
Please fill out the sections below and check every box before requesting review.
|
||||
-->
|
||||
|
||||
## What & why
|
||||
|
||||
<!-- What does this PR change, and why? Link any related issue: "Closes #123". -->
|
||||
|
||||
## How it was tested
|
||||
|
||||
<!-- Commands you ran, manual steps, screenshots. -->
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] I have read [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
- [ ] The change builds and existing tests/checks pass locally.
|
||||
- [ ] I have added or updated tests/docs where it makes sense.
|
||||
- [ ] My commits are reasonably scoped with clear messages.
|
||||
|
||||
## AI-assisted contributions (required)
|
||||
|
||||
This project **requires disclosure of AI tool usage**. Please pick one:
|
||||
|
||||
- [ ] No AI tools were used to produce this contribution.
|
||||
- [ ] AI tools were used. Tool(s): `___________`. I have reviewed and understand
|
||||
every change, and take responsibility for it. AI-authored commits are
|
||||
marked with a `Co-Authored-By` / `Assisted-By` trailer.
|
||||
|
||||
## License
|
||||
|
||||
- [ ] I agree that my contribution is licensed under this project's license
|
||||
(**GNU GPL v3.0 or later**), and I have the right to contribute it.
|
||||
54
.gitea/scripts/gen_tree.py
Normal file
54
.gitea/scripts/gen_tree.py
Normal file
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Render an ASCII tree of tracked files, read from stdin (one path per line).
|
||||
|
||||
Used by the `sync-project-tree` workflow to regenerate this repo's PROJECT_TREE.md
|
||||
snapshot in the RunicGateway/docs repo. Feed it `git ls-files`:
|
||||
|
||||
git ls-files | python3 .gitea/scripts/gen_tree.py <root-label>
|
||||
|
||||
Deterministic ordering: directories before files, each group sorted
|
||||
case-insensitively with the raw name as a tiebreak. Output uses the classic
|
||||
`tree(1)` box-drawing style so the result is stable across runs and platforms.
|
||||
"""
|
||||
import sys
|
||||
|
||||
|
||||
def build(paths):
|
||||
root = {}
|
||||
for p in paths:
|
||||
p = p.strip().replace("\\", "/")
|
||||
if not p:
|
||||
continue
|
||||
node = root
|
||||
for part in p.split("/"):
|
||||
node = node.setdefault(part, {})
|
||||
return root
|
||||
|
||||
|
||||
def render(node, prefix, lines):
|
||||
entries = list(node.items())
|
||||
# directories (non-empty children dict) before files, then case-insensitive name
|
||||
entries.sort(key=lambda kv: (0 if kv[1] else 1, kv[0].lower(), kv[0]))
|
||||
for i, (name, child) in enumerate(entries):
|
||||
last = i == len(entries) - 1
|
||||
branch = "└── " if last else "├── "
|
||||
suffix = "/" if child else ""
|
||||
lines.append(f"{prefix}{branch}{name}{suffix}")
|
||||
if child:
|
||||
render(child, prefix + (" " if last else "│ "), lines)
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", newline="\n")
|
||||
except AttributeError:
|
||||
pass
|
||||
root_label = sys.argv[1] if len(sys.argv) > 1 else "."
|
||||
tree = build(sys.stdin.read().splitlines())
|
||||
lines = [f"{root_label}/"]
|
||||
render(tree, "", lines)
|
||||
sys.stdout.write("\n".join(lines) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
101
.gitea/workflows/pr-checks.yml
Normal file
101
.gitea/workflows/pr-checks.yml
Normal file
@@ -0,0 +1,101 @@
|
||||
# Gate every pull request into `main` on the same Rust checks the release runs,
|
||||
# so a formatting slip, a lint regression, or a failing test can't reach the
|
||||
# deployable branch.
|
||||
#
|
||||
# Why this exists: release.yml runs only AFTER merge (on push to `main`) and its
|
||||
# FIRST Rust step is `cargo fmt --check`. Before this workflow, an unformatted
|
||||
# commit merged cleanly and then killed the release job before it could build,
|
||||
# tag, or publish anything — the repo had no pull_request workflow at all. These
|
||||
# gates are deliberately a mirror of release.yml's, in the same order, so a green
|
||||
# PR means the release will get past its gates too.
|
||||
#
|
||||
# Enforcement (one-time, in the Gitea UI):
|
||||
# Repository Settings → Branches → Branch Protection (rule for `main`)
|
||||
# • Enable Status Check
|
||||
# • Status check patterns: PR Checks / *
|
||||
# Note: Gitea only lists a context in its dropdown after it has reported once,
|
||||
# so let this workflow run on one PR first. The `PR Checks / *` glob matches
|
||||
# without needing the dropdown.
|
||||
#
|
||||
# Scope note: this gates PRs into `main` only. Feature work that lands on an
|
||||
# integration branch first (e.g. `edge`) is still caught on the branch's PR into
|
||||
# `main`. To gate that earlier hop too, add the branch to the `branches:` list
|
||||
# below — nothing else needs to change.
|
||||
#
|
||||
# Runner: the same self-hosted `ubuntu-latest` runner release.yml uses. Rust is
|
||||
# not assumed to be preinstalled, so the toolchain step bootstraps it the same
|
||||
# way release.yml does (minus the MinGW cross-compile deps — PRs build for the
|
||||
# host only; the Windows cross-build stays a release-time concern).
|
||||
|
||||
name: PR Checks
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
|
||||
# A newer push to the same PR cancels the in-flight run.
|
||||
concurrency:
|
||||
group: pr-checks-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
WORKDIR: sidecar
|
||||
|
||||
jobs:
|
||||
rust-gates:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
# One job runs all three gates on purpose: installing the toolchain costs
|
||||
# far more than the checks themselves, so splitting fmt/clippy/test into
|
||||
# parallel jobs would pay that cost three times for no wall-clock win.
|
||||
- name: Install Rust toolchain (rustfmt + clippy)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
SUDO=""; [ "$(id -u)" -ne 0 ] && SUDO="sudo"
|
||||
$SUDO apt-get update
|
||||
$SUDO apt-get install -y --no-install-recommends \
|
||||
build-essential curl ca-certificates git
|
||||
|
||||
if ! command -v cargo >/dev/null 2>&1; then
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
|
||||
| sh -s -- -y --profile minimal --default-toolchain stable
|
||||
fi
|
||||
echo "${HOME}/.cargo/bin" >> "$GITHUB_PATH"
|
||||
export PATH="${HOME}/.cargo/bin:${PATH}"
|
||||
rustup component add rustfmt clippy
|
||||
cargo --version && cargo fmt --version && cargo clippy --version
|
||||
|
||||
# Keyed on Cargo.lock: dependency builds are reused until a dep actually
|
||||
# changes. A cache miss only makes the run slower, never wrong.
|
||||
- name: Cache cargo registry and build dir
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
sidecar/target
|
||||
key: ${{ runner.os }}-cargo-${{ hashFiles('sidecar/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-cargo-
|
||||
|
||||
# Cheapest gate first — parses only, no compile, so a formatting slip
|
||||
# fails in seconds instead of after a full build.
|
||||
- name: cargo fmt --check
|
||||
working-directory: sidecar
|
||||
run: cargo fmt --check
|
||||
|
||||
# --all-targets covers tests and examples, not just the binary.
|
||||
# -D warnings makes a lint a failure; the crate is clean at this bar today,
|
||||
# so anything new here is a regression introduced by the PR.
|
||||
- name: cargo clippy
|
||||
working-directory: sidecar
|
||||
run: cargo clippy --locked --all-targets -- -D warnings
|
||||
|
||||
# --locked matches release.yml: it also proves Cargo.lock is in sync with
|
||||
# Cargo.toml, rather than letting the build silently update it.
|
||||
- name: cargo test
|
||||
working-directory: sidecar
|
||||
run: cargo test --locked
|
||||
52
.gitea/workflows/sonarqube.yml
Normal file
52
.gitea/workflows/sonarqube.yml
Normal file
@@ -0,0 +1,52 @@
|
||||
# Run SonarQube static analysis against the code that just landed on `main` and
|
||||
# report the results to the self-hosted SonarQube server for review. This is
|
||||
# intentionally NON-BLOCKING: it triggers on push to main (i.e. AFTER merge),
|
||||
# not on pull_request, so it never gates a PR. It complements release.yml
|
||||
# (which builds + cuts releases) — this one only feeds the dashboard.
|
||||
#
|
||||
# Prerequisites (one-time, in the Gitea UI — Repo → Settings → Actions):
|
||||
# • Secret SONAR_TOKEN — a SonarQube "Analysis" token generated at
|
||||
# My Account → Security in SonarQube for the
|
||||
# Runic-Gateway-link project (or a global one).
|
||||
# • Variable SONAR_HOST_URL — the SonarQube base URL on your LAN, e.g.
|
||||
# http://192.168.0.56:9000
|
||||
# (kept as a variable, not committed, so the internal address stays out of git.)
|
||||
#
|
||||
# The runner (self-hosted `ubuntu-latest`, same as release.yml) must be able to
|
||||
# reach SONAR_HOST_URL on your network. Nothing here waits on the SonarQube
|
||||
# Quality Gate, so a failing gate does not fail this job — check the dashboard
|
||||
# when you want to.
|
||||
#
|
||||
# Scope: this analyses the Rust source directly (the Sonar scanner reads
|
||||
# sonar-project.properties). It does NOT build the crate or run Clippy — see the
|
||||
# "Optional enrichment" note in sonar-project.properties for wiring in a Clippy
|
||||
# report if your SonarQube edition supports Rust lint import.
|
||||
|
||||
name: SonarQube
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# Allow re-running the analysis on demand from the Actions tab.
|
||||
workflow_dispatch: {}
|
||||
|
||||
concurrency:
|
||||
group: sonarqube-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
analysis:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out (full history for accurate new-code + blame)
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
# SonarQube uses git history to attribute issues to authors and to
|
||||
# compute "new code". A shallow clone degrades both.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Run SonarQube scan
|
||||
uses: sonarsource/sonarqube-scan-action@v4
|
||||
env:
|
||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
||||
SONAR_HOST_URL: ${{ vars.SONAR_HOST_URL }}
|
||||
111
.gitea/workflows/sync-project-tree.yml
Normal file
111
.gitea/workflows/sync-project-tree.yml
Normal file
@@ -0,0 +1,111 @@
|
||||
name: sync-project-tree
|
||||
|
||||
# Keeps this repo's file-layout snapshot (docs/link/PROJECT_TREE.md in the
|
||||
# RunicGateway/docs repo) current. On every push to `main` it regenerates the
|
||||
# tree from tracked files and, if it changed, opens (or force-updates) a pull
|
||||
# request against the docs repo. It never writes to the docs repo's `main`
|
||||
# directly. Auth reuses the same REGISTRY_USER / REGISTRY_TOKEN secrets the
|
||||
# other workflows use (the token needs repo read/write on RunicGateway/docs).
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch: {}
|
||||
|
||||
concurrency:
|
||||
group: sync-project-tree
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
GITEA_HOST: gitea.whitlocktech.com
|
||||
DOCS_REPO: RunicGateway/docs
|
||||
SELF_REPO: RunicGateway/link
|
||||
DOCS_PATH: link/PROJECT_TREE.md
|
||||
TREE_TITLE: uo-link
|
||||
ROOT_LABEL: link
|
||||
PR_BRANCH: chore/sync-link-tree
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out this repo
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Ensure python3 is available
|
||||
run: |
|
||||
set -euo pipefail
|
||||
command -v python3 >/dev/null 2>&1 || { sudo apt-get update -qq && sudo apt-get install -y -qq python3; }
|
||||
|
||||
- name: Render PROJECT_TREE.md from tracked files
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p _sync
|
||||
{
|
||||
printf '# %s — Project Tree\n\n' "${TREE_TITLE}"
|
||||
printf '> **Auto-generated.** This file is maintained by the `sync-project-tree` CI workflow in\n'
|
||||
printf '> the [`%s`](https://%s/%s) repository, which\n' "${SELF_REPO}" "${GITEA_HOST}" "${SELF_REPO}"
|
||||
printf '> opens a pull request here whenever the tracked file layout on `main` changes. Do not edit\n'
|
||||
printf '> by hand — changes will be overwritten by the next sync.\n\n'
|
||||
printf 'A snapshot of the tracked files in the repository (build output, dependencies, and other\n'
|
||||
printf 'git-ignored paths are excluded).\n\n'
|
||||
printf '```text\n'
|
||||
git ls-files | python3 .gitea/scripts/gen_tree.py "${ROOT_LABEL}"
|
||||
printf '```\n'
|
||||
} > _sync/PROJECT_TREE.md
|
||||
echo "----- generated ${DOCS_PATH} -----"
|
||||
cat _sync/PROJECT_TREE.md
|
||||
|
||||
- name: Open or update the docs PR if the tree changed
|
||||
env:
|
||||
REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
|
||||
REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Secrets can carry a trailing CR/LF depending on how they were pasted;
|
||||
# strip line breaks before they land in a URL or Authorization header.
|
||||
CI_USER="$(printf '%s' "${REGISTRY_USER}" | tr -d '\r\n')"
|
||||
CI_TOKEN="$(printf '%s' "${REGISTRY_TOKEN}" | tr -d '\r\n')"
|
||||
API="https://${GITEA_HOST}/api/v1/repos/${DOCS_REPO}"
|
||||
REMOTE="https://${CI_USER}:${CI_TOKEN}@${GITEA_HOST}/${DOCS_REPO}.git"
|
||||
|
||||
git clone --depth 1 "${REMOTE}" docs_repo
|
||||
cd docs_repo
|
||||
git config user.name "runic-docs-bot"
|
||||
git config user.email "ci@whitlocktech.com"
|
||||
|
||||
mkdir -p "$(dirname "${DOCS_PATH}")"
|
||||
cp ../_sync/PROJECT_TREE.md "${DOCS_PATH}"
|
||||
git add "${DOCS_PATH}"
|
||||
if git diff --cached --quiet; then
|
||||
echo "PROJECT_TREE.md already up to date — nothing to sync."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
SHORT_SHA="$(echo "${GITHUB_SHA:-local}" | cut -c1-7)"
|
||||
git checkout -B "${PR_BRANCH}"
|
||||
git commit -m "docs(tree): sync ${DOCS_PATH} from ${SELF_REPO}@${SHORT_SHA} [skip ci]"
|
||||
git push --force "${REMOTE}" "HEAD:${PR_BRANCH}"
|
||||
|
||||
# Open a PR only if one isn't already open for this branch (a force-push
|
||||
# to an existing open PR's head updates it in place).
|
||||
OPEN="$(curl -sSf -H "Authorization: token ${CI_TOKEN}" \
|
||||
"${API}/pulls?state=open&limit=50" \
|
||||
| jq --arg b "${PR_BRANCH}" '[.[] | select(.head.ref == $b)] | length')"
|
||||
if [ "${OPEN}" = "0" ]; then
|
||||
curl -sSf -X POST "${API}/pulls" \
|
||||
-H "Authorization: token ${CI_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(jq -n \
|
||||
--arg head "${PR_BRANCH}" \
|
||||
--arg base "main" \
|
||||
--arg title "docs(tree): sync ${DOCS_PATH}" \
|
||||
--arg body "Automated project-tree sync from [\`${SELF_REPO}\`](https://${GITEA_HOST}/${SELF_REPO}), regenerated from tracked files on \`main\`. Merge once the layout looks right; the workflow will keep this branch current until then." \
|
||||
'{head: $head, base: $base, title: $title, body: $body}')" \
|
||||
>/dev/null
|
||||
echo "Opened a new docs PR for ${PR_BRANCH}."
|
||||
else
|
||||
echo "Existing open docs PR for ${PR_BRANCH} was updated via force-push."
|
||||
fi
|
||||
133
CODE_OF_CONDUCT.md
Normal file
133
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,133 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, caste, color, religion, or sexual
|
||||
identity and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the overall
|
||||
community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or advances of
|
||||
any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email address,
|
||||
without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official email address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
**whitlocktech@gmail.com**.
|
||||
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series of
|
||||
actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or permanent
|
||||
ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within the
|
||||
community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.1, available at
|
||||
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
||||
|
||||
Community Impact Guidelines were inspired by
|
||||
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
||||
[https://www.contributor-covenant.org/translations][translations].
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
||||
[Mozilla CoC]: https://github.com/mozilla/diversity
|
||||
[FAQ]: https://www.contributor-covenant.org/faq
|
||||
[translations]: https://www.contributor-covenant.org/translations
|
||||
89
CONTRIBUTING.md
Normal file
89
CONTRIBUTING.md
Normal file
@@ -0,0 +1,89 @@
|
||||
# Contributing to Runic Gateway — uo-link sidecar
|
||||
|
||||
Thanks for your interest in contributing! This repo is the **Rust sidecar** half
|
||||
of the game bridge: it terminates the loopback link from the ServUO shard and
|
||||
exposes the WebSocket + REST API the website consumes.
|
||||
|
||||
By participating you agree to abide by our
|
||||
[Code of Conduct](CODE_OF_CONDUCT.md).
|
||||
|
||||
## Ways to contribute
|
||||
|
||||
- **Report a bug** or **request a feature** through the
|
||||
[issue tracker](https://gitea.whitlocktech.com/RunicGateway/link/issues)
|
||||
(issue templates are provided).
|
||||
- **Improve the code or docs** by opening a pull request (see below).
|
||||
- **Never** report a security vulnerability in a public issue — see
|
||||
[SECURITY.md](SECURITY.md). The sidecar is the only network-facing part of the
|
||||
bridge, so its security matters.
|
||||
|
||||
## Development setup
|
||||
|
||||
**Prerequisites:** a recent stable Rust toolchain (install via
|
||||
[rustup](https://rustup.rs/)).
|
||||
|
||||
The sidecar is a standard cargo crate under `sidecar/`:
|
||||
|
||||
```bash
|
||||
cd sidecar
|
||||
cp sidecar.toml.example sidecar.toml # then edit
|
||||
cargo build --release # binary at target/release/uo-link-sidecar
|
||||
cargo run --release
|
||||
```
|
||||
|
||||
See [`sidecar/README.md`](sidecar/README.md) for configuration and the wire
|
||||
protocol. The loopback JSON protocol shared with the ServUO plugin
|
||||
([RunicGateway/servuo-plugins](https://gitea.whitlocktech.com/RunicGateway/servuo-plugins))
|
||||
is a **compatibility contract** — the canonical spec lives in the
|
||||
[docs repo](https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/link).
|
||||
If you change an event or command, keep both sides and the spec in sync.
|
||||
|
||||
### Checks
|
||||
|
||||
Please make sure the crate builds cleanly and is formatted and lint-clean before
|
||||
opening a PR:
|
||||
|
||||
```bash
|
||||
cargo fmt --all
|
||||
cargo clippy --all-targets -- -D warnings
|
||||
cargo test
|
||||
cargo build --release
|
||||
```
|
||||
|
||||
## Branch & PR workflow
|
||||
|
||||
1. Branch from `main` with a descriptive name
|
||||
(`feature/…`, `fix/…`, `docs/…`, `chore/…`).
|
||||
2. Keep changes focused; small PRs are easier to review.
|
||||
3. Push and open a pull request against `main`. Fill out the PR template,
|
||||
including the **AI-assisted contributions** disclosure.
|
||||
4. A maintainer will review; address feedback with follow-up commits.
|
||||
|
||||
### Commit messages
|
||||
|
||||
We use [Conventional Commits](https://www.conventionalcommits.org/) —
|
||||
`type(scope): summary`. Note the release workflow
|
||||
(`.gitea/workflows/release.yml`) derives versions from conventional commits on
|
||||
`main`, so accurate `feat:` / `fix:` prefixes matter here.
|
||||
|
||||
## AI-assisted contributions (disclosure required)
|
||||
|
||||
This project is developed openly with AI assistance, and we ask the same
|
||||
transparency of everyone. **If you used an AI tool** (Claude, Copilot, ChatGPT,
|
||||
Cursor, etc.) to help produce a contribution, you must disclose it:
|
||||
|
||||
- Tick the AI-usage box in the pull-request template and name the tool(s).
|
||||
- Mark AI-authored commits with a trailer, e.g.
|
||||
`Co-Authored-By: Claude <noreply@anthropic.com>` or `Assisted-By: <tool>`.
|
||||
- You remain responsible for every line you submit: review it, understand it,
|
||||
and make sure it is correct and that you have the right to contribute it.
|
||||
|
||||
Disclosed AI assistance is welcome. Undisclosed AI-generated contributions are
|
||||
not, and may be closed.
|
||||
|
||||
## License
|
||||
|
||||
Runic Gateway is licensed under the **GNU General Public License v3.0 or later**
|
||||
(see [LICENSE.md](LICENSE.md)). By submitting a contribution you agree that it is
|
||||
licensed under the same terms (inbound = outbound) and that you have the right to
|
||||
contribute it.
|
||||
31
CONTRIBUTORS.md
Normal file
31
CONTRIBUTORS.md
Normal file
@@ -0,0 +1,31 @@
|
||||
# Contributors
|
||||
|
||||
Runic Gateway is built and maintained by the people and tools listed here.
|
||||
Thank you to everyone who has contributed.
|
||||
|
||||
## Maintainers
|
||||
|
||||
- **whitlocktech** <whitlocktech@gmail.com> — project lead and maintainer
|
||||
|
||||
## Contributors
|
||||
|
||||
<!--
|
||||
Add yourself here when your contribution is merged — alphabetical by name or
|
||||
handle. One line each:
|
||||
|
||||
- **Name or handle** (optional link) — what you contributed
|
||||
-->
|
||||
|
||||
- _Your name could be here — see [CONTRIBUTING.md](CONTRIBUTING.md)._
|
||||
|
||||
## AI-assisted development
|
||||
|
||||
Parts of Runic Gateway were developed with the assistance of AI coding tools,
|
||||
including **Claude** (Anthropic) via Claude Code. AI-assisted commits are
|
||||
attributed in their commit trailers (e.g. `Co-Authored-By: Claude ...`).
|
||||
|
||||
In keeping with this project's transparency policy, **all contributors must
|
||||
disclose their use of AI tools** on any contribution — see the
|
||||
"AI-assisted contributions" section of [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
Disclosed AI assistance is welcome; undisclosed AI-generated contributions are
|
||||
not.
|
||||
674
LICENSE.md
Normal file
674
LICENSE.md
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
42
README.md
42
README.md
@@ -25,6 +25,7 @@ network-facing component, which is what keeps the game unreachable from the inte
|
||||
| Path | What |
|
||||
|------|------|
|
||||
| `sidecar/` | The Rust sidecar crate — terminates the loopback link to the shard, exposes WS + REST to the website. See [`sidecar/README.md`](sidecar/README.md). |
|
||||
| `.gitea/workflows/pr-checks.yml` | Gates every PR into `main` on `cargo fmt --check`, `cargo clippy -D warnings`, and `cargo test`. |
|
||||
| `.gitea/workflows/release.yml` | Builds + releases the sidecar binary (Linux + Windows) on every merge to `main`. |
|
||||
|
||||
## Build & run
|
||||
@@ -38,10 +39,30 @@ cp sidecar.toml.example sidecar.toml # then edit
|
||||
cargo run --release
|
||||
```
|
||||
|
||||
Deploying it rather than developing on it: `--config <PATH>` names the config file (as does
|
||||
`$UOLINK_CONFIG`), and `--print-config` prints the resolved settings — **including the auth token
|
||||
the website needs** — as JSON, provisioning the config file on first run. That is the supported way
|
||||
to read the token back; it is not meant to be scraped from the log.
|
||||
|
||||
```bash
|
||||
uo-link-sidecar --print-config --config /etc/runicgateway/sidecar.toml
|
||||
```
|
||||
|
||||
`.gitea/workflows/release.yml` cross-compiles Linux + Windows binaries and cuts a Gitea release on
|
||||
every merge to `main` (conventional-commit versioning). See [`sidecar/README.md`](sidecar/README.md)
|
||||
for configuration and the wire protocol.
|
||||
|
||||
Before that, `.gitea/workflows/pr-checks.yml` runs the same gates on every pull request into `main` —
|
||||
`cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, then `cargo test --locked`. Run them
|
||||
locally before pushing and the PR will be green:
|
||||
|
||||
```bash
|
||||
cd sidecar
|
||||
cargo fmt # or --check to just report
|
||||
cargo clippy --locked --all-targets -- -D warnings
|
||||
cargo test --locked
|
||||
```
|
||||
|
||||
## Deployment & compatibility
|
||||
|
||||
The plugin ([RunicGateway/servuo-plugins](https://gitea.whitlocktech.com/RunicGateway/servuo-plugins))
|
||||
@@ -58,3 +79,24 @@ repos. Canonical spec:
|
||||
[INTEGRATION.md](https://gitea.whitlocktech.com/RunicGateway/docs/src/branch/main/link/INTEGRATION.md).
|
||||
Because a wedged or absent sidecar cannot stall the shard, either side can be deployed or restarted
|
||||
independently.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
Runic Gateway is free software, licensed under the **GNU General Public License
|
||||
v3.0 or later** — see [LICENSE.md](LICENSE.md).
|
||||
|
||||
Copyright (C) 2026 Runic Gateway
|
||||
|
||||
This program is free software: you can redistribute it and/or modify it under
|
||||
the terms of the GNU General Public License as published by the Free Software
|
||||
Foundation, either version 3 of the License, or (at your option) any later
|
||||
version. It is distributed WITHOUT ANY WARRANTY; without even the implied
|
||||
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
General Public License for more details.
|
||||
|
||||
Contributions are welcome — please read [CONTRIBUTING.md](CONTRIBUTING.md) (note
|
||||
the **AI-usage disclosure** requirement) and our
|
||||
[Code of Conduct](CODE_OF_CONDUCT.md). Report vulnerabilities privately per
|
||||
[SECURITY.md](SECURITY.md).
|
||||
|
||||
50
SECURITY.md
Normal file
50
SECURITY.md
Normal file
@@ -0,0 +1,50 @@
|
||||
# Security Policy
|
||||
|
||||
Thank you for helping keep Runic Gateway and its users safe.
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
**Please do not report security vulnerabilities through public issues, pull
|
||||
requests, or the wiki.** A public report tips off attackers before a fix is
|
||||
available.
|
||||
|
||||
Instead, report privately by email to:
|
||||
|
||||
**whitlocktech@gmail.com**
|
||||
|
||||
Please include as much of the following as you can:
|
||||
|
||||
- The repository and component affected.
|
||||
- The type of issue (e.g. authentication bypass, injection, secret exposure,
|
||||
remote code execution, denial of service).
|
||||
- Step-by-step instructions to reproduce, and a proof-of-concept if you have one.
|
||||
- The impact — what an attacker could do with it.
|
||||
- Any suggested remediation.
|
||||
|
||||
You will receive an acknowledgement of your report, typically within a few days.
|
||||
We will keep you informed as we investigate and work toward a fix, and we are
|
||||
happy to credit you in the release notes once the issue is resolved (let us know
|
||||
if you would prefer to remain anonymous).
|
||||
|
||||
## Scope
|
||||
|
||||
Runic Gateway is a self-hosted platform made up of several components:
|
||||
|
||||
| Component | Repo | Network exposure |
|
||||
|---|---|---|
|
||||
| Website (site + admin + API) | `RunicGateway/website` | Internet-facing (behind a reverse proxy) |
|
||||
| uo-link sidecar | `RunicGateway/link` | The only network-facing part of the game bridge |
|
||||
| ServUO plugin | `RunicGateway/servuo-plugins` | Loopback only — dials the sidecar on `127.0.0.1` |
|
||||
| Documentation | `RunicGateway/docs` | Content only |
|
||||
|
||||
Because instances are self-hosted, the security of any given deployment also
|
||||
depends on how it is configured and operated — strong secrets (`JWT_SECRET`,
|
||||
`SECRET_ENC_KEY`, database and admin passwords), a correctly configured reverse
|
||||
proxy and `TRUST_PROXY`, and keeping the shard itself unreachable from the
|
||||
internet (only the sidecar should be exposed). See each repo's README for the
|
||||
security model.
|
||||
|
||||
## Supported versions
|
||||
|
||||
This project is developed continuously and does not maintain long-term release
|
||||
branches. Security fixes land on `main`; please run a recent build.
|
||||
@@ -18,9 +18,61 @@ RUST_LOG=debug cargo run # see every event, incl. pong heartbeats
|
||||
|
||||
On first run it writes `sidecar.toml` with a generated auth token and logs the path. Binds the shard listener (`127.0.0.1:7788`) and the web server (`127.0.0.1:8080`) from that file, then waits for the shard to connect.
|
||||
|
||||
## Command line
|
||||
|
||||
Four flags. Everything else is configuration, and configuration lives in the file.
|
||||
|
||||
```
|
||||
uo-link-sidecar [--print-config] [--config <PATH>] [-V|--version] [-h|--help]
|
||||
```
|
||||
|
||||
| Flag | What |
|
||||
|------|------|
|
||||
| `--print-config` | Resolve the configuration, print it as JSON on stdout, exit. |
|
||||
| `--config <PATH>` | Path to `sidecar.toml`. Outranks `$UOLINK_CONFIG`; default `./sidecar.toml`. |
|
||||
| `-V`, `--version` | `uo-link-sidecar <ver> (protocol <n>)`. |
|
||||
| `-h`, `--help` | Usage. |
|
||||
|
||||
An unrecognized argument is an error (exit `2`), not something to ignore — a typo'd flag would otherwise start a sidecar that is not the one you asked for.
|
||||
|
||||
### `--print-config`
|
||||
|
||||
The non-interactive way to read the sidecar's own settings back, so an installer or a diagnostic never has to scrape the startup log or parse TOML:
|
||||
|
||||
```console
|
||||
$ uo-link-sidecar --print-config --config /etc/runicgateway/sidecar.toml
|
||||
{
|
||||
"component": "uo-link-sidecar",
|
||||
"config_created": false,
|
||||
"config_path": "/etc/runicgateway/sidecar.toml",
|
||||
"protocol": 3,
|
||||
"shard": { "bind": "127.0.0.1:7788" },
|
||||
"store": { "path": "/var/lib/runicgateway/uo-link.db" },
|
||||
"token_generated": false,
|
||||
"version": "0.1.0",
|
||||
"web": {
|
||||
"auth_required": true,
|
||||
"auth_token": "c0f04ace66a937edff407d9dc25d5d8a967b0300e3306f11",
|
||||
"bind": "127.0.0.1:8080",
|
||||
"ws_path": "/ws"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **It contains the auth token in clear text.** That is the point — those values go straight into Admin → Shard — but it means the output is a secret: don't pipe it into a log or a CI artifact.
|
||||
- **It performs first-run setup**, exactly as a normal start would: a missing config file is written and a blank token is generated and saved. So `--print-config` on a fresh host provisions the sidecar *and* tells you its token in one step. `config_created` and `token_generated` report whether this run did either, which is how a re-run distinguishes "read an existing install" from "provisioned a new one".
|
||||
- Paths are the **resolved absolute** ones, not what the file literally says.
|
||||
- Nothing else is written to stdout — the log subscriber is not started in this mode, so the JSON is the entire output.
|
||||
|
||||
## Configuration & auth
|
||||
|
||||
All runtime settings live in `sidecar.toml` (path overridable with `$UOLINK_CONFIG`) — **nothing is compiled into the binary**. See `sidecar.toml.example`. Environment variables override the file: `UOLINK_SHARD_BIND`, `UOLINK_WEB_BIND`, `UOLINK_WEB_TOKEN`, `UOLINK_DB_PATH`.
|
||||
All runtime settings live in `sidecar.toml` (path overridable with `--config` or `$UOLINK_CONFIG`) — **nothing is compiled into the binary**. See `sidecar.toml.example`. Environment variables override the file: `UOLINK_SHARD_BIND`, `UOLINK_WEB_BIND`, `UOLINK_WEB_TOKEN`, `UOLINK_DB_PATH`.
|
||||
|
||||
### Where the data goes
|
||||
|
||||
A **relative** `[store].path` resolves against the directory holding `sidecar.toml`, not the process's working directory. Under `cargo run` those are the same thing, so nothing changes for development; for an installed service they are emphatically not. A unit that pins `UOLINK_CONFIG=/etc/runicgateway/sidecar.toml` and leaves the default `uo-link.db` gets `/etc/runicgateway/uo-link.db` — beside its config, deterministically — instead of a database wherever the service manager happened to set CWD (`%SystemRoot%\System32`, or a silently redirected VirtualStore copy under `C:\Program Files\`).
|
||||
|
||||
Absolute paths are used as written, and the parent directory is created if it does not exist, so a service can name `/var/lib/runicgateway/uo-link.db` on a host where nothing has created that directory yet. Paths are handed to SQLite as filesystem paths rather than being formatted into a `sqlite://` URL, so a `%`, `#`, `?` or space in the path means what it looks like.
|
||||
|
||||
The website authenticates to the sidecar with a shared token, presented as:
|
||||
|
||||
@@ -41,10 +93,10 @@ So you can never accidentally run without auth. Rotate by editing the token and
|
||||
|
||||
## Protocol version
|
||||
|
||||
The wire protocol has a version (`PROTOCOL_VERSION`, currently **1**), so the website and sidecar detect a mismatch immediately instead of failing in strange ways when a message shape changes.
|
||||
The wire protocol has a version (`PROTOCOL_VERSION`, currently **3**), so the website and sidecar detect a mismatch immediately instead of failing in strange ways when a message shape changes.
|
||||
|
||||
- Every response carries an `X-UOLink-Version: 1` header.
|
||||
- `/health` and the WebSocket `ws.hello` include `"protocol": 1`.
|
||||
- Every response carries an `X-UOLink-Version: 3` header.
|
||||
- `/health` and the WebSocket `ws.hello` include `"protocol": 3`.
|
||||
- If a request sends `X-UOLink-Version` and it disagrees with the sidecar, the request is rejected **409 Conflict** with `{sidecar_protocol, client_protocol}` so the mismatch is obvious.
|
||||
|
||||
Bump `PROTOCOL_VERSION` in `main.rs` whenever an event or endpoint's shape changes.
|
||||
@@ -56,7 +108,7 @@ Bump `PROTOCOL_VERSION` in `main.rs` whenever an event or endpoint's shape chang
|
||||
```json
|
||||
{
|
||||
"status": "ok", // "ok" when plugin connected and DB reachable, else "degraded"
|
||||
"protocol": 1,
|
||||
"protocol": 3,
|
||||
"plugin_connected": true, // is the shard link up?
|
||||
"database": "ok",
|
||||
"uptime": "3d 12h",
|
||||
@@ -101,7 +153,9 @@ A shard `*.error` reply maps to HTTP 404 (unknown/not-found) or 400 (bad request
|
||||
- **`shard.rs`** — `serve()` binds the listener and accepts shard connections in a loop. Each connection splits into read/write halves: the read half parses newline-JSON into `ShardEvent { kind, value }` and forwards them; the write half drains an mpsc of command lines. `ShardHandle::send` posts a command to whichever shard is currently connected, and **drops with a warning if none is** — a website query during a shard outage should fail fast and retry, not queue behind a reconnect. Live *events* that must survive an outage are buffered by the shard, not here.
|
||||
- **`web.rs`** — the website-facing HTTP surface (axum). `AppState` holds the `broadcast::Sender<String>`; each `/ws` client subscribes and forwards every event as a text frame. A client that lags past the broadcast buffer is warned and kept live (it just misses events) rather than stalling the others. This side *may* be exposed beyond loopback — it is the gatekeeper, so add auth when you do.
|
||||
- **`rpc.rs`** — request/reply correlation over the one shard socket. A REST call registers a pending entry under a correlation id, sends the command, and awaits the reply (10 s timeout). The event loop routes any incoming line whose id is pending back to the waiter; everything else flows on as a live event. Recognizes three correlation fields, matching what the plugin echoes: `reqId` (queries), `code` (link), `id` (town-crier).
|
||||
- **`store.rs`** — SQLite (`sqlx`). Three tables: `events` (the full live stream, append-only), `links` (account ↔ website user, mirrored from `link.ok`), `profiles` (last-known character sheet, cached from `char.profile`). History and economy read here instead of the shard; `pong` is dropped as ephemeral chatter. DB file defaults to `uo-link.db` (`DB_PATH` in `main.rs`), gitignored.
|
||||
- **`store.rs`** — SQLite (`sqlx`). Three tables: `events` (the full live stream, append-only), `links` (account ↔ website user, mirrored from `link.ok`), `profiles` (last-known character sheet, cached from `char.profile`). History and economy read here instead of the shard; `pong` is dropped as ephemeral chatter. The DB file is `[store].path` (default `uo-link.db` beside the config), gitignored.
|
||||
- **`config.rs`** — resolves the config file, applies the environment overrides, guarantees an auth token, anchors relative paths, and renders the `--print-config` document.
|
||||
- **`cli.rs`** — the four flags above. Hand-rolled; no argument-parsing dependency.
|
||||
- **`main.rs`** — wires it together: the shard event loop first tries to route each line as an RPC reply; if it isn't one, the line is a live event — logged, persisted, and broadcast to WS.
|
||||
|
||||
## Wire protocol
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
# uo-link sidecar configuration — example.
|
||||
#
|
||||
# The sidecar reads `sidecar.toml` (override the path with $UOLINK_CONFIG). If that file
|
||||
# is absent on first run, one is generated automatically with a random auth_token, so you
|
||||
# normally do not create this by hand — just start the sidecar and edit the file it writes.
|
||||
# Nothing here is compiled into the binary.
|
||||
# The sidecar reads `sidecar.toml` (override the path with --config or $UOLINK_CONFIG).
|
||||
# If that file is absent on first run, one is generated automatically with a random
|
||||
# auth_token, so you normally do not create this by hand — just start the sidecar and edit
|
||||
# the file it writes. Nothing here is compiled into the binary.
|
||||
#
|
||||
# Environment variables override the file:
|
||||
# UOLINK_SHARD_BIND, UOLINK_WEB_BIND, UOLINK_WEB_TOKEN, UOLINK_DB_PATH
|
||||
#
|
||||
# Read the resolved settings back without starting the sidecar (JSON, includes the token):
|
||||
# uo-link-sidecar --print-config --config /etc/runicgateway/sidecar.toml
|
||||
|
||||
[shard]
|
||||
# Loopback address the shard dials out to. Keep this on localhost — the game must not
|
||||
@@ -27,4 +30,9 @@ bind = "127.0.0.1:8080"
|
||||
auth_token = "replace-with-a-long-random-secret"
|
||||
|
||||
[store]
|
||||
# A RELATIVE path resolves against the directory holding this file, not the working
|
||||
# directory of the process — so a service pinned to /etc/runicgateway/sidecar.toml keeps
|
||||
# its database beside its config no matter what CWD the service manager picked. Give an
|
||||
# absolute path (or set UOLINK_DB_PATH) to put the data somewhere else, e.g.
|
||||
# /var/lib/runicgateway/uo-link.db or C:\ProgramData\RunicGateway\uo-link.db.
|
||||
path = "uo-link.db"
|
||||
|
||||
172
sidecar/src/cli.rs
Normal file
172
sidecar/src/cli.rs
Normal file
@@ -0,0 +1,172 @@
|
||||
//! Command-line surface.
|
||||
//!
|
||||
//! The sidecar is configured by file and environment (see [`crate::config`]); this is deliberately
|
||||
//! not a second configuration mechanism. It exists so the binary can be *driven by an installer*
|
||||
//! rather than only by a human reading its logs:
|
||||
//!
|
||||
//! - `--print-config` resolves the configuration exactly as a normal start would — including
|
||||
//! generating the auth token on first run — and prints it as JSON on stdout. That is the
|
||||
//! supported way to obtain the token for the website's Admin → Shard form. Before this existed,
|
||||
//! the only way to read it back was to scrape the startup log or parse `sidecar.toml`.
|
||||
//! - `--config <PATH>` names the config file without having to export `UOLINK_CONFIG`, so a
|
||||
//! diagnostic run can point at an installed config from any working directory.
|
||||
//!
|
||||
//! Hand-rolled rather than pulled from a crate: four flags, no subcommands, no completions. A
|
||||
//! dependency here would be larger than the code it replaced.
|
||||
|
||||
/// What this invocation should do. Everything except `Run` prints and exits.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Mode {
|
||||
/// Normal operation: bind the shard listener and the web server.
|
||||
Run,
|
||||
/// Resolve config, print it as JSON, exit.
|
||||
PrintConfig,
|
||||
Help,
|
||||
Version,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Cli {
|
||||
pub mode: Mode,
|
||||
/// `--config <PATH>`, which outranks `$UOLINK_CONFIG`.
|
||||
pub config: Option<String>,
|
||||
}
|
||||
|
||||
pub const USAGE: &str = "\
|
||||
uo-link sidecar — bridges a ServUO shard to the Runic Gateway website.
|
||||
|
||||
Usage: uo-link-sidecar [OPTIONS]
|
||||
|
||||
Options:
|
||||
--print-config Resolve the configuration, print it as JSON, and exit.
|
||||
Runs first-run setup like a normal start does: if the
|
||||
config file is missing it is written, and a blank auth
|
||||
token is generated and saved. The JSON CONTAINS THE
|
||||
AUTH TOKEN in clear text.
|
||||
--config <PATH> Path to sidecar.toml. Overrides $UOLINK_CONFIG;
|
||||
defaults to ./sidecar.toml.
|
||||
-V, --version Print the sidecar and protocol versions and exit.
|
||||
-h, --help Print this help and exit.
|
||||
|
||||
Configuration lives in sidecar.toml; environment variables override the file:
|
||||
UOLINK_CONFIG, UOLINK_SHARD_BIND, UOLINK_WEB_BIND, UOLINK_WEB_TOKEN,
|
||||
UOLINK_DB_PATH
|
||||
";
|
||||
|
||||
/// Parses arguments **without** the program name.
|
||||
///
|
||||
/// Returns the message to print on stderr when the arguments are unusable; the caller exits `2`.
|
||||
pub fn parse<I: IntoIterator<Item = String>>(args: I) -> Result<Cli, String> {
|
||||
let mut mode = Mode::Run;
|
||||
let mut config = None;
|
||||
let mut it = args.into_iter();
|
||||
|
||||
while let Some(arg) = it.next() {
|
||||
match arg.as_str() {
|
||||
"--print-config" => mode = Mode::PrintConfig,
|
||||
"-h" | "--help" => {
|
||||
return Ok(Cli {
|
||||
mode: Mode::Help,
|
||||
config,
|
||||
})
|
||||
}
|
||||
"-V" | "--version" => {
|
||||
return Ok(Cli {
|
||||
mode: Mode::Version,
|
||||
config,
|
||||
})
|
||||
}
|
||||
"--config" => {
|
||||
// `--config` with nothing after it would otherwise silently fall through and start
|
||||
// the sidecar against the default config — the opposite of what was asked for.
|
||||
let path = it
|
||||
.next()
|
||||
.ok_or_else(|| "--config requires a path".to_string())?;
|
||||
config = Some(path);
|
||||
}
|
||||
_ => match arg.strip_prefix("--config=") {
|
||||
Some("") => return Err("--config requires a path".into()),
|
||||
Some(path) => config = Some(path.to_string()),
|
||||
None => return Err(format!("unrecognized argument: {arg}")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Cli { mode, config })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn parse_str(args: &[&str]) -> Result<Cli, String> {
|
||||
parse(args.iter().map(|s| s.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_arguments_runs_the_sidecar() {
|
||||
let cli = parse_str(&[]).unwrap();
|
||||
assert_eq!(cli.mode, Mode::Run);
|
||||
assert_eq!(cli.config, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn print_config_is_recognized() {
|
||||
assert_eq!(
|
||||
parse_str(&["--print-config"]).unwrap().mode,
|
||||
Mode::PrintConfig
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_accepts_both_spellings() {
|
||||
let spaced = parse_str(&["--config", "/etc/runicgateway/sidecar.toml"]).unwrap();
|
||||
let equals = parse_str(&["--config=/etc/runicgateway/sidecar.toml"]).unwrap();
|
||||
assert_eq!(
|
||||
spaced.config.as_deref(),
|
||||
Some("/etc/runicgateway/sidecar.toml")
|
||||
);
|
||||
assert_eq!(spaced, equals);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_combines_with_print_config() {
|
||||
let cli = parse_str(&["--config", "c.toml", "--print-config"]).unwrap();
|
||||
assert_eq!(cli.mode, Mode::PrintConfig);
|
||||
assert_eq!(cli.config.as_deref(), Some("c.toml"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_is_never_swallowed_as_a_flag() {
|
||||
// `--config --print-config` takes the next token as the path, wrong as that path is. The
|
||||
// alternative — treating it as a missing value — guesses at intent.
|
||||
let cli = parse_str(&["--config", "--print-config"]).unwrap();
|
||||
assert_eq!(cli.mode, Mode::Run);
|
||||
assert_eq!(cli.config.as_deref(), Some("--print-config"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_without_a_value_is_an_error() {
|
||||
assert!(parse_str(&["--config"]).is_err());
|
||||
assert!(parse_str(&["--config="]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_arguments_are_rejected() {
|
||||
// Silently ignoring a typo'd flag would start a sidecar that is not what was asked for.
|
||||
let err = parse_str(&["--pirnt-config"]).unwrap_err();
|
||||
assert!(err.contains("--pirnt-config"), "{err}");
|
||||
assert!(parse_str(&["/etc/runicgateway/sidecar.toml"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn help_and_version_win_immediately() {
|
||||
assert_eq!(parse_str(&["--help", "--bogus"]).unwrap().mode, Mode::Help);
|
||||
assert_eq!(parse_str(&["-h"]).unwrap().mode, Mode::Help);
|
||||
assert_eq!(
|
||||
parse_str(&["--version", "--bogus"]).unwrap().mode,
|
||||
Mode::Version
|
||||
);
|
||||
assert_eq!(parse_str(&["-V"]).unwrap().mode, Mode::Version);
|
||||
}
|
||||
}
|
||||
@@ -4,15 +4,26 @@
|
||||
//! first run, if the file is absent, a default one is written with a freshly generated auth token,
|
||||
//! so the sidecar is secured out of the box and the operator just copies the token to the website.
|
||||
//!
|
||||
//! File path: `$UOLINK_CONFIG`, else `sidecar.toml` in the working directory.
|
||||
//! File path: `--config <PATH>`, else `$UOLINK_CONFIG`, else `sidecar.toml` in the working
|
||||
//! directory.
|
||||
//!
|
||||
//! **Paths are anchored to the config file, not the working directory.** A relative
|
||||
//! `[store].path` resolves against the directory holding `sidecar.toml`. A service started with
|
||||
//! `UOLINK_CONFIG=/etc/runicgateway/sidecar.toml` therefore keeps its database beside its config
|
||||
//! instead of wherever the service manager happened to set the working directory — which on
|
||||
//! Windows can be `%SystemRoot%\System32` or, under `C:\Program Files\`, a silently redirected
|
||||
//! VirtualStore copy. The values reported by `--print-config` are the resolved absolute ones.
|
||||
|
||||
use std::env;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use tracing::info;
|
||||
|
||||
use crate::PROTOCOL_VERSION;
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
pub struct Config {
|
||||
#[serde(default)]
|
||||
@@ -33,8 +44,8 @@ pub struct ShardCfg {
|
||||
pub struct WebCfg {
|
||||
#[serde(default = "default_web_bind")]
|
||||
pub bind: String,
|
||||
/// Shared secret the website must present. Empty means the web surface is unauthenticated —
|
||||
/// only acceptable when `bind` is loopback; refused otherwise (see `Config::validate`).
|
||||
/// Shared secret the website must present. Never empty in practice — `Config::load` generates
|
||||
/// and persists one when it finds none, so the web surface is authenticated from first boot.
|
||||
#[serde(default)]
|
||||
pub auth_token: String,
|
||||
}
|
||||
@@ -45,6 +56,20 @@ pub struct StoreCfg {
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// A loaded configuration plus what loading it *did* — an installer re-running the binary needs to
|
||||
/// distinguish "read an existing install" from "provisioned a new one", and it cannot tell from the
|
||||
/// values alone.
|
||||
#[derive(Debug)]
|
||||
pub struct Loaded {
|
||||
pub cfg: Config,
|
||||
/// Absolute path of the config file that was read or written.
|
||||
pub path: PathBuf,
|
||||
/// The config file did not exist and was created by this run.
|
||||
pub config_created: bool,
|
||||
/// No usable token was configured, so one was generated and saved.
|
||||
pub token_generated: bool,
|
||||
}
|
||||
|
||||
fn default_shard_bind() -> String {
|
||||
"127.0.0.1:7788".into()
|
||||
}
|
||||
@@ -79,9 +104,20 @@ impl Default for StoreCfg {
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn load() -> anyhow::Result<Self> {
|
||||
let path = env::var("UOLINK_CONFIG").unwrap_or_else(|_| "sidecar.toml".into());
|
||||
let existed = Path::new(&path).exists();
|
||||
/// Which config file this invocation will use: `--config`, else `$UOLINK_CONFIG`, else
|
||||
/// `sidecar.toml` beside the working directory. Always returned absolute, so every later
|
||||
/// message names a path the operator can act on.
|
||||
pub fn resolve_path(cli_override: Option<&str>) -> PathBuf {
|
||||
let raw = cli_override
|
||||
.map(str::to_string)
|
||||
.or_else(|| env::var("UOLINK_CONFIG").ok())
|
||||
.unwrap_or_else(|| "sidecar.toml".into());
|
||||
absolutize(PathBuf::from(raw))
|
||||
}
|
||||
|
||||
pub fn load(cli_override: Option<&str>) -> anyhow::Result<Loaded> {
|
||||
let path = Self::resolve_path(cli_override);
|
||||
let existed = path.exists();
|
||||
|
||||
let mut cfg: Config = if existed {
|
||||
let text = fs::read_to_string(&path)?;
|
||||
@@ -95,12 +131,16 @@ impl Config {
|
||||
// Authentication is always on. A blank token is never allowed — if none is set (fresh
|
||||
// install, or someone cleared it), generate one, save it, and continue. This keeps setup
|
||||
// effortless while making it impossible to accidentally run with auth off.
|
||||
if cfg.web.auth_token.trim().is_empty() {
|
||||
let token_generated = cfg.web.auth_token.trim().is_empty();
|
||||
if token_generated {
|
||||
let token = generate_token();
|
||||
|
||||
if existed {
|
||||
persist_token(&path, &token)?;
|
||||
} else {
|
||||
// The parent may not exist yet when an installer points at a fresh
|
||||
// /etc/runicgateway; failing here would mean "run me again after mkdir".
|
||||
create_parent_dir(&path)?;
|
||||
fs::write(&path, default_file(&token))?;
|
||||
}
|
||||
|
||||
@@ -108,10 +148,17 @@ impl Config {
|
||||
|
||||
info!("No auth token configured.");
|
||||
info!("Generated new token: {}", token);
|
||||
info!("Saved to {}. Authentication is on.", path);
|
||||
info!("Saved to {}. Authentication is on.", path.display());
|
||||
}
|
||||
|
||||
Ok(cfg)
|
||||
cfg.anchor_store_path(&path);
|
||||
|
||||
Ok(Loaded {
|
||||
cfg,
|
||||
path,
|
||||
config_created: !existed,
|
||||
token_generated,
|
||||
})
|
||||
}
|
||||
|
||||
/// Environment overrides, so a deployment can set secrets without editing the file.
|
||||
@@ -130,15 +177,102 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves `[store].path` against the config file's directory (see the module docs). Absolute
|
||||
/// paths and SQLite's non-filesystem spellings are left exactly as written.
|
||||
fn anchor_store_path(&mut self, config_path: &Path) {
|
||||
if is_sqlite_special(&self.store.path) {
|
||||
return;
|
||||
}
|
||||
let raw = PathBuf::from(&self.store.path);
|
||||
let anchored = if raw.is_absolute() {
|
||||
raw
|
||||
} else {
|
||||
config_dir(config_path).join(raw)
|
||||
};
|
||||
self.store.path = absolutize(anchored).to_string_lossy().into_owned();
|
||||
}
|
||||
|
||||
pub fn auth_required(&self) -> bool {
|
||||
// Always true now — load() guarantees a non-empty token.
|
||||
!self.web.auth_token.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// The `--print-config` document: everything an installer needs to register this sidecar with a
|
||||
/// website, in one non-interactive read.
|
||||
///
|
||||
/// **This includes the auth token in clear text**, which is the point — §2.4 of the installer plan
|
||||
/// calls the manual token hunt the largest "I installed it and nothing happened" failure mode. The
|
||||
/// caller prints it to stdout and starts no log subscriber, so the document is the whole output.
|
||||
pub fn describe(loaded: &Loaded) -> serde_json::Value {
|
||||
json!({
|
||||
"component": "uo-link-sidecar",
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"protocol": PROTOCOL_VERSION,
|
||||
"config_path": loaded.path.to_string_lossy(),
|
||||
"config_created": loaded.config_created,
|
||||
"token_generated": loaded.token_generated,
|
||||
"shard": { "bind": loaded.cfg.shard.bind },
|
||||
"web": {
|
||||
"bind": loaded.cfg.web.bind,
|
||||
"ws_path": crate::web::WS_PATH,
|
||||
"auth_required": loaded.cfg.auth_required(),
|
||||
"auth_token": loaded.cfg.web.auth_token,
|
||||
},
|
||||
"store": { "path": loaded.cfg.store.path },
|
||||
})
|
||||
}
|
||||
|
||||
/// Directory holding the config file. A bare `sidecar.toml` has no parent component, which would
|
||||
/// join into an empty base — treat it as the current directory.
|
||||
fn config_dir(config_path: &Path) -> PathBuf {
|
||||
match config_path.parent() {
|
||||
Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
|
||||
_ => PathBuf::from("."),
|
||||
}
|
||||
}
|
||||
|
||||
/// Prefixes the working directory onto a relative path, then drops the `.` components that
|
||||
/// joining leaves behind — cosmetic, but these paths are printed and pasted into service units.
|
||||
fn absolutize(p: PathBuf) -> PathBuf {
|
||||
let joined = if p.is_absolute() {
|
||||
p
|
||||
} else {
|
||||
match env::current_dir() {
|
||||
Ok(cwd) => cwd.join(p),
|
||||
Err(_) => p,
|
||||
}
|
||||
};
|
||||
let cleaned: PathBuf = joined
|
||||
.components()
|
||||
.filter(|c| !matches!(c, Component::CurDir))
|
||||
.collect();
|
||||
if cleaned.as_os_str().is_empty() {
|
||||
joined
|
||||
} else {
|
||||
cleaned
|
||||
}
|
||||
}
|
||||
|
||||
/// `:memory:` and `file:` URIs are instructions to SQLite, not paths on disk. Anchoring them to a
|
||||
/// directory would turn a working in-memory store into an attempt to create a file called
|
||||
/// `:memory:` — which Windows cannot even name.
|
||||
fn is_sqlite_special(path: &str) -> bool {
|
||||
path == ":memory:" || path.starts_with("file:")
|
||||
}
|
||||
|
||||
fn create_parent_dir(path: &Path) -> anyhow::Result<()> {
|
||||
if let Some(dir) = path.parent() {
|
||||
if !dir.as_os_str().is_empty() && !dir.exists() {
|
||||
fs::create_dir_all(dir)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rewrites the `auth_token` line in an existing config file, preserving everything else. Falls
|
||||
/// back to inserting it under `[web]`, or appending a `[web]` section, if the key is absent.
|
||||
fn persist_token(path: &str, token: &str) -> anyhow::Result<()> {
|
||||
fn persist_token(path: &Path, token: &str) -> anyhow::Result<()> {
|
||||
let text = fs::read_to_string(path)?;
|
||||
let line = format!("auth_token = \"{token}\"");
|
||||
|
||||
@@ -213,10 +347,269 @@ bind = "127.0.0.1:8080"
|
||||
# WebSocket: add ?token=<token> to the connect URL
|
||||
# Authentication is always on: if this is left blank, the sidecar generates a new
|
||||
# token here on startup. Rotate by changing this value and restarting.
|
||||
# Read it back without starting the sidecar: uo-link-sidecar --print-config
|
||||
auth_token = "{token}"
|
||||
|
||||
[store]
|
||||
# Relative paths resolve against the directory holding THIS FILE, not the working
|
||||
# directory of the process.
|
||||
path = "uo-link.db"
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A unique scratch directory. `std::env::temp_dir()` plus the test name keeps the cases
|
||||
/// independent under the default parallel test runner.
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let dir = env::temp_dir().join(format!("uo-link-cfg-test-{name}"));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).expect("create scratch dir");
|
||||
dir
|
||||
}
|
||||
|
||||
/// `Config::load` consults the process environment, and a developer may have `UOLINK_*` set
|
||||
/// for a local shard. Mutating shared env state from a test thread is worse than skipping, so
|
||||
/// the two cases that exercise the full load path bail out instead of failing spuriously.
|
||||
fn env_overrides_present() -> bool {
|
||||
[
|
||||
"UOLINK_SHARD_BIND",
|
||||
"UOLINK_WEB_BIND",
|
||||
"UOLINK_WEB_TOKEN",
|
||||
"UOLINK_DB_PATH",
|
||||
]
|
||||
.iter()
|
||||
.any(|k| env::var_os(k).is_some())
|
||||
}
|
||||
|
||||
fn cfg_with_store(path: &str) -> Config {
|
||||
Config {
|
||||
store: StoreCfg { path: path.into() },
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_store_path_anchors_to_the_config_directory() {
|
||||
// The working-directory trap: the service pins UOLINK_CONFIG but the service manager
|
||||
// decides the CWD, so a relative db path must not follow the CWD.
|
||||
let mut cfg = cfg_with_store("uo-link.db");
|
||||
let config_path = if cfg!(windows) {
|
||||
PathBuf::from(r"C:\ProgramData\RunicGateway\sidecar.toml")
|
||||
} else {
|
||||
PathBuf::from("/etc/runicgateway/sidecar.toml")
|
||||
};
|
||||
cfg.anchor_store_path(&config_path);
|
||||
|
||||
let expected = config_path.parent().unwrap().join("uo-link.db");
|
||||
assert_eq!(Path::new(&cfg.store.path), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_store_path_is_left_alone() {
|
||||
let absolute = if cfg!(windows) {
|
||||
r"C:\ProgramData\RunicGateway\uo-link.db"
|
||||
} else {
|
||||
"/var/lib/runicgateway/uo-link.db"
|
||||
};
|
||||
let mut cfg = cfg_with_store(absolute);
|
||||
cfg.anchor_store_path(Path::new("/etc/runicgateway/sidecar.toml"));
|
||||
assert_eq!(cfg.store.path, absolute);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_config_filename_anchors_to_the_working_directory() {
|
||||
// `cargo run` in the crate root: config dir and CWD are the same, so the historical
|
||||
// behavior (db beside the binary's CWD) is preserved exactly.
|
||||
let mut cfg = cfg_with_store("uo-link.db");
|
||||
cfg.anchor_store_path(Path::new("sidecar.toml"));
|
||||
assert_eq!(
|
||||
Path::new(&cfg.store.path),
|
||||
env::current_dir().unwrap().join("uo-link.db")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sqlite_special_paths_are_not_anchored() {
|
||||
for special in [":memory:", "file:cache?mode=memory"] {
|
||||
let mut cfg = cfg_with_store(special);
|
||||
cfg.anchor_store_path(Path::new("/etc/runicgateway/sidecar.toml"));
|
||||
assert_eq!(cfg.store.path, special);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_path_prefers_the_cli_override() {
|
||||
// Absolute in, absolute out — and unchanged, so the operator sees the path they passed.
|
||||
let explicit = if cfg!(windows) {
|
||||
r"C:\tmp\custom.toml"
|
||||
} else {
|
||||
"/tmp/custom.toml"
|
||||
};
|
||||
assert_eq!(
|
||||
Config::resolve_path(Some(explicit)),
|
||||
PathBuf::from(explicit)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_path_makes_a_relative_override_absolute() {
|
||||
let resolved = Config::resolve_path(Some("./conf/sidecar.toml"));
|
||||
assert!(resolved.is_absolute(), "{}", resolved.display());
|
||||
assert_eq!(
|
||||
resolved,
|
||||
env::current_dir()
|
||||
.unwrap()
|
||||
.join("conf")
|
||||
.join("sidecar.toml")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persist_token_replaces_an_existing_key() {
|
||||
let dir = scratch("replace");
|
||||
let path = dir.join("sidecar.toml");
|
||||
fs::write(
|
||||
&path,
|
||||
"[web]\nbind = \"127.0.0.1:8080\"\nauth_token = \"\"\n\n[store]\npath = \"x.db\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
persist_token(&path, "deadbeef").unwrap();
|
||||
|
||||
let out = fs::read_to_string(&path).unwrap();
|
||||
assert!(out.contains("auth_token = \"deadbeef\""), "{out}");
|
||||
assert_eq!(out.matches("auth_token").count(), 1, "{out}");
|
||||
// Everything else survives — the file is the operator's, not ours to rewrite.
|
||||
assert!(out.contains("bind = \"127.0.0.1:8080\""), "{out}");
|
||||
assert!(out.contains("path = \"x.db\""), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persist_token_inserts_under_an_existing_web_section() {
|
||||
let dir = scratch("insert");
|
||||
let path = dir.join("sidecar.toml");
|
||||
fs::write(&path, "[web]\nbind = \"127.0.0.1:8080\"\n").unwrap();
|
||||
|
||||
persist_token(&path, "deadbeef").unwrap();
|
||||
|
||||
let out = fs::read_to_string(&path).unwrap();
|
||||
let web = out.find("[web]").unwrap();
|
||||
let token = out.find("auth_token").unwrap();
|
||||
assert!(token > web, "token must land inside [web]: {out}");
|
||||
assert!(out.contains("auth_token = \"deadbeef\""), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persist_token_appends_a_web_section_when_there_is_none() {
|
||||
let dir = scratch("append");
|
||||
let path = dir.join("sidecar.toml");
|
||||
fs::write(&path, "[shard]\nbind = \"127.0.0.1:7788\"\n").unwrap();
|
||||
|
||||
persist_token(&path, "deadbeef").unwrap();
|
||||
|
||||
let out = fs::read_to_string(&path).unwrap();
|
||||
assert!(out.contains("[shard]"), "{out}");
|
||||
assert!(out.contains("[web]\nauth_token = \"deadbeef\""), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generated_config_round_trips_through_the_parser() {
|
||||
// The template is a format! string, so a stray brace or a bad key would only ever surface
|
||||
// on someone's first run.
|
||||
let cfg: Config = toml::from_str(&default_file("deadbeef")).expect("template parses");
|
||||
assert_eq!(cfg.web.auth_token, "deadbeef");
|
||||
assert_eq!(cfg.shard.bind, "127.0.0.1:7788");
|
||||
assert_eq!(cfg.web.bind, "127.0.0.1:8080");
|
||||
assert_eq!(cfg.store.path, "uo-link.db");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_tokens_are_random_and_hex() {
|
||||
let (a, b) = (generate_token(), generate_token());
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(a.len(), 48);
|
||||
assert!(a.chars().all(|c| c.is_ascii_hexdigit()), "{a}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn describe_reports_the_resolved_configuration() {
|
||||
let loaded = Loaded {
|
||||
cfg: Config {
|
||||
shard: ShardCfg {
|
||||
bind: "127.0.0.1:7788".into(),
|
||||
},
|
||||
web: WebCfg {
|
||||
bind: "0.0.0.0:8080".into(),
|
||||
auth_token: "deadbeef".into(),
|
||||
},
|
||||
store: StoreCfg {
|
||||
path: "/var/lib/runicgateway/uo-link.db".into(),
|
||||
},
|
||||
},
|
||||
path: PathBuf::from("/etc/runicgateway/sidecar.toml"),
|
||||
config_created: true,
|
||||
token_generated: true,
|
||||
};
|
||||
|
||||
let doc = describe(&loaded);
|
||||
|
||||
assert_eq!(doc["component"], "uo-link-sidecar");
|
||||
assert_eq!(doc["version"], env!("CARGO_PKG_VERSION"));
|
||||
assert_eq!(doc["protocol"], PROTOCOL_VERSION);
|
||||
assert_eq!(doc["config_path"], "/etc/runicgateway/sidecar.toml");
|
||||
assert_eq!(doc["config_created"], true);
|
||||
assert_eq!(doc["token_generated"], true);
|
||||
assert_eq!(doc["shard"]["bind"], "127.0.0.1:7788");
|
||||
assert_eq!(doc["web"]["bind"], "0.0.0.0:8080");
|
||||
assert_eq!(doc["web"]["ws_path"], "/ws");
|
||||
assert_eq!(doc["web"]["auth_required"], true);
|
||||
assert_eq!(doc["web"]["auth_token"], "deadbeef");
|
||||
assert_eq!(doc["store"]["path"], "/var/lib/runicgateway/uo-link.db");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_provisions_a_missing_config_and_reports_it() {
|
||||
if env_overrides_present() {
|
||||
return;
|
||||
}
|
||||
let dir = scratch("provision");
|
||||
let path = dir.join("sidecar.toml");
|
||||
|
||||
let loaded = Config::load(Some(path.to_str().unwrap())).unwrap();
|
||||
|
||||
assert!(loaded.config_created);
|
||||
assert!(loaded.token_generated);
|
||||
assert!(
|
||||
path.exists(),
|
||||
"the config file must be written, not just held in memory"
|
||||
);
|
||||
assert!(!loaded.cfg.web.auth_token.is_empty());
|
||||
// The db lands beside the config, whatever the working directory is.
|
||||
assert_eq!(Path::new(&loaded.cfg.store.path), dir.join("uo-link.db"));
|
||||
|
||||
// Second run: same token, and nothing reported as new.
|
||||
let again = Config::load(Some(path.to_str().unwrap())).unwrap();
|
||||
assert!(!again.config_created);
|
||||
assert!(!again.token_generated);
|
||||
assert_eq!(again.cfg.web.auth_token, loaded.cfg.web.auth_token);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn load_creates_the_config_directory() {
|
||||
if env_overrides_present() {
|
||||
return;
|
||||
}
|
||||
// An installer pointing at a fresh /etc/runicgateway should not have to mkdir first.
|
||||
let dir = scratch("mkdir").join("nested").join("deeper");
|
||||
let path = dir.join("sidecar.toml");
|
||||
|
||||
let loaded = Config::load(Some(path.to_str().unwrap())).unwrap();
|
||||
|
||||
assert!(path.exists(), "{}", path.display());
|
||||
assert!(loaded.config_created);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! Terminates the loopback link to the ServUO shard and exposes a website-facing HTTP surface. So
|
||||
//! far: the shard link (bidirectional) and a WebSocket live feed. REST queries and SQLite come next.
|
||||
|
||||
mod cli;
|
||||
mod config;
|
||||
mod rpc;
|
||||
mod shard;
|
||||
@@ -24,17 +25,57 @@ use tracing_subscriber::EnvFilter;
|
||||
/// v2 (Protocol 2.0): adds the account-provisioning verbs/endpoints (`POST /accounts/create`,
|
||||
/// `DELETE /link/:account`) and their events. Outbound event kinds are additive, so a v1 website
|
||||
/// keeps working against the live feed; the new *endpoints* require a v2 sidecar.
|
||||
pub const PROTOCOL_VERSION: u32 = 2;
|
||||
///
|
||||
/// v3 (Protocol 3.0): adds `world.ruleset`, `points.board` and `vendor.listing` /
|
||||
/// `vendor.listing.remove`, with the `GET /ruleset`, `/points` and `/market` reads that serve them
|
||||
/// from the store. Same shape as the v2 bump — the kinds are additive, the endpoints are not — and
|
||||
/// there is deliberately no feature-negotiation array: v3 implies all three kinds.
|
||||
pub const PROTOCOL_VERSION: u32 = 3;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let args = match cli::parse(std::env::args().skip(1)) {
|
||||
Ok(args) => args,
|
||||
Err(msg) => {
|
||||
eprintln!("uo-link-sidecar: {msg}\n\n{}", cli::USAGE);
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
|
||||
match args.mode {
|
||||
cli::Mode::Help => {
|
||||
print!("{}", cli::USAGE);
|
||||
return Ok(());
|
||||
}
|
||||
cli::Mode::Version => {
|
||||
println!(
|
||||
"uo-link-sidecar {} (protocol {})",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
PROTOCOL_VERSION
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
// Tracing stays uninitialized here on purpose: the subscriber writes to stdout, and stdout
|
||||
// is the document. Config::load's messages are dropped rather than interleaved into JSON
|
||||
// an installer is about to parse — everything they would have said is in the document.
|
||||
cli::Mode::PrintConfig => {
|
||||
let loaded = config::Config::load(args.config.as_deref())?;
|
||||
println!("{:#}", config::describe(&loaded));
|
||||
return Ok(());
|
||||
}
|
||||
cli::Mode::Run => {}
|
||||
}
|
||||
|
||||
init_tracing();
|
||||
info!("uo-link sidecar starting");
|
||||
|
||||
let cfg = config::Config::load()?;
|
||||
let loaded = config::Config::load(args.config.as_deref())?;
|
||||
let cfg = loaded.cfg;
|
||||
info!(
|
||||
config = %loaded.path.display(),
|
||||
shard = %cfg.shard.bind,
|
||||
web = %cfg.web.bind,
|
||||
db = %cfg.store.path,
|
||||
auth = cfg.auth_required(),
|
||||
"configuration loaded"
|
||||
);
|
||||
@@ -194,6 +235,75 @@ async fn main() -> anyhow::Result<()> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Points/loyalty boards (Protocol 3.0): one row per point system, keyed by
|
||||
// the shard's own PointsType name. The plugin only emits a system whose top N
|
||||
// actually moved, so this is a sparse stream of overwrites — and there is no
|
||||
// `points.remove` to handle, because the shard's set of systems is fixed at
|
||||
// startup and cannot shrink.
|
||||
"points.board" => {
|
||||
if let Some(system) = ev.value.get("system").and_then(|s| s.as_str()) {
|
||||
if let Err(e) = event_store
|
||||
.upsert_points_board(
|
||||
system,
|
||||
ev.value.get("nameString").and_then(|n| n.as_str()),
|
||||
&text,
|
||||
t,
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to upsert points board");
|
||||
}
|
||||
}
|
||||
}
|
||||
// Player-vendor market index (Protocol 3.0). Each frame is authoritative for
|
||||
// one vendor — the shard's round-robin sweep only emits a shop whose contents,
|
||||
// prices or location actually moved — so this is a whole-row overwrite.
|
||||
//
|
||||
// Unlike the boards above there IS a remove: a vendor is dismissed, expires, or
|
||||
// its owner switches off the in-game Vendor Search flag, and any of those must
|
||||
// take the shop off the site. The last of the three is a privacy control, so
|
||||
// dropping the row promptly is the point rather than housekeeping.
|
||||
"vendor.listing" => {
|
||||
if let Some(serial) = ev.value.get("serial").and_then(|s| s.as_str()) {
|
||||
let loc = ev.value.get("location");
|
||||
let field = |k: &str| loc.and_then(|l| l.get(k));
|
||||
if let Err(e) = event_store
|
||||
.upsert_vendor(
|
||||
serial,
|
||||
ev.value.get("shopName").and_then(|v| v.as_str()),
|
||||
ev.value.get("ownerName").and_then(|v| v.as_str()),
|
||||
field("map").and_then(|v| v.as_str()),
|
||||
field("x").and_then(|v| v.as_i64()),
|
||||
field("y").and_then(|v| v.as_i64()),
|
||||
field("region").and_then(|v| v.as_str()),
|
||||
ev.value.get("count").and_then(|v| v.as_i64()),
|
||||
&text,
|
||||
t,
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to upsert vendor listing");
|
||||
}
|
||||
}
|
||||
}
|
||||
"vendor.listing.remove" => {
|
||||
if let Some(serial) = ev.value.get("serial").and_then(|s| s.as_str()) {
|
||||
if let Err(e) = event_store.delete_vendor(serial).await {
|
||||
tracing::warn!(error = %e, "failed to remove vendor listing");
|
||||
}
|
||||
}
|
||||
}
|
||||
// Shard ruleset (Protocol 3.0): a singleton projection. The shard re-emits
|
||||
// world.ruleset on every connect, so this row is simply overwritten; `rev`
|
||||
// lets a reader tell a re-send from an actual config change.
|
||||
"world.ruleset" => {
|
||||
if let Err(e) = event_store
|
||||
.upsert_ruleset(ev.value.get("rev").and_then(|r| r.as_str()), &text, t)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(error = %e, "failed to upsert ruleset");
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! instead of round-tripping the shard. Links and profiles are written from the REST reply paths
|
||||
//! (`link.ok`, `char.profile`), which are RPC replies and never hit the broadcast stream.
|
||||
|
||||
use std::str::FromStr;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::Value;
|
||||
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
|
||||
@@ -20,9 +20,24 @@ pub struct Store {
|
||||
|
||||
impl Store {
|
||||
/// Opens (creating if absent) the SQLite database and ensures the schema exists.
|
||||
///
|
||||
/// `path` is a filesystem path, handed to sqlx as one. It is deliberately **not** formatted
|
||||
/// into a `sqlite://` URL first: that spelling is parsed as a URL, so it percent-decodes the
|
||||
/// path and splits it on `?`. Under an installed layout the path is absolute and chosen by the
|
||||
/// operator — `C:\ProgramData\RunicGateway\uo-link.db`, or something under a home directory
|
||||
/// with a `%` or `#` in it — and a URL round-trip silently opens a *different* file.
|
||||
pub async fn open(path: &str) -> anyhow::Result<Self> {
|
||||
let opts =
|
||||
SqliteConnectOptions::from_str(&format!("sqlite://{path}"))?.create_if_missing(true);
|
||||
// A service unit can name a data directory that does not exist yet; creating it here means
|
||||
// one less way for a fresh install to fail on first start.
|
||||
if let Some(dir) = Path::new(path).parent() {
|
||||
if !dir.as_os_str().is_empty() && !dir.exists() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
}
|
||||
|
||||
let opts = SqliteConnectOptions::new()
|
||||
.filename(path)
|
||||
.create_if_missing(true);
|
||||
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(4)
|
||||
@@ -293,6 +308,174 @@ impl Store {
|
||||
Ok(parse_json_column(rows))
|
||||
}
|
||||
|
||||
// ---- shard ruleset (Protocol 3.0) ----
|
||||
|
||||
/// Stores the shard's published ruleset. A singleton (`id = 1`): the shard emits one
|
||||
/// `world.ruleset` frame per connect describing how it is configured, and only the latest one
|
||||
/// matters. `rev` is the shard's FNV-1a of the body, kept so a reader can tell "same ruleset,
|
||||
/// re-sent on reconnect" from "the operator changed something" without diffing the JSON.
|
||||
pub async fn upsert_ruleset(
|
||||
&self,
|
||||
rev: Option<&str>,
|
||||
json: &str,
|
||||
t: i64,
|
||||
) -> anyhow::Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO ruleset (id, rev, json, updated_t) VALUES (1, ?, ?, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET rev = excluded.rev, json = excluded.json, updated_t = excluded.updated_t",
|
||||
)
|
||||
.bind(rev)
|
||||
.bind(json)
|
||||
.bind(t)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The stored ruleset, or `None` if the shard has never published one. Returning `None` rather
|
||||
/// than an empty object is deliberate: "not published yet" and "published, everything off" are
|
||||
/// different answers and the website renders them differently.
|
||||
pub async fn ruleset(&self) -> anyhow::Result<Option<Value>> {
|
||||
let row = sqlx::query("SELECT json FROM ruleset WHERE id = 1")
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
Ok(row.and_then(|r| serde_json::from_str(&r.get::<String, _>("json")).ok()))
|
||||
}
|
||||
|
||||
// ---- points / loyalty boards (Protocol 3.0) ----
|
||||
|
||||
/// Upserts one system's leaderboard, keyed by its `PointsType` name (`QueensLoyalty`,
|
||||
/// `CleanUpBritannia`, …). Fed from `points.board`; one row per system, always the most recent
|
||||
/// top-N snapshot.
|
||||
///
|
||||
/// There is no matching delete, and that is deliberate rather than an omission: the shard's set
|
||||
/// of point systems is fixed at startup by `PointsSystem.Configure`, so a system cannot vanish
|
||||
/// at runtime and the plugin emits no `points.remove`. Same argument the governor board makes.
|
||||
pub async fn upsert_points_board(
|
||||
&self,
|
||||
system: &str,
|
||||
name: Option<&str>,
|
||||
json: &str,
|
||||
t: i64,
|
||||
) -> anyhow::Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO points_boards (system, name, json, updated_t) VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(system) DO UPDATE SET name = excluded.name, json = excluded.json, updated_t = excluded.updated_t",
|
||||
)
|
||||
.bind(system)
|
||||
.bind(name)
|
||||
.bind(json)
|
||||
.bind(t)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Every system's latest board, ordered by display name then system key. Systems the shard has
|
||||
/// never published are simply absent — the website renders the set it is given.
|
||||
pub async fn points_boards_all(&self) -> anyhow::Result<Vec<Value>> {
|
||||
let rows = sqlx::query("SELECT json FROM points_boards ORDER BY name, system")
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
Ok(parse_json_column(rows))
|
||||
}
|
||||
|
||||
/// One system's board, or `None` when that system has never published one. `None` is a real
|
||||
/// answer (an unknown system name, or one the operator excluded via `Bridge.cfg PointsSystems`),
|
||||
/// which the website turns into a 404 rather than an empty board.
|
||||
pub async fn points_board(&self, system: &str) -> anyhow::Result<Option<Value>> {
|
||||
let row = sqlx::query("SELECT json FROM points_boards WHERE system = ?")
|
||||
.bind(system)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
Ok(row.and_then(|r| serde_json::from_str(&r.get::<String, _>("json")).ok()))
|
||||
}
|
||||
|
||||
// ---- player-vendor market index (Protocol 3.0) ----
|
||||
|
||||
/// Upserts one vendor's whole listing, keyed by serial. Fed from `vendor.listing`, which the
|
||||
/// shard emits as an authoritative per-vendor frame — so this replaces the row outright rather
|
||||
/// than merging anything.
|
||||
///
|
||||
/// The items ride inside `json` and are deliberately NOT normalized into a `vendor_items`
|
||||
/// table. The sidecar's job for the market is outage resilience (`PROTOCOL_2.md` §12.2) — hand
|
||||
/// the website back what the shard last said — not search. Search lives in MariaDB on the
|
||||
/// website side, where the query surface, the indexes and the cliloc-resolved display names
|
||||
/// already are; a second search implementation here would be one more thing to keep in step
|
||||
/// with it for no reader.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn upsert_vendor(
|
||||
&self,
|
||||
serial: &str,
|
||||
shop_name: Option<&str>,
|
||||
owner_name: Option<&str>,
|
||||
map: Option<&str>,
|
||||
x: Option<i64>,
|
||||
y: Option<i64>,
|
||||
region: Option<&str>,
|
||||
count: Option<i64>,
|
||||
json: &str,
|
||||
t: i64,
|
||||
) -> anyhow::Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO vendors (serial, shop_name, owner_name, map, x, y, region, count, json, updated_t)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(serial) DO UPDATE SET shop_name = excluded.shop_name,
|
||||
owner_name = excluded.owner_name, map = excluded.map, x = excluded.x, y = excluded.y,
|
||||
region = excluded.region, count = excluded.count, json = excluded.json,
|
||||
updated_t = excluded.updated_t",
|
||||
)
|
||||
.bind(serial)
|
||||
.bind(shop_name)
|
||||
.bind(owner_name)
|
||||
.bind(map)
|
||||
.bind(x)
|
||||
.bind(y)
|
||||
.bind(region)
|
||||
.bind(count)
|
||||
.bind(json)
|
||||
.bind(t)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops one vendor from the index. Fed from `vendor.listing.remove` — a vendor dismissed,
|
||||
/// expired, or whose owner switched off its in-game Vendor Search flag.
|
||||
pub async fn delete_vendor(&self, serial: &str) -> anyhow::Result<()> {
|
||||
sqlx::query("DELETE FROM vendors WHERE serial = ?")
|
||||
.bind(serial)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One page of the index, ordered by serial.
|
||||
///
|
||||
/// Paged where the other boards are not, and the ordering is why it can be: a whole-world
|
||||
/// market is the one board that does not fit in a response. Ordering by SERIAL rather than by
|
||||
/// shop name is deliberate — the page is a snapshot cursor for the website's reconnect
|
||||
/// backfill, and a serial is stable while a shop name is renameable, so a rename mid-backfill
|
||||
/// cannot make a vendor skip or repeat a page.
|
||||
pub async fn vendors_page(&self, limit: i64, offset: i64) -> anyhow::Result<Vec<Value>> {
|
||||
let limit = limit.clamp(1, 1000);
|
||||
let offset = offset.max(0);
|
||||
let rows = sqlx::query("SELECT json FROM vendors ORDER BY serial LIMIT ? OFFSET ?")
|
||||
.bind(limit)
|
||||
.bind(offset)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
Ok(parse_json_column(rows))
|
||||
}
|
||||
|
||||
/// How many vendors the index holds, so a paging caller knows when to stop.
|
||||
pub async fn vendors_count(&self) -> anyhow::Result<i64> {
|
||||
let row = sqlx::query("SELECT COUNT(*) AS n FROM vendors")
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
Ok(row.get::<i64, _>("n"))
|
||||
}
|
||||
|
||||
// ---- Town Cryer news (Protocol 2.1) ----
|
||||
|
||||
/// Stores/replaces one external news article (the `news.add` command json), keyed by id. The
|
||||
@@ -392,4 +575,39 @@ CREATE TABLE IF NOT EXISTS news (
|
||||
json TEXT NOT NULL,
|
||||
updated_t INTEGER NOT NULL
|
||||
);
|
||||
|
||||
-- Points/loyalty leaderboards (Protocol 3.0). One row per point system, keyed by the shard's
|
||||
-- own PointsType name; `name` is the resolved display name, hoisted only for the ORDER BY.
|
||||
CREATE TABLE IF NOT EXISTS points_boards (
|
||||
system TEXT PRIMARY KEY,
|
||||
name TEXT,
|
||||
json TEXT NOT NULL,
|
||||
updated_t INTEGER NOT NULL
|
||||
);
|
||||
|
||||
-- Player-vendor market index (Protocol 3.0). One row per vendor, holding the whole authoritative
|
||||
-- `vendor.listing` frame including its items. The hoisted columns exist for the ORDER BY and for
|
||||
-- an operator eyeballing the table; nothing here is searched, because search is the website's job
|
||||
-- (see upsert_vendor). Rows are dropped on `vendor.listing.remove`.
|
||||
CREATE TABLE IF NOT EXISTS vendors (
|
||||
serial TEXT PRIMARY KEY,
|
||||
shop_name TEXT,
|
||||
owner_name TEXT,
|
||||
map TEXT,
|
||||
x INTEGER,
|
||||
y INTEGER,
|
||||
region TEXT,
|
||||
count INTEGER,
|
||||
json TEXT NOT NULL,
|
||||
updated_t INTEGER NOT NULL
|
||||
);
|
||||
|
||||
-- The shard's published ruleset (Protocol 3.0). Singleton: the CHECK is what makes it one,
|
||||
-- so an upsert can target id = 1 unconditionally and no second row can ever appear.
|
||||
CREATE TABLE IF NOT EXISTS ruleset (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
rev TEXT,
|
||||
json TEXT NOT NULL,
|
||||
updated_t INTEGER NOT NULL
|
||||
);
|
||||
"#;
|
||||
|
||||
@@ -43,10 +43,14 @@ pub struct AppState {
|
||||
pub last_event: Arc<AtomicI64>,
|
||||
}
|
||||
|
||||
/// Path of the live-feed WebSocket. Named because `--print-config` reports it: an installer builds
|
||||
/// the website's WS URL from `web.bind` plus this, and neither side should be hardcoding it twice.
|
||||
pub const WS_PATH: &str = "/ws";
|
||||
|
||||
pub async fn serve(addr: &str, state: AppState) -> anyhow::Result<()> {
|
||||
// Everything except /health is behind the auth check.
|
||||
let protected = Router::new()
|
||||
.route("/ws", get(ws_upgrade))
|
||||
.route(WS_PATH, get(ws_upgrade))
|
||||
// Queries (shard reply correlated by reqId).
|
||||
.route("/char/:account/:slot", get(char_by_slot))
|
||||
.route("/char/serial/:serial", get(char_by_serial))
|
||||
@@ -82,6 +86,20 @@ pub async fn serve(addr: &str, state: AppState) -> anyhow::Result<()> {
|
||||
.route("/governors", get(governors))
|
||||
.route("/online", get(online))
|
||||
.route("/houses", get(houses))
|
||||
// The shard ruleset (Protocol 3.0), likewise store-backed: the shard publishes it once per
|
||||
// connect, so serving it from the store is what lets the site's rules page render while the
|
||||
// shard is down.
|
||||
.route("/ruleset", get(ruleset))
|
||||
// Points/loyalty leaderboards (Protocol 3.0), store-backed like the other boards: the
|
||||
// whole set, or one system by its PointsType name.
|
||||
.route("/points", get(points))
|
||||
.route("/points/:system", get(points_system))
|
||||
// The player-vendor market index (Protocol 3.0). `/market`, NOT `/vendors`: axum would
|
||||
// route the latter fine, but `/vendors/:account` next door is the per-account RPC, and two
|
||||
// routes a prefix apart that mean "this player's shops" and "every shop on the shard" is a
|
||||
// readability trap nobody wins. The only PAGED read the sidecar serves — a whole-world
|
||||
// market does not fit in one response.
|
||||
.route("/market", get(market))
|
||||
.route_layer(middleware::from_fn_with_state(state.clone(), gate));
|
||||
|
||||
let app = Router::new()
|
||||
@@ -790,6 +808,60 @@ async fn houses(State(st): State<AppState>) -> impl IntoResponse {
|
||||
}
|
||||
}
|
||||
|
||||
/// The shard's published ruleset: expansion, which optional systems are on, skill/stat caps,
|
||||
/// account and house limits, champion scroll rules, the save/restart schedule. Served from the
|
||||
/// store, so it answers during a shard outage with the last-known ruleset — which is the whole
|
||||
/// point, since a rules page that goes blank when the shard restarts is worse than a stale one.
|
||||
///
|
||||
/// `{"ruleset": null}` means the shard has never published one (an old plugin, or
|
||||
/// `Bridge.RulesetEnabled=false`), which the website renders differently from a published ruleset.
|
||||
async fn ruleset(State(st): State<AppState>) -> impl IntoResponse {
|
||||
match st.store.ruleset().await {
|
||||
Ok(r) => (StatusCode::OK, Json(json!({ "ruleset": r }))),
|
||||
Err(e) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({"error": e.to_string()})),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every points/loyalty leaderboard the shard publishes: one entry per point system, each with its
|
||||
/// display name (literal and/or cliloc), max points, participant count and top N. Store-backed like
|
||||
/// the other boards, so the site's leaderboards page renders during a shard outage — which matters
|
||||
/// more here than elsewhere, since these are month-scale standings that a restart must not blank.
|
||||
async fn points(State(st): State<AppState>) -> impl IntoResponse {
|
||||
match st.store.points_boards_all().await {
|
||||
Ok(boards) => (StatusCode::OK, Json(json!({"boards": boards}))),
|
||||
Err(e) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({"error": e.to_string()})),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// One system's board by its `PointsType` name (`QueensLoyalty`, `CleanUpBritannia`, …).
|
||||
///
|
||||
/// 404 rather than an empty board when the system is unknown: the shard publishes only the systems
|
||||
/// it shows on the loyalty gump (or the explicit `Bridge.cfg PointsSystems` list), so "no such
|
||||
/// board" and "a board with nobody on it" are different answers and the website renders them
|
||||
/// differently.
|
||||
async fn points_system(
|
||||
State(st): State<AppState>,
|
||||
Path(system): Path<String>,
|
||||
) -> impl IntoResponse {
|
||||
match st.store.points_board(&system).await {
|
||||
Ok(Some(board)) => (StatusCode::OK, Json(board)),
|
||||
Ok(None) => (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(json!({"error": "unknown points system", "system": system})),
|
||||
),
|
||||
Err(e) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({"error": e.to_string()})),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The current online population: total plus per-facet and per-region counts. This is the most
|
||||
/// recent `presence.online` snapshot from the event store (so it survives a sidecar restart); the
|
||||
/// live `presence.online` stream keeps it current, and `GET /history?kind=presence.online` gives the
|
||||
@@ -810,6 +882,54 @@ async fn online(State(st): State<AppState>) -> impl IntoResponse {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PageQuery {
|
||||
limit: Option<i64>,
|
||||
offset: Option<i64>,
|
||||
}
|
||||
|
||||
/// The player-vendor market index: every vendor's shop name, owner, location and priced inventory,
|
||||
/// as the shard last published it. Store-backed like the other boards, which is what lets the
|
||||
/// website's market page render (labelled stale) while the shard is down.
|
||||
///
|
||||
/// Paged — `?limit=&offset=`, limit clamped to 1..1000, default 200 — because this is the one board
|
||||
/// that can be a whole world's inventory. `total` is returned alongside so the caller knows when to
|
||||
/// stop rather than paging until it sees a short page, which would race a concurrent sweep.
|
||||
///
|
||||
/// The frames are served VERBATIM, including owner names and coordinates. That is not an oversight:
|
||||
/// the sidecar defines no audiences (docs/link/v3.md §3.2). Deciding who may see a vendor's owner
|
||||
/// or whereabouts is the website's job and is admin-configurable there.
|
||||
async fn market(State(st): State<AppState>, Query(q): Query<PageQuery>) -> impl IntoResponse {
|
||||
let limit = q.limit.unwrap_or(200);
|
||||
let offset = q.offset.unwrap_or(0);
|
||||
|
||||
let total = match st.store.vendors_count().await {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({"error": e.to_string()})),
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
match st.store.vendors_page(limit, offset).await {
|
||||
Ok(vendors) => (
|
||||
StatusCode::OK,
|
||||
Json(json!({
|
||||
"vendors": vendors,
|
||||
"total": total,
|
||||
"limit": limit.clamp(1, 1000),
|
||||
"offset": offset.max(0),
|
||||
})),
|
||||
),
|
||||
Err(e) => (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(json!({"error": e.to_string()})),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- websocket ----
|
||||
|
||||
async fn ws_upgrade(ws: WebSocketUpgrade, State(state): State<AppState>) -> impl IntoResponse {
|
||||
|
||||
25
sonar-project.properties
Normal file
25
sonar-project.properties
Normal file
@@ -0,0 +1,25 @@
|
||||
# SonarQube analysis config for the link (uo-link sidecar) repo.
|
||||
# Consumed by the scanner in .gitea/workflows/sonarqube.yml on push to main.
|
||||
# The project key must match the one created in SonarQube (dashboard URL
|
||||
# ?id=Runic-Gateway-link).
|
||||
|
||||
sonar.projectKey=Runic-Gateway-link
|
||||
sonar.projectName=runic gateway link
|
||||
|
||||
# Analysed application code. The Rust sidecar crate lives under sidecar/src.
|
||||
# Rust unit tests live inline (#[cfg(test)] modules) rather than in a separate
|
||||
# tree, so there is no distinct sonar.tests path to declare.
|
||||
sonar.sources=sidecar/src
|
||||
|
||||
# Never analyse build output, the vendored lockfile, or generated config.
|
||||
sonar.exclusions=**/target/**,**/*.lock
|
||||
|
||||
sonar.sourceEncoding=UTF-8
|
||||
|
||||
# ── Optional enrichment (enable if your SonarQube edition/version supports it) ──
|
||||
# SonarQube imports Clippy findings when given a JSON report. To turn this on:
|
||||
# 1. In sonarqube.yml, add a step before the scan that runs:
|
||||
# cargo clippy --message-format=json > sidecar/clippy-report.json
|
||||
# (needs the Rust toolchain + `rustup component add clippy` on the runner).
|
||||
# 2. Uncomment the line below.
|
||||
# sonar.rust.clippy.reportPaths=sidecar/clippy-report.json
|
||||
Reference in New Issue
Block a user