server: auth schema, keys, sessions, connection registry (#17)

This commit is contained in:
2026-11-14 22:13:04 +01:00
parent c89c8eab42
commit e612db5826
11 changed files with 915 additions and 13 deletions
+175
View File
@@ -0,0 +1,175 @@
## Players, player keys and sessions (DESIGN 3.2, 4.4, 8; issue #17).
## DDL is migration step 2 in db.nim. Choices recorded FIXED (owner-delegated, #17) in DESIGN 3.2:
## player(id, name NULL until first sign-in, role gm|player, colour, created_at);
## player_key(player_id PK FK, secret plaintext, created_at) - one current key, replace overwrites;
## session(id, player_id FK, token_hash UNIQUE, created_at, last_seen) - never expires;
## exactly one GM (partial unique index); max 6 non-GM players, unused keys count.
## Keys are plaintext so the GM can re-show them (Q11); sessions store only SHA-256(token).
## This module does no locking: the caller serializes access to the one DbConn (4.3).
import std/[options, strutils, times]
import db_connector/db_sqlite
import crypto
type
PlayerRole* = enum
prGm = "gm"
prPlayer = "player"
Player* = object
id*: int
name*: Option[string] ## none = NULL (never signed in, so no display name yet)
role*: PlayerRole
colour*: string
KeyCreated* = object
key*: string
created*: bool
rotated*: bool
const
MaxPlayers* = 6
## Non-GM players; unused keys count toward the cap (DESIGN 3.2).
GmName* = "GM"
PlayerColours* = ["#3b82f6", "#10b981", "#f59e0b", "#ef4444", "#8b5cf6", "#06b6d4"]
GmColour* = "#6b7280"
proc nowStamp(): string =
now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")
proc rowToPlayer(row: Row): Player =
Player(id: parseInt(row[0]),
name: if row[1].len == 0: none(string) else: some(row[1]),
role: parseEnum[PlayerRole](row[2]),
colour: row[3])
proc gmPlayer*(db: DbConn): Option[Player] =
for row in db.getAllRows(sql"SELECT id, name, role, colour FROM player WHERE role = 'gm'"):
return some(rowToPlayer(row))
proc playerById*(db: DbConn, id: int): Option[Player] =
for row in db.getAllRows(sql"SELECT id, name, role, colour FROM player WHERE id = ?", id):
return some(rowToPlayer(row))
proc playerCount*(db: DbConn): int =
## Non-GM players, named or not (unused keys count toward the 6-player cap).
parseInt(db.getValue(sql"SELECT count(*) FROM player WHERE role = 'player'"))
proc keyOf*(db: DbConn, playerId: int): Option[string] =
let s = db.getValue(sql"SELECT secret FROM player_key WHERE player_id = ?", playerId)
if s.len == 0: none(string) else: some(s)
proc insertKey(db: DbConn, playerId: int, key: string) =
db.exec(sql"INSERT INTO player_key (player_id, secret, created_at) VALUES (?, ?, ?)",
playerId, key, nowStamp())
proc ensureGm*(db: DbConn, rotate = false): KeyCreated =
## Creates the single GM (role gm, name "GM") if absent; prints the same key on re-run.
## rotate = true: new key, all GM sessions revoked. Caller guarantees no server holds the lock.
let gm = gmPlayer(db)
if gm.isSome:
let id = gm.get.id
if rotate:
let key = generatePlayerKey()
db.exec(sql"BEGIN")
try:
db.exec(sql"UPDATE player_key SET secret = ?, created_at = ? WHERE player_id = ?",
key, nowStamp(), id)
db.exec(sql"DELETE FROM session WHERE player_id = ?", id)
db.exec(sql"COMMIT")
except CatchableError:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard
raise
return KeyCreated(key: key, rotated: true)
let existing = keyOf(db, id)
if existing.isSome:
return KeyCreated(key: existing.get)
# Degraded DB (key row missing): heal it rather than print nothing.
let key = generatePlayerKey()
insertKey(db, id, key)
return KeyCreated(key: key, created: true)
let key = generatePlayerKey()
db.exec(sql"BEGIN")
try:
let id = int(insertID(db,
sql"INSERT INTO player (name, role, colour, created_at) VALUES (?, 'gm', ?, ?)",
GmName, GmColour, nowStamp()))
insertKey(db, id, key)
db.exec(sql"COMMIT")
result = KeyCreated(key: key, created: true)
except CatchableError:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard
raise
proc createPlayerWithKey*(db: DbConn): tuple[id: int, key: string] =
## key.create: no name at creation (the player types it at first sign-in, DESIGN 3.2).
let colour = PlayerColours[playerCount(db) mod PlayerColours.len]
let key = generatePlayerKey()
db.exec(sql"BEGIN")
try:
let id = int(insertID(db,
sql"INSERT INTO player (name, role, colour, created_at) VALUES (NULL, 'player', ?, ?)",
colour, nowStamp()))
insertKey(db, id, key)
db.exec(sql"COMMIT")
result = (id: id, key: key)
except CatchableError:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard
raise
proc findPlayerByKey*(db: DbConn, input: string): Option[Player] =
## Every row is compared without an early exit; comparison ignores case, dashes and spaces.
let wanted = normalizeKey(input)
if wanted.len == 0: return none(Player)
var found: Option[Player]
for row in db.getAllRows(sql"""
SELECT p.id, p.name, p.role, p.colour, k.secret
FROM player p JOIN player_key k ON k.player_id = p.id ORDER BY p.id"""):
if constantTimeEqual(normalizeKey(row[4]), wanted):
found = some(rowToPlayer(row))
found
proc replacePlayerKey*(db: DbConn, playerId: int): Option[string] =
## key.replace: new secret, all sessions of that player revoked. The GM's own key never rotates
## here (CLI only, DESIGN 3.2) - the caller refuses before calling.
let player = playerById(db, playerId)
if player.isNone or player.get.role == prGm: return none(string)
let key = generatePlayerKey()
db.exec(sql"BEGIN")
try:
db.exec(sql"UPDATE player_key SET secret = ?, created_at = ? WHERE player_id = ?",
key, nowStamp(), playerId)
db.exec(sql"DELETE FROM session WHERE player_id = ?", playerId)
db.exec(sql"COMMIT")
except CatchableError:
try: db.exec(sql"ROLLBACK")
except CatchableError: discard
raise
some(key)
proc removePlayer*(db: DbConn, playerId: int): bool =
## player.remove: key and sessions go with the player (ON DELETE CASCADE). Characters and
## controlled tokens are the GM's from slice 8 on; those tables do not exist in slice 2.
db.execAffectedRows(sql"DELETE FROM player WHERE id = ? AND role = 'player'", playerId) > 0
proc createSession*(db: DbConn, playerId: int, tokenHash: string) =
let stamp = nowStamp()
db.exec(sql"INSERT INTO session (player_id, token_hash, created_at, last_seen) VALUES (?, ?, ?, ?)",
playerId, tokenHash, stamp, stamp)
proc sessionPlayer*(db: DbConn, tokenHash: string): Option[Player] =
if tokenHash.len == 0: return none(Player)
for row in db.getAllRows(sql"""
SELECT p.id, p.name, p.role, p.colour
FROM session s JOIN player p ON p.id = s.player_id
WHERE s.token_hash = ? ORDER BY s.id""", tokenHash):
return some(rowToPlayer(row))
proc revokeSessions*(db: DbConn, playerId: int) =
db.exec(sql"DELETE FROM session WHERE player_id = ?", playerId)
proc sessionCount*(db: DbConn, playerId: int): int =
parseInt(db.getValue(sql"SELECT count(*) FROM session WHERE player_id = ?", playerId))
+105
View File
@@ -0,0 +1,105 @@
## Live WebSocket connection registry (DESIGN 4.3, 6.5; issue #17).
## Caps FIXED (owner-delegated, #15): 4 connections per player (a 5th evicts that player's oldest),
## 16 total (the 17th is refused before the upgrade). Connections are kept in activation order, which
## is the eviction order. Keyed by an app connId, not by WebSocket fields (H19).
## One lock, held only for these O(16) list operations. The caller closes the tickets returned.
import std/[locks, options]
import mummy
import auth
type
Conn* = object
id*: int
playerId*: int
role*: PlayerRole
ws*: WebSocket
Conns* = ref object
lock: Lock
nextId: int
pending: int ## upgrades in flight, reserved against the total cap
maxPerPlayer: int
maxTotal: int
active: seq[Conn] ## activation order; active[0] is the oldest of the whole server
Activation* = object
id*: int
evictedId*: Option[int]
evicted*: Option[WebSocket]
const
MaxConnsPerPlayer* = 4
MaxConnsTotal* = 16
proc newConns*(maxPerPlayer = MaxConnsPerPlayer, maxTotal = MaxConnsTotal): Conns =
result = Conns(maxPerPlayer: maxPerPlayer, maxTotal: maxTotal)
initLock(result.lock)
proc reserve*(c: Conns): bool =
## Before the upgrade: false means the 17th connection - answer HTTP 503, no upgrade.
withLock c.lock:
result = c.active.len + c.pending < c.maxTotal
if result: inc c.pending
proc cancelReserve*(c: Conns) =
withLock c.lock:
if c.pending > 0: dec c.pending
proc playerConnIndices(c: Conns, playerId: int): seq[int] =
for i, conn in c.active:
if conn.playerId == playerId: result.add i
proc activate*(c: Conns, playerId: int, role: PlayerRole, ws: WebSocket): Activation =
## After a successful upgrade. A 5th connection of one player evicts that player's oldest.
withLock c.lock:
if c.pending > 0: dec c.pending
let mine = c.playerConnIndices(playerId)
if mine.len >= c.maxPerPlayer:
let oldest = mine[0]
result.evictedId = some(c.active[oldest].id)
result.evicted = some(c.active[oldest].ws)
c.active.delete(oldest)
inc c.nextId
result.id = c.nextId
c.active.add Conn(id: c.nextId, playerId: playerId, role: role, ws: ws)
proc remove*(c: Conns, connId: int) =
withLock c.lock:
for i, conn in c.active:
if conn.id == connId:
c.active.delete(i)
return
proc connById*(c: Conns, connId: int): Option[Conn] =
withLock c.lock:
for conn in c.active:
if conn.id == connId: return some(conn)
proc connForWs*(c: Conns, ws: WebSocket): Option[Conn] =
## Mummy hands the same WebSocket value back on MessageEvent/CloseEvent (H19 layout check).
withLock c.lock:
for conn in c.active:
if conn.ws == ws: return some(conn)
proc revokePlayer*(c: Conns, playerId: int): seq[WebSocket] =
## key.replace / player.remove / GM key rotation: every live connection of that player.
withLock c.lock:
var i = 0
while i < c.active.len:
if c.active[i].playerId == playerId:
result.add c.active[i].ws
c.active.delete(i)
else:
inc i
proc activeCount*(c: Conns): int =
withLock c.lock:
result = c.active.len
proc activeCountFor*(c: Conns, playerId: int): int =
withLock c.lock:
result = c.playerConnIndices(playerId).len
proc pendingCount*(c: Conns): int =
withLock c.lock:
result = c.pending
+151
View File
@@ -0,0 +1,151 @@
## Secrets and hashing for auth (DESIGN 3.2, #17): the player/GM key generator, the session token
## generator and SHA-256 for session-token hashes.
## Choices recorded FIXED (owner-delegated, #17), DESIGN 3.2/8:
## - Player key: 20 secret characters in 5 groups of 4 joined by '-', alphabet `KeyAlphabet`
## (no 0/O, 1/I/L), from the OS CSPRNG via std/sysrand (getrandom), ~99 bits.
## - Session token: 32 random bytes, hex encoded (64 chars). Only `sha256Hex(token)` is stored.
## - SHA-256 is implemented here (FIPS 180-4) because the pinned Nim stdlib has no SHA-2 and the
## project takes no crypto dependency. Known-answer tests in tests/tcrypto.nim.
import std/[strutils, sysrand]
const
KeyAlphabet* = "ABCDEFGHJKMNPQRSTUVWXYZ23456789"
## 31 symbols: A-Z without I, L, O; digits 2-9. 31^20 ~ 2^99.
KeyLength* = 20
KeyGroups* = 5
KeyGroupSize* = 4
SessionTokenBytes* = 32
const HexDigits = "0123456789abcdef"
proc toHexLower*(bytes: openArray[byte]): string =
result = newStringOfCap(bytes.len * 2)
for b in bytes:
result.add HexDigits[int(b shr 4)]
result.add HexDigits[int(b and 0x0f)]
proc bytesOf*(s: string): seq[byte] =
result = newSeq[byte](s.len)
for i, c in s: result[i] = byte(c)
const Sha256K: array[64, uint32] = [
0x428a2f98'u32, 0x71374491'u32, 0xb5c0fbcf'u32, 0xe9b5dba5'u32,
0x3956c25b'u32, 0x59f111f1'u32, 0x923f82a4'u32, 0xab1c5ed5'u32,
0xd807aa98'u32, 0x12835b01'u32, 0x243185be'u32, 0x550c7dc3'u32,
0x72be5d74'u32, 0x80deb1fe'u32, 0x9bdc06a7'u32, 0xc19bf174'u32,
0xe49b69c1'u32, 0xefbe4786'u32, 0x0fc19dc6'u32, 0x240ca1cc'u32,
0x2de92c6f'u32, 0x4a7484aa'u32, 0x5cb0a9dc'u32, 0x76f988da'u32,
0x983e5152'u32, 0xa831c66d'u32, 0xb00327c8'u32, 0xbf597fc7'u32,
0xc6e00bf3'u32, 0xd5a79147'u32, 0x06ca6351'u32, 0x14292967'u32,
0x27b70a85'u32, 0x2e1b2138'u32, 0x4d2c6dfc'u32, 0x53380d13'u32,
0x650a7354'u32, 0x766a0abb'u32, 0x81c2c92e'u32, 0x92722c85'u32,
0xa2bfe8a1'u32, 0xa81a664b'u32, 0xc24b8b70'u32, 0xc76c51a3'u32,
0xd192e819'u32, 0xd6990624'u32, 0xf40e3585'u32, 0x106aa070'u32,
0x19a4c116'u32, 0x1e376c08'u32, 0x2748774c'u32, 0x34b0bcb5'u32,
0x391c0cb3'u32, 0x4ed8aa4a'u32, 0x5b9cca4f'u32, 0x682e6ff3'u32,
0x748f82ee'u32, 0x78a5636f'u32, 0x84c87814'u32, 0x8cc70208'u32,
0x90befffa'u32, 0xa4506ceb'u32, 0xbef9a3f7'u32, 0xc67178f2'u32]
proc rotr(x: uint32, n: int): uint32 {.inline.} =
(x shr n) or (x shl (32 - n))
proc sha256*(data: openArray[byte]): array[32, byte] =
var h: array[8, uint32] = [
0x6a09e667'u32, 0xbb67ae85'u32, 0x3c6ef372'u32, 0xa54ff53a'u32,
0x510e527f'u32, 0x9b05688c'u32, 0x1f83d9ab'u32, 0x5be0cd19'u32]
var msg = newSeq[byte](data.len + 1)
for i, b in data: msg[i] = b
msg[data.len] = 0x80'u8
let bitLen = uint64(data.len) * 8'u64
while msg.len mod 64 != 56: msg.add 0'u8
for shift in countdown(7, 0):
msg.add byte((bitLen shr uint64(shift * 8)) and 0xff'u64)
var w: array[64, uint32]
var offset = 0
while offset < msg.len:
for j in 0 ..< 16:
let k = offset + j * 4
w[j] = (uint32(msg[k]) shl 24) or (uint32(msg[k + 1]) shl 16) or
(uint32(msg[k + 2]) shl 8) or uint32(msg[k + 3])
for j in 16 ..< 64:
let s0 = rotr(w[j - 15], 7) xor rotr(w[j - 15], 18) xor (w[j - 15] shr 3)
let s1 = rotr(w[j - 2], 17) xor rotr(w[j - 2], 19) xor (w[j - 2] shr 10)
w[j] = w[j - 16] + s0 + w[j - 7] + s1
var a = h[0]
var b = h[1]
var c = h[2]
var d = h[3]
var e = h[4]
var f = h[5]
var g = h[6]
var hh = h[7]
for j in 0 ..< 64:
let s1 = rotr(e, 6) xor rotr(e, 11) xor rotr(e, 25)
let ch = (e and f) xor ((not e) and g)
let t1 = hh + s1 + ch + Sha256K[j] + w[j]
let s0 = rotr(a, 2) xor rotr(a, 13) xor rotr(a, 22)
let maj = (a and b) xor (a and c) xor (b and c)
let t2 = s0 + maj
hh = g; g = f; f = e; e = d + t1
d = c; c = b; b = a; a = t1 + t2
h[0] = h[0] + a; h[1] = h[1] + b; h[2] = h[2] + c; h[3] = h[3] + d
h[4] = h[4] + e; h[5] = h[5] + f; h[6] = h[6] + g; h[7] = h[7] + hh
offset += 64
for j in 0 ..< 8:
result[j * 4] = byte(h[j] shr 24)
result[j * 4 + 1] = byte((h[j] shr 16) and 0xff)
result[j * 4 + 2] = byte((h[j] shr 8) and 0xff)
result[j * 4 + 3] = byte(h[j] and 0xff)
proc sha256Hex*(data: openArray[byte]): string =
toHexLower(sha256(data))
proc sha256Hex*(s: string): string =
sha256Hex(bytesOf(s))
proc randomBytes*(n: int): seq[byte] =
## OS CSPRNG (std/sysrand: getrandom(2) on Linux). Raises OSError if unavailable.
urandom(n)
proc randomHexToken*(bytes = SessionTokenBytes): string =
toHexLower(randomBytes(bytes))
proc randomSessionToken*(): string =
randomHexToken(SessionTokenBytes)
proc formatPlayerKey*(raw: string): string =
## "abcd...20 chars" -> "ABCD-EFGH-..." (5 groups of 4). Input is the 20 raw symbols.
doAssert raw.len == KeyLength
result = ""
for i in 0 ..< KeyGroups:
if i > 0: result.add '-'
result.add raw[i * KeyGroupSize ..< (i + 1) * KeyGroupSize].toUpperAscii
proc generatePlayerKey*(): string =
## 20 symbols from KeyAlphabet, uniform (rejection sampling: 31*8 = 248 < 256).
var raw = newStringOfCap(KeyLength)
while raw.len < KeyLength:
for b in randomBytes(32):
if raw.len == KeyLength: break
if int(b) >= KeyAlphabet.len * 8: continue
raw.add KeyAlphabet[int(b) mod KeyAlphabet.len]
formatPlayerKey(raw)
proc normalizeKey*(input: string): string =
## Key comparison ignores case, dashes and spaces (DESIGN 6.6).
result = newStringOfCap(input.len)
for c in input:
if c in {'-', ' ', '\t', '\r', '\n'}: continue
result.add c.toLowerAscii
proc constantTimeEqual*(a, b: string): bool =
## Length-independent comparison for secrets: never exits on the first difference.
var diff = a.len xor b.len
let n = max(a.len, b.len)
for i in 0 ..< n:
let ca = if i < a.len: uint8(a[i]) else: 0'u8
let cb = if i < b.len: uint8(b[i]) else: 0'u8
diff = diff or int(ca xor cb)
diff == 0
+29 -4
View File
@@ -18,7 +18,9 @@ type
Migration* = object
version*: int
name*: string
sql*: string
stmts*: seq[string]
## One or more DDL statements, run in order inside the step's transaction.
## db_connector's exec() prepares a single statement, so they cannot be one string.
MigrationRow* = tuple[version: int, name: string]
const
@@ -29,11 +31,33 @@ CREATE TABLE IF NOT EXISTS schema_migration (
applied_at TEXT NOT NULL
)"""
migrations* = [
Migration(version: 1, name: "meta", sql: """
Migration(version: 1, name: "meta", stmts: @["""
CREATE TABLE meta (
k TEXT PRIMARY KEY,
v TEXT NOT NULL
)"""),
)"""]),
Migration(version: 2, name: "auth", stmts: @["""
CREATE TABLE player (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE, -- NULL until first sign-in; unique among players
role TEXT NOT NULL CHECK (role IN ('gm', 'player')),
colour TEXT NOT NULL,
created_at TEXT NOT NULL
)""", """
CREATE UNIQUE INDEX player_single_gm ON player(role) WHERE role = 'gm'""", """
CREATE TABLE player_key (
player_id INTEGER PRIMARY KEY REFERENCES player(id) ON DELETE CASCADE,
secret TEXT NOT NULL, -- plaintext: the GM can re-show it (Q11)
created_at TEXT NOT NULL
)""", """
CREATE TABLE session (
id INTEGER PRIMARY KEY,
player_id INTEGER NOT NULL REFERENCES player(id) ON DELETE CASCADE,
token_hash TEXT NOT NULL UNIQUE, -- SHA-256 of the cookie token; the token is never stored
created_at TEXT NOT NULL,
last_seen TEXT NOT NULL
)""", """
CREATE INDEX session_player ON session(player_id)"""]),
]
LatestVersion* = migrations[^1].version
## Derived, so adding a step cannot leave it stale.
@@ -77,7 +101,8 @@ proc migrate*(db: DbConn): int =
if m.version <= version: continue
db.exec(sql"BEGIN")
try:
db.exec(sql(m.sql))
for stmt in m.stmts:
db.exec(sql(stmt))
let stamp = now().utc.format("yyyy-MM-dd'T'HH:mm:ss'Z'")
db.exec(sql"INSERT INTO schema_migration (version, name, applied_at) VALUES (?, ?, ?)",
m.version, m.name, stamp)
+42
View File
@@ -0,0 +1,42 @@
## Data-dir lock (DESIGN 3.2 / 11.1, #17): the running server holds an exclusive advisory lock on
## `<stateDir>/instance.lock`; `fff-vtt gm-key --new` must not rotate under a live server.
## POSIX fcntl(F_SETLK) write lock: process-scoped, released when the fd is closed or the process exits.
import std/[os, posix]
const InstanceLockName* = "instance.lock"
type
InstanceLock* = object
path*: string
fd*: cint
held*: bool
proc tryAcquire*(stateDir: string): InstanceLock =
result.path = stateDir / InstanceLockName
let fd = open(result.path.cstring, O_RDWR or O_CREAT, Mode(0o600))
if fd < 0: return
var fl: Tflock
fl.l_type = cshort(F_WRLCK)
fl.l_whence = cshort(SEEK_SET)
fl.l_start = 0
fl.l_len = 0
if fcntl(fd, F_SETLK, addr fl) == 0:
result.fd = fd
result.held = true
# Record the holder for humans; the lock, not the content, is the protocol.
discard ftruncate(fd, 0)
let pid = $getCurrentProcessId() & "\n"
discard posix.write(fd, pid.cstring, pid.len)
else:
discard posix.close(fd)
proc release*(l: var InstanceLock) =
if l.held:
var fl: Tflock
fl.l_type = cshort(F_UNLCK)
fl.l_whence = cshort(SEEK_SET)
fl.l_start = 0
fl.l_len = 0
discard fcntl(l.fd, F_SETLK, addr fl)
discard posix.close(l.fd)
l.held = false