GitHubComeçar

Esta página ainda não foi traduzida para português, por isso a versão em inglês é exibida abaixo.

Multiplayer e mods

admin

import "github.com/nsgo-dev/game/pkg/online/admin"

admin gives the self-hosted services an operator door of their own: who the operators are, what each may do, how they sign in, and an audit record of every operator call that changes something. accountsd, cloudsaved and leaderboardd serve it on a second listener when their configuration has an admin: block, and a dedicated server can mount gameserver.Inspector on the same foundation. Operator routes never mount on a player-facing listener.

It is server-side code and does not depend on NSGo.

Turning it on

Add an admin: block at the end of the daemon's configuration file (accounts.yaml, cloudsave.yaml or leaderboards.yaml):

admin:
  addr: 127.0.0.1:9090
  operators: operators.yaml
  audit: audit
  allowedOrigins:
    - https://console.example.com
  sessionTTL: 8h
  idleTimeout: 30m
Field Meaning
addr Address of the admin listener. It must differ from the daemon's -addr; keep it on a private network or behind a proxy only operators reach.
operators The operators file. Its TOTP secrets, when an operator needs them, are in the file of the same name ending in .totp.yaml.
audit Directory of the audit log, one JSON Lines file per UTC day (audit log).
allowedOrigins Web origins of an operator console allowed to use a session from a browser. Command-line tools that use tokens need no entry.
sessionTTL How long a session lasts from sign-in, 1m to 24h; 8h when omitted.
idleTimeout How long a session lasts without a request, 1m to the session TTL; 30m (or the TTL, when shorter) when omitted.

Relative paths are relative to the configuration file's directory. Without the block the daemon has no admin listener and answers 404 for every /admin/ path. The daemon reloads the operators and secrets files within a few seconds of a change; if the new files do not load, it logs why and keeps the previous ones.

Operators and roles

operators.yaml lists the operators, each with a role and an argon2id password hash, never a plaintext password:

version: 1
operators:
  - id: ada
    role: owner
    password: $argon2id$v=19$m=19456,t=2,p=1$c2FsdHNhbHRzYWx0c2FsdA$aGFzaGhhc2hoYXNoaGFzaGhhc2hoYXNoaGFzaGhhc2g
    totp: required
  - id: ci
    role: viewer
    tokensNotBefore: "2026-11-30T12:00:00Z"
roles:
  support-lead:
    - '*.read'
    - accounts.*

An operator ID is 1 to 64 characters of a-z, 0-9, ., _ and -; audit records name it as op:<id>. An operator without a password cannot sign in with a session and uses bearer tokens only, as a CI job does. totp: required adds a code from an authenticator app at sign-in. tokensNotBefore, a UTC time in whole seconds, refuses the operator's bearer tokens issued before it.

A permission is a service.action string, such as accounts.suspend or cloudsave.restore. A role grants a list of patterns: * (everything), service.* (every action of one service), *.action (one action of every service) or an exact permission. *.read grants accounts.read but not cloudsave.read.payload, so reading a save's contents, which may hold personal data, needs its own grant. The built-in roles:

Role Patterns
viewer *.read, which includes audit.read: the audit log, with every operator's actions and failed sign-ins
support *.read, accounts.export, accounts.revoke, accounts.suspend, cloudsave.read.payload, cloudsave.restore
moderator *.read, accounts.revoke, accounts.suspend, leaderboard.delete, leaderboard.hide
operator *.read, accounts.*, cloudsave.*, leaderboard.*, server.*
owner *

A file may define more roles under roles:, but not redefine a built-in one. The permissions this package and gameserver.Inspector check are audit.read (the audit log), server.read (a game server's runtime, matches, rooms and peers) and server.pprof (its profiles); each service names its own operator routes' permissions on its page, such as cloud save's operator routes.

Managing operators

game admin edits the files, so no one writes a hash or a secret by hand:

printf '%s\n' "$ADA_PASSWORD" | go tool game admin operator add -role owner -totp ada
go tool game admin operator add -role viewer -no-password ci
printf '%s\n' "$NEW_PASSWORD" | go tool game admin operator passwd ada
go tool game admin operator totp ada
go tool game admin operator totp -off ada
go tool game admin operator revoke-tokens ci

-file names the operators file (operators.yaml by default). A password is read from the first line of standard input, 12 to 1024 characters; the line is echoed on a terminal, so pipe it in from a password manager or a secret store. add -totp and totp write a new 160-bit secret to the .totp.yaml file, readable by its owner alone, and print it with its otpauth:// URI for an authenticator app (-issuer sets the name the app shows). revoke-tokens sets the operator's tokensNotBefore to now, so every bearer token issued for it until then is refused; add sets it too, so the tokens of an earlier operator with the same ID stay refused. Keep the .totp.yaml file out of version control; the operators file holds no secret in the clear and may be reviewed like any other text file. Both formats are on File Formats.

Signing in

A browser console signs in with a session:

POST /admin/v1/session
Content-Type: application/json

{"operator": "ada", "password": "...", "totp": "123456"}

The answer is {"service", "operator", "role", "permissions", "via": "session", "csrf", "expires"} and a nsgo_admin_<service> cookie (such as nsgo_admin_accounts, so the listeners of several services on one host keep their sessions apart) that is HttpOnly, SameSite=Strict, limited to /admin/ and Secure behind TLS (or a proxy that sets X-Forwarded-Proto: https). A wrong operator, password or code all answer 401 invalid_credentials. A TOTP code is good for its 30-second step and one step on either side, and is accepted once: signing in again with the same code, even within its window, is refused, on every service that shares the operators file and after a restart. The listeners record the codes they accept in the .totp-used directory beside the operators file (operators.totp-used for operators.yaml), which each daemon needs to be able to write; a TOTP sign-in that cannot be recorded there answers 503. Five refusals in a row lock the operator ID for five minutes (429 locked), and an ID never has more sign-ins in flight than it has refusals left, so attempts sent at once are refused with 429 rather than checked. Sessions live in the daemon's memory, so a restart signs everyone out; a session also ends when its operator leaves the operators file or changes password.

Every state-changing request made with the cookie must carry the session's CSRF token in X-CSRF-Token and an Origin header naming an allowed origin or the listener itself; otherwise it gets 403 csrf. A sign-in from a browser must come from such an origin too. GET /admin/v1/whoami returns the operator, its role and permissions, and for a session the CSRF token again, so a reloaded console page can pick it up. DELETE /admin/v1/session signs out.

Tokens for tools and CI

A command-line tool or a CI job sends Authorization: Bearer <token> instead, with a token for the admin audience signed by the account service's key. Mint one where the key is:

accountsd admin-token -config accounts.yaml -key key.pem -operator ci -ttl 24h

The operator must be in the operators file the configuration's admin: block names, or the one -operators names when accounts.yaml has no such block. The token's subject is op:ci; every daemon's admin listener accepts it with the key set it already verifies players with, for as long as -ttl (1m to 720h), the operator stays in its operators file and the token was issued no earlier than the operator's tokensNotBefore. A password change does not end tokens: game admin operator revoke-tokens does. A request with a token needs no CSRF token, since a browser never attaches one by itself. The account service never issues a player a token for the admin audience: every service's configuration refuses admin as its audience.

Audit log

Every state-changing request, refused or not, writes an audit.Record: the actor op:<id>, the route's action (such as accounts.suspend), what it acted on, and the method, path, status and whether it came with a session or a token. A missing permission writes admin.denied for reads too. Sign-in writes admin.signin or admin.signin.failed, and sign-out admin.signout. A request with no session or token is refused with 401, and recorded as admin.denied by anonymous when it would have changed something. Every record the listener writes has the remote address in remote; behind a proxy that is the proxy's.

Anonymous requests cost their sender nothing, so their records (admin.denied by anonymous and admin.signin.failed) are limited to 30 a minute per remote address; the next record from that address once a minute has passed counts the ones left out in suppressed. Operators' records are never left out: they wait up to ten seconds for room in the audit log's queue. A sign-in whose record cannot be queued in that time is refused with 503 audit_unavailable; the record of a call already made is written to the daemon's log instead. The daemon also logs an error whenever the audit log drops records.

GET /admin/v1/audit reads the records back for operators with audit.read:

Parameter Meaning
from, to RFC 3339 times; records at or after from and before to.
actor Only this actor, such as op:ada.
action Only this action, or with a trailing * (accounts.*) every action that starts with it.
limit At most this many records, 1 to 1000 (the default).
cursor Continue from the next of the previous answer.

The answer is {"records": [{"time", "actor", "action", "subject", "data"}], "next", "corrupt"} in the order the records were written; next is absent once there is nothing more, and corrupt, present when not zero, counts lines skipped because they are not records, such as one torn by a crash. A last line still being written is left for a later read.

Routes of a service

A service registers its operator routes on the listener's Server, each with the one permission it requires (the account service's are listed in accounts):

err := srv.Handle(admin.Route{
	Method:     http.MethodPost,
	Path:       "/admin/v1/accounts/{id}/suspend",
	Permission: "accounts.suspend",
	Handler: func(w http.ResponseWriter, r *http.Request, c *admin.Call) {
		c.SetSubject("account:" + r.PathValue("id"))
		c.Set("until", until)
		// ...
	},
})

leaderboardd serves the leaderboard's routes this way: listing boards and entries, deleting and hiding an account's entries and resetting a board (see leaderboard/selfhost).

The Server authenticates the request, checks the CSRF token and the permission, runs the handler and writes the audit record with the handler's subject and details and the status it answered; AuditReads audits a GET route too, for reads of personal data. A daemon passes its routes to admin.Listen in ListenOptions.Routes. A handler that authorizes requests itself, such as gameserver.Inspector, mounts with Server.Mount; admin.Require(authorizer, w, r, permission) is the same check for any handler, and *admin.Server is the Authorizer it takes. With a *admin.Server, Require records the refusals a route records; a mounted handler that changes state writes the audit record of each call it makes itself:

insp := gameserver.NewOperatorInspector(srv) // server.read; server.pprof for profiles
insp.Pprof = true
_ = srv.Mount("/admin/v1/runtime", insp)
_ = srv.Mount("/admin/v1/pprof/", insp)
Editar esta página