Rename to Questward and integrate auth.timfalken.com login.
OAuth sign-in replaces stub-only access in production, the first account becomes game admin, and editors manage admins from world settings; deploy and docs follow the Questward naming.
@@ -1,6 +1,6 @@
1
# Tile MMO
1
# Questward
2
2
3
Authoritative Node.js tile MMO with a FrameworkV3 web client. Architecture lives in `tile_mmo_server_technical_design_v0.6.md`. Implementation status lives in `docs/FEATURES.md`.
3
Authoritative Node.js tile MMO with a FrameworkV3 web client. Architecture lives in `questward_server_technical_design_v0.6.md`. Implementation status lives in `docs/FEATURES.md`.
4
4
5
5
## Layout
6
6
@@ -22,6 +22,18 @@ npm start
22
22
23
23
Open [http://localhost:8080](http://localhost:8080) to play and [http://localhost:8080/editor](http://localhost:8080/editor) for the world editor.
24
24
25
Until auth.timfalken.com exists, each browser connection is a stub admin (`admin-1`, `admin-2`, …). A fresh world is infinite closed grass: open chunk `0,0` in the editor, save, then **Apply now** before a character can walk.
25
Sign in via [auth.timfalken.com](https://auth.timfalken.com) (OAuth). Without `QUESTWARD_AUTH_CLIENT_SECRET`, local dev uses stub admins (`admin-1`, …). A fresh world is infinite closed grass: open chunk `0,0` in the [world editor](http://localhost:8080/editor), save, then **Apply now** before a character can walk.
26
27
### Auth env (production)
28
29
| Variable | Purpose |
30
|----------|---------|
31
| `QUESTWARD_AUTH_CLIENT_SECRET` | OAuth client secret from auth.timfalken.com `/admin` |
32
| `QUESTWARD_AUTH_CLIENT_ID` | Registered domain (default `timfalken.com`) |
33
| `QUESTWARD_AUTH_REDIRECT_URI` | Callback URL (default: `{public-origin}/auth/callback`) |
34
| `QUESTWARD_AUTH_URL` | Auth base URL (default `https://auth.timfalken.com`) |
35
| `QUESTWARD_AUTH_STUB=1` | Force stub auth |
36
37
Register `questward.timfalken.com` (or your host) with callback path `/auth/callback` in the auth admin panel.
26
38
27
39
The player-driven **Central Exchange** marketplace is live (hidden order book, escrow, midpoint matching, pigeon settlement). Place a Central Exchange counter in the editor next to a bank.
@@ -1,6 +1,6 @@1
# Tile MMO
1
# Questward
2
2
3
Authoritative Node.js tile MMO with a FrameworkV3 web client. Architecture lives in `tile_mmo_server_technical_design_v0.6.md`. Implementation status lives in `docs/FEATURES.md`.
3
Authoritative Node.js tile MMO with a FrameworkV3 web client. Architecture lives in `questward_server_technical_design_v0.6.md`. Implementation status lives in `docs/FEATURES.md`.
4
4
5
## Layout
5
## Layout
6
6
@@ -22,6 +22,18 @@ npm start22
22
23
Open [http://localhost:8080](http://localhost:8080) to play and [http://localhost:8080/editor](http://localhost:8080/editor) for the world editor.
23
Open [http://localhost:8080](http://localhost:8080) to play and [http://localhost:8080/editor](http://localhost:8080/editor) for the world editor.
24
24
25
Until auth.timfalken.com exists, each browser connection is a stub admin (`admin-1`, `admin-2`, …). A fresh world is infinite closed grass: open chunk `0,0` in the editor, save, then **Apply now** before a character can walk.
25
Sign in via [auth.timfalken.com](https://auth.timfalken.com) (OAuth). Without `QUESTWARD_AUTH_CLIENT_SECRET`, local dev uses stub admins (`admin-1`, …). A fresh world is infinite closed grass: open chunk `0,0` in the [world editor](http://localhost:8080/editor), save, then **Apply now** before a character can walk.
26
27
### Auth env (production)
28
29
| Variable | Purpose |
30
|----------|---------|
31
| `QUESTWARD_AUTH_CLIENT_SECRET` | OAuth client secret from auth.timfalken.com `/admin` |
32
| `QUESTWARD_AUTH_CLIENT_ID` | Registered domain (default `timfalken.com`) |
33
| `QUESTWARD_AUTH_REDIRECT_URI` | Callback URL (default: `{public-origin}/auth/callback`) |
34
| `QUESTWARD_AUTH_URL` | Auth base URL (default `https://auth.timfalken.com`) |
35
| `QUESTWARD_AUTH_STUB=1` | Force stub auth |
36
37
Register `questward.timfalken.com` (or your host) with callback path `/auth/callback` in the auth admin panel.
26
38
27
The player-driven **Central Exchange** marketplace is live (hidden order book, escrow, midpoint matching, pigeon settlement). Place a Central Exchange counter in the editor next to a bank.
39
The player-driven **Central Exchange** marketplace is live (hidden order book, escrow, midpoint matching, pigeon settlement). Place a Central Exchange counter in the editor next to a bank.
@@ -2,13 +2,17 @@
2
2
<html lang="en">
3
3
<head>
4
4
<meta charset="utf-8">
5
<title>World editor</title>
5
<title>Questward — World editor</title>
6
6
<link rel="stylesheet" href="/ui/editor.css">
7
7
</head>
8
8
<body>
9
9
<header>
10
<h1>World editor</h1>
10
<h1>Questward — World editor</h1>
11
11
<p id="who">Connecting…</p>
12
<p id="auth-actions" class="auth-actions">
13
<a id="auth-sign-in" href="/auth/login" hidden>Sign in</a>
14
<a id="auth-sign-out" href="/auth/logout" hidden>Sign out</a>
15
</p>
12
16
<p id="error" class="error"></p>
13
17
</header>
14
18
<aside>
@@ -2,13 +2,17 @@2
<html lang="en">2
<html lang="en">3
<head>3
<head>4
<meta charset="utf-8">4
<meta charset="utf-8">5
<title>World editor</title>5
<title>Questward — World editor</title>6
<link rel="stylesheet" href="/ui/editor.css">6
<link rel="stylesheet" href="/ui/editor.css">7
</head>7
</head>8
<body>8
<body>9
<header>9
<header>10
<h1>World editor</h1>10
<h1>Questward — World editor</h1>11
<p id="who">Connecting…</p>11
<p id="who">Connecting…</p>12
<p id="auth-actions" class="auth-actions">13
<a id="auth-sign-in" href="/auth/login" hidden>Sign in</a>14
<a id="auth-sign-out" href="/auth/logout" hidden>Sign out</a>15
</p>12
<p id="error" class="error"></p>16
<p id="error" class="error"></p>13
</header>17
</header>14
<aside>18
<aside>@@ -2,7 +2,7 @@
2
2
<html lang="en">
3
3
<head>
4
4
<meta charset="utf-8">
5
<title>Tile MMO</title>
5
<title>Questward</title>
6
6
<link rel="stylesheet" href="/ui/play.css">
7
7
</head>
8
8
<body>
@@ -525,8 +525,13 @@
525
525
</div>
526
526
<div id="overlay">
527
527
<section class="panel">
528
<h1>Tile MMO</h1>
528
<h1>Questward</h1>
529
529
<p id="status">Connecting…</p>
530
<p id="auth-actions" class="auth-actions">
531
<a id="auth-sign-in" href="/auth/login" hidden>Sign in</a>
532
<a id="auth-sign-out" href="/auth/logout" hidden>Sign out</a>
533
<a id="auth-export" href="/settings/export" hidden>Export my data</a>
534
</p>
530
535
<p id="error" class="error"></p>
531
536
<div id="character-list"></div>
532
537
<button id="create-character-open" type="button">Create Character</button>
@@ -2,7 +2,7 @@2
<html lang="en">2
<html lang="en">3
<head>3
<head>4
<meta charset="utf-8">4
<meta charset="utf-8">5
<title>Tile MMO</title>5
<title>Questward</title>6
<link rel="stylesheet" href="/ui/play.css">6
<link rel="stylesheet" href="/ui/play.css">7
</head>7
</head>8
<body>8
<body>@@ -525,8 +525,13 @@525
</div>525
</div>526
<div id="overlay">526
<div id="overlay">527
<section class="panel">527
<section class="panel">528
<h1>Tile MMO</h1>528
<h1>Questward</h1>529
<p id="status">Connecting…</p>529
<p id="status">Connecting…</p>530
<p id="auth-actions" class="auth-actions">531
<a id="auth-sign-in" href="/auth/login" hidden>Sign in</a>532
<a id="auth-sign-out" href="/auth/logout" hidden>Sign out</a>533
<a id="auth-export" href="/settings/export" hidden>Export my data</a>534
</p>530
<p id="error" class="error"></p>535
<p id="error" class="error"></p>531
<div id="character-list"></div>536
<div id="character-list"></div>532
<button id="create-character-open" type="button">Create Character</button>537
<button id="create-character-open" type="button">Create Character</button>@@ -1,31 +1,35 @@
1
1
import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2
import {
3
GROUND_DEFINITIONS,
4
BLOCK_DEFINITIONS,
5
GroundType,
6
BlockType,
7
normalizeGround,
8
normalizeBlock,
9
listPlaceableBlockPaletteEntries
10
} from "/shared/definitions/tiles.js";
2
import
3
{
4
GROUND_DEFINITIONS,
5
BLOCK_DEFINITIONS,
6
GroundType,
7
BlockType,
8
normalizeGround,
9
normalizeBlock,
10
listPlaceableBlockPaletteEntries
11
} from "/shared/definitions/tiles.js";
11
12
import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
12
import {
13
SeasonId,
14
seasonIdAt,
15
seasonalCycleStates,
16
seasonIdFromVisualState,
17
placeableStatesForType
18
} from "/shared/world/season.js";
13
import
14
{
15
SeasonId,
16
seasonIdAt,
17
seasonalCycleStates,
18
seasonIdFromVisualState,
19
placeableStatesForType
20
} from "/shared/world/season.js";
19
21
import { loadGraphicsSettings } from "/shared/graphics/settings.js";
20
22
import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
21
23
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
22
import {
23
computeNeighborConnectMask,
24
composeNeighborConnectState,
25
definitionUsesNeighborConnect,
26
neighborConnectBlocksMatch
27
} from "/shared/world/neighborConnect.js";
24
import
25
{
26
computeNeighborConnectMask,
27
composeNeighborConnectState,
28
definitionUsesNeighborConnect,
29
neighborConnectBlocksMatch
30
} from "/shared/world/neighborConnect.js";
28
31
import { GameSocket, defaultSocketUrl } from "../net/socket.js";
32
import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";
29
33
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
30
34
import { WorldView } from "../render/worldView.js";
31
35
import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
@@ -34,11 +38,12 @@ import { initTileConfigModal } from "./tileConfigModal.js";
34
38
import { initQuestsModal } from "./questsModal.js";
35
39
import { initDialoguesModal } from "./dialoguesModal.js";
36
40
import { createDimensionCombobox } from "./dimensionCombobox.js";
37
import {
38
OVERWORLD_ID,
39
normalizeDimensionId,
40
isOverworld
41
} from "/shared/world/dimensions.js";
41
import
42
{
43
OVERWORLD_ID,
44
normalizeDimensionId,
45
isOverworld
46
} from "/shared/world/dimensions.js";
42
47
43
48
const game = new Game();
44
49
let socket;
@@ -73,6 +78,8 @@ let editorZoom = null;
73
78
let activeRevisionId = null;
74
79
let pendingRevisionId = null;
75
80
let applyInFlight = false;
81
/** @type {string|null} */
82
let sessionAuthSubject = null;
76
83
const EDITOR_ZOOM_MIN = 0.25;
77
84
const EDITOR_ZOOM_MAX = 8;
78
85
const EDITOR_ZOOM_STEP = 1.12;
@@ -854,6 +861,26 @@ function updateTooltip (local, options = {})
854
861
855
862
async function main ()
856
863
{
864
const authStatus = await fetchAuthStatus();
865
const signIn = document.getElementById("auth-sign-in");
866
const signOut = document.getElementById("auth-sign-out");
867
if (signIn)
868
{
869
signIn.hidden = !!authStatus?.authenticated;
870
signIn.href = loginUrl("/editor");
871
}
872
if (signOut)
873
{
874
signOut.hidden = !authStatus?.authenticated;
875
signOut.href = logoutUrl("/editor");
876
}
877
if (!authStatus.authenticated)
878
{
879
$("who").textContent = "Sign in required";
880
$("error").textContent = "Sign in with your Tim Falken account to use the world editor.";
881
return;
882
}
883
857
884
catalog = await loadSpriteCatalog();
858
885
imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
859
886
await preloadCatalogImages(game, catalog);
@@ -1011,13 +1038,23 @@ async function main ()
1011
1038
{
1012
1039
if (message.type === MessageType.session)
1013
1040
{
1014
$("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
1041
sessionAuthSubject = message.authSubject ?? null;
1042
const label = message.username ?? message.authSubject ?? "Unknown";
1043
$("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;
1044
if (!message.isAdmin)
1045
{
1046
$("error").textContent = "Admin access required.";
1047
return;
1048
}
1049
$("error").textContent = "";
1015
1050
socket.send({ type: MessageType.editorLoadSettings });
1051
socket.send({ type: MessageType.editorLoadGameAdmins });
1016
1052
socket.send({ type: MessageType.editorConsoleSubscribe });
1017
1053
requestDimensions();
1018
1054
loadNeighborhood(0, 0);
1019
1055
}
1020
else if (message.type === MessageType.editorSettings)
1056
else if (message.type === MessageType.editorSettings
1057
|| message.type === MessageType.editorGameAdmins)
1021
1058
{ settingsModal.handleMessage(message); }
1022
1059
else if (message.type === MessageType.editorConsoleSnapshot)
1023
1060
{ applyConsoleSnapshot(message.lines); }
@@ -1083,6 +1120,7 @@ async function main ()
1083
1120
settingsModal = initSettingsModal({
1084
1121
socket,
1085
1122
MessageType,
1123
getAuthSubject: () => sessionAuthSubject,
1086
1124
onApplied (settings)
1087
1125
{
1088
1126
view.setSettings(settings);
@@ -1,31 +1,35 @@1
import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";1
import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";2
import {2
import3
GROUND_DEFINITIONS,3
{4
BLOCK_DEFINITIONS,4
GROUND_DEFINITIONS,5
GroundType,5
BLOCK_DEFINITIONS,6
BlockType,6
GroundType,7
normalizeGround,7
BlockType,8
normalizeBlock,8
normalizeGround,9
listPlaceableBlockPaletteEntries9
normalizeBlock,10
} from "/shared/definitions/tiles.js";10
listPlaceableBlockPaletteEntries11
} from "/shared/definitions/tiles.js";11
import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";12
import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";12
import {13
import13
SeasonId,14
{14
seasonIdAt,15
SeasonId,15
seasonalCycleStates,16
seasonIdAt,16
seasonIdFromVisualState,17
seasonalCycleStates,17
placeableStatesForType18
seasonIdFromVisualState,18
} from "/shared/world/season.js";19
placeableStatesForType20
} from "/shared/world/season.js";19
import { loadGraphicsSettings } from "/shared/graphics/settings.js";21
import { loadGraphicsSettings } from "/shared/graphics/settings.js";20
import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";22
import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";21
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";23
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";22
import {24
import23
computeNeighborConnectMask,25
{24
composeNeighborConnectState,26
computeNeighborConnectMask,25
definitionUsesNeighborConnect,27
composeNeighborConnectState,26
neighborConnectBlocksMatch28
definitionUsesNeighborConnect,27
} from "/shared/world/neighborConnect.js";29
neighborConnectBlocksMatch30
} from "/shared/world/neighborConnect.js";28
import { GameSocket, defaultSocketUrl } from "../net/socket.js";31
import { GameSocket, defaultSocketUrl } from "../net/socket.js";32
import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";29
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";33
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";30
import { WorldView } from "../render/worldView.js";34
import { WorldView } from "../render/worldView.js";31
import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";35
import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";@@ -34,11 +38,12 @@ import { initTileConfigModal } from "./tileConfigModal.js";34
import { initQuestsModal } from "./questsModal.js";38
import { initQuestsModal } from "./questsModal.js";35
import { initDialoguesModal } from "./dialoguesModal.js";39
import { initDialoguesModal } from "./dialoguesModal.js";36
import { createDimensionCombobox } from "./dimensionCombobox.js";40
import { createDimensionCombobox } from "./dimensionCombobox.js";37
import {41
import38
OVERWORLD_ID,42
{39
normalizeDimensionId,43
OVERWORLD_ID,40
isOverworld44
normalizeDimensionId,41
} from "/shared/world/dimensions.js";45
isOverworld46
} from "/shared/world/dimensions.js";42
47
43
const game = new Game();48
const game = new Game();44
let socket;49
let socket;@@ -73,6 +78,8 @@ let editorZoom = null;73
let activeRevisionId = null;78
let activeRevisionId = null;74
let pendingRevisionId = null;79
let pendingRevisionId = null;75
let applyInFlight = false;80
let applyInFlight = false;81
/** @type {string|null} */82
let sessionAuthSubject = null;76
const EDITOR_ZOOM_MIN = 0.25;83
const EDITOR_ZOOM_MIN = 0.25;77
const EDITOR_ZOOM_MAX = 8;84
const EDITOR_ZOOM_MAX = 8;78
const EDITOR_ZOOM_STEP = 1.12;85
const EDITOR_ZOOM_STEP = 1.12;@@ -854,6 +861,26 @@ function updateTooltip (local, options = {})854
861
855
async function main ()862
async function main ()856
{863
{864
const authStatus = await fetchAuthStatus();865
const signIn = document.getElementById("auth-sign-in");866
const signOut = document.getElementById("auth-sign-out");867
if (signIn)868
{869
signIn.hidden = !!authStatus?.authenticated;870
signIn.href = loginUrl("/editor");871
}872
if (signOut)873
{874
signOut.hidden = !authStatus?.authenticated;875
signOut.href = logoutUrl("/editor");876
}877
if (!authStatus.authenticated)878
{879
$("who").textContent = "Sign in required";880
$("error").textContent = "Sign in with your Tim Falken account to use the world editor.";881
return;882
}883
857
catalog = await loadSpriteCatalog();884
catalog = await loadSpriteCatalog();858
imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));885
imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));859
await preloadCatalogImages(game, catalog);886
await preloadCatalogImages(game, catalog);@@ -1011,13 +1038,23 @@ async function main ()1011
{1038
{1012
if (message.type === MessageType.session)1039
if (message.type === MessageType.session)1013
{1040
{1014
$("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;1041
sessionAuthSubject = message.authSubject ?? null;1042
const label = message.username ?? message.authSubject ?? "Unknown";1043
$("who").textContent = `${label}${message.isAdmin ? " · admin" : " · not admin"}`;1044
if (!message.isAdmin)1045
{1046
$("error").textContent = "Admin access required.";1047
return;1048
}1049
$("error").textContent = "";1015
socket.send({ type: MessageType.editorLoadSettings });1050
socket.send({ type: MessageType.editorLoadSettings });1051
socket.send({ type: MessageType.editorLoadGameAdmins });1016
socket.send({ type: MessageType.editorConsoleSubscribe });1052
socket.send({ type: MessageType.editorConsoleSubscribe });1017
requestDimensions();1053
requestDimensions();1018
loadNeighborhood(0, 0);1054
loadNeighborhood(0, 0);1019
}1055
}1020
else if (message.type === MessageType.editorSettings)1056
else if (message.type === MessageType.editorSettings1057
|| message.type === MessageType.editorGameAdmins)1021
{ settingsModal.handleMessage(message); }1058
{ settingsModal.handleMessage(message); }1022
else if (message.type === MessageType.editorConsoleSnapshot)1059
else if (message.type === MessageType.editorConsoleSnapshot)1023
{ applyConsoleSnapshot(message.lines); }1060
{ applyConsoleSnapshot(message.lines); }@@ -1083,6 +1120,7 @@ async function main ()1083
settingsModal = initSettingsModal({1120
settingsModal = initSettingsModal({1084
socket,1121
socket,1085
MessageType,1122
MessageType,1123
getAuthSubject: () => sessionAuthSubject,1086
onApplied (settings)1124
onApplied (settings)1087
{1125
{1088
view.setSettings(settings);1126
view.setSettings(settings);@@ -38,7 +38,7 @@ const SLOT_LABELS = Object.freeze({
38
38
offhand: "Off-hand"
39
39
});
40
40
41
export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })
41
export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight, getAuthSubject })
42
42
{
43
43
const backdrop = document.getElementById("settings-backdrop");
44
44
const modal = document.getElementById("settings-modal");
@@ -65,6 +65,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
65
65
let draftEquipmentStats = normalizeEquipmentStatBonuses(null);
66
66
let equipmentStatsPanel = null;
67
67
let equipmentStatsCategoryId = EQUIPMENT_STAT_CATEGORIES[0]?.id ?? null;
68
/** @type {{ authSubject: string, username: string|null, email: string|null }[]} */
69
let gameAdmins = [];
70
let gameAdminsPanel = null;
68
71
69
72
buildForm(form, {
70
73
getActiveCategory: () => activeCategory,
@@ -78,6 +81,11 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
78
81
{ renderStarterPanel(); }
79
82
if (id === "equipmentStats")
80
83
{ renderEquipmentStatsPanel(); }
84
if (id === "gameAdmins")
85
{
86
socket.send({ type: MessageType.editorLoadGameAdmins });
87
renderGameAdminsPanel();
88
}
81
89
},
82
90
onFieldInput (field)
83
91
{
@@ -95,6 +103,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
95
103
onEquipmentStatsPanelReady (panel)
96
104
{
97
105
equipmentStatsPanel = panel;
106
},
107
onGameAdminsPanelReady (panel)
108
{
109
gameAdminsPanel = panel;
98
110
}
99
111
});
100
112
@@ -148,6 +160,74 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
148
160
renderStarterPanel();
149
161
form.dispatchEvent(new CustomEvent("starter-changed"));
150
162
});
163
form.addEventListener("game-admin-grant", (event) =>
164
{
165
const username = String(event.detail?.username ?? "").trim();
166
if (!username)
167
{ return; }
168
socket.send({ type: MessageType.editorGrantGameAdmin, username });
169
});
170
form.addEventListener("game-admin-revoke", (event) =>
171
{
172
const authSubject = String(event.detail?.authSubject ?? "").trim();
173
if (!authSubject)
174
{ return; }
175
socket.send({
176
type: MessageType.editorRevokeGameAdmin,
177
authSubject,
178
confirmSelf: !!event.detail?.confirmSelf
179
});
180
});
181
182
function renderGameAdminsPanel ()
183
{
184
if (!gameAdminsPanel)
185
{ return; }
186
const selfSubject = getAuthSubject?.() ?? null;
187
gameAdminsPanel.list.innerHTML = "";
188
if (!gameAdmins.length)
189
{
190
const empty = document.createElement("p");
191
empty.className = "hint";
192
empty.textContent = "No game admins yet.";
193
gameAdminsPanel.list.append(empty);
194
return;
195
}
196
for (const admin of gameAdmins)
197
{
198
const row = document.createElement("div");
199
row.className = "game-admin-row";
200
const label = document.createElement("span");
201
label.textContent = admin.username ?? admin.email ?? admin.authSubject;
202
const meta = document.createElement("span");
203
meta.className = "muted small";
204
meta.textContent = admin.email && admin.username ? admin.email : admin.authSubject;
205
const remove = document.createElement("button");
206
remove.type = "button";
207
remove.textContent = "Remove admin";
208
remove.addEventListener("click", () =>
209
{
210
const isSelf = admin.authSubject === selfSubject;
211
if (isSelf)
212
{
213
const ok = window.confirm("Remove your own admin access? You will lose editor access on reconnect.");
214
if (!ok)
215
{ return; }
216
form.dispatchEvent(new CustomEvent("game-admin-revoke", {
217
detail: { authSubject: admin.authSubject, confirmSelf: true }
218
}));
219
return;
220
}
221
if (!window.confirm(`Remove admin access from ${label.textContent}?`))
222
{ return; }
223
form.dispatchEvent(new CustomEvent("game-admin-revoke", {
224
detail: { authSubject: admin.authSubject, confirmSelf: false }
225
}));
226
});
227
row.append(label, meta, remove);
228
gameAdminsPanel.list.append(row);
229
}
230
}
151
231
152
232
function show (visible)
153
233
{
@@ -174,6 +254,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
174
254
document.getElementById("open-settings").addEventListener("click", () =>
175
255
{
176
256
socket.send({ type: MessageType.editorLoadSettings });
257
socket.send({ type: MessageType.editorLoadGameAdmins });
177
258
show(true);
178
259
});
179
260
document.getElementById("settings-close").addEventListener("click", () => show(false));
@@ -638,6 +719,12 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi
638
719
isOpen: () => open,
639
720
handleMessage (message)
640
721
{
722
if (message.type === MessageType.editorGameAdmins)
723
{
724
gameAdmins = Array.isArray(message.admins) ? message.admins : [];
725
renderGameAdminsPanel();
726
return;
727
}
641
728
loaded = true;
642
729
baseline = {
643
730
...message.settings,
@@ -667,7 +754,8 @@ function buildForm (form, {
667
754
onFieldInput,
668
755
onSeedPanelReady,
669
756
onStarterPanelReady,
670
onEquipmentStatsPanelReady
757
onEquipmentStatsPanelReady,
758
onGameAdminsPanelReady
671
759
})
672
760
{
673
761
form.innerHTML = "";
@@ -722,6 +810,17 @@ function buildForm (form, {
722
810
section.append(panel.root);
723
811
onEquipmentStatsPanelReady?.(panel);
724
812
}
813
else if (category.panel === "gameAdmins")
814
{
815
const panel = buildGameAdminsPanel({
816
onGrant (username)
817
{ form.dispatchEvent(new CustomEvent("game-admin-grant", { detail: { username } })); },
818
onRevoke (authSubject, confirmSelf)
819
{ form.dispatchEvent(new CustomEvent("game-admin-revoke", { detail: { authSubject, confirmSelf } })); }
820
});
821
section.append(panel.root);
822
onGameAdminsPanelReady?.(panel);
823
}
725
824
else
726
825
{
727
826
for (const field of category.fields)
@@ -848,6 +947,38 @@ function buildSeedPricePanel ({ onSearch, onPrev, onNext })
848
947
return { root, search, meta, list, prev, next, pageLabel };
849
948
}
850
949
950
function buildGameAdminsPanel ({ onGrant, onRevoke })
951
{
952
const root = document.createElement("div");
953
root.className = "game-admins-panel";
954
955
const hint = document.createElement("p");
956
hint.className = "hint";
957
hint.textContent = "Game admins can use the world editor. The first account to sign in becomes admin. Others must sign in once before you can promote them by username.";
958
959
const list = document.createElement("div");
960
list.className = "game-admins-list";
961
962
const addRow = document.createElement("div");
963
addRow.className = "game-admin-add";
964
const input = document.createElement("input");
965
input.type = "text";
966
input.placeholder = "Username";
967
input.autocomplete = "off";
968
const addBtn = document.createElement("button");
969
addBtn.type = "button";
970
addBtn.textContent = "Grant admin";
971
addBtn.addEventListener("click", () =>
972
{
973
onGrant?.(input.value);
974
input.value = "";
975
});
976
addRow.append(input, addBtn);
977
978
root.append(hint, list, addRow);
979
return { root, list };
980
}
981
851
982
function buildStarterEquipmentPanel ({ onAddInventory })
852
983
{
853
984
const root = document.createElement("div");
@@ -38,7 +38,7 @@ const SLOT_LABELS = Object.freeze({38
offhand: "Off-hand"38
offhand: "Off-hand"39
});39
});40
40
41
export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })41
export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight, getAuthSubject })42
{42
{43
const backdrop = document.getElementById("settings-backdrop");43
const backdrop = document.getElementById("settings-backdrop");44
const modal = document.getElementById("settings-modal");44
const modal = document.getElementById("settings-modal");@@ -65,6 +65,9 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi65
let draftEquipmentStats = normalizeEquipmentStatBonuses(null);65
let draftEquipmentStats = normalizeEquipmentStatBonuses(null);66
let equipmentStatsPanel = null;66
let equipmentStatsPanel = null;67
let equipmentStatsCategoryId = EQUIPMENT_STAT_CATEGORIES[0]?.id ?? null;67
let equipmentStatsCategoryId = EQUIPMENT_STAT_CATEGORIES[0]?.id ?? null;68
/** @type {{ authSubject: string, username: string|null, email: string|null }[]} */69
let gameAdmins = [];70
let gameAdminsPanel = null;68
71
69
buildForm(form, {72
buildForm(form, {70
getActiveCategory: () => activeCategory,73
getActiveCategory: () => activeCategory,@@ -78,6 +81,11 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi78
{ renderStarterPanel(); }81
{ renderStarterPanel(); }79
if (id === "equipmentStats")82
if (id === "equipmentStats")80
{ renderEquipmentStatsPanel(); }83
{ renderEquipmentStatsPanel(); }84
if (id === "gameAdmins")85
{86
socket.send({ type: MessageType.editorLoadGameAdmins });87
renderGameAdminsPanel();88
}81
},89
},82
onFieldInput (field)90
onFieldInput (field)83
{91
{@@ -95,6 +103,10 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi95
onEquipmentStatsPanelReady (panel)103
onEquipmentStatsPanelReady (panel)96
{104
{97
equipmentStatsPanel = panel;105
equipmentStatsPanel = panel;106
},107
onGameAdminsPanelReady (panel)108
{109
gameAdminsPanel = panel;98
}110
}99
});111
});100
112
@@ -148,6 +160,74 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi148
renderStarterPanel();160
renderStarterPanel();149
form.dispatchEvent(new CustomEvent("starter-changed"));161
form.dispatchEvent(new CustomEvent("starter-changed"));150
});162
});163
form.addEventListener("game-admin-grant", (event) =>164
{165
const username = String(event.detail?.username ?? "").trim();166
if (!username)167
{ return; }168
socket.send({ type: MessageType.editorGrantGameAdmin, username });169
});170
form.addEventListener("game-admin-revoke", (event) =>171
{172
const authSubject = String(event.detail?.authSubject ?? "").trim();173
if (!authSubject)174
{ return; }175
socket.send({176
type: MessageType.editorRevokeGameAdmin,177
authSubject,178
confirmSelf: !!event.detail?.confirmSelf179
});180
});181
182
function renderGameAdminsPanel ()183
{184
if (!gameAdminsPanel)185
{ return; }186
const selfSubject = getAuthSubject?.() ?? null;187
gameAdminsPanel.list.innerHTML = "";188
if (!gameAdmins.length)189
{190
const empty = document.createElement("p");191
empty.className = "hint";192
empty.textContent = "No game admins yet.";193
gameAdminsPanel.list.append(empty);194
return;195
}196
for (const admin of gameAdmins)197
{198
const row = document.createElement("div");199
row.className = "game-admin-row";200
const label = document.createElement("span");201
label.textContent = admin.username ?? admin.email ?? admin.authSubject;202
const meta = document.createElement("span");203
meta.className = "muted small";204
meta.textContent = admin.email && admin.username ? admin.email : admin.authSubject;205
const remove = document.createElement("button");206
remove.type = "button";207
remove.textContent = "Remove admin";208
remove.addEventListener("click", () =>209
{210
const isSelf = admin.authSubject === selfSubject;211
if (isSelf)212
{213
const ok = window.confirm("Remove your own admin access? You will lose editor access on reconnect.");214
if (!ok)215
{ return; }216
form.dispatchEvent(new CustomEvent("game-admin-revoke", {217
detail: { authSubject: admin.authSubject, confirmSelf: true }218
}));219
return;220
}221
if (!window.confirm(`Remove admin access from ${label.textContent}?`))222
{ return; }223
form.dispatchEvent(new CustomEvent("game-admin-revoke", {224
detail: { authSubject: admin.authSubject, confirmSelf: false }225
}));226
});227
row.append(label, meta, remove);228
gameAdminsPanel.list.append(row);229
}230
}151
231
152
function show (visible)232
function show (visible)153
{233
{@@ -174,6 +254,7 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi174
document.getElementById("open-settings").addEventListener("click", () =>254
document.getElementById("open-settings").addEventListener("click", () =>175
{255
{176
socket.send({ type: MessageType.editorLoadSettings });256
socket.send({ type: MessageType.editorLoadSettings });257
socket.send({ type: MessageType.editorLoadGameAdmins });177
show(true);258
show(true);178
});259
});179
document.getElementById("settings-close").addEventListener("click", () => show(false));260
document.getElementById("settings-close").addEventListener("click", () => show(false));@@ -638,6 +719,12 @@ export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNi638
isOpen: () => open,719
isOpen: () => open,639
handleMessage (message)720
handleMessage (message)640
{721
{722
if (message.type === MessageType.editorGameAdmins)723
{724
gameAdmins = Array.isArray(message.admins) ? message.admins : [];725
renderGameAdminsPanel();726
return;727
}641
loaded = true;728
loaded = true;642
baseline = {729
baseline = {643
...message.settings,730
...message.settings,@@ -667,7 +754,8 @@ function buildForm (form, {667
onFieldInput,754
onFieldInput,668
onSeedPanelReady,755
onSeedPanelReady,669
onStarterPanelReady,756
onStarterPanelReady,670
onEquipmentStatsPanelReady757
onEquipmentStatsPanelReady,758
onGameAdminsPanelReady671
})759
})672
{760
{673
form.innerHTML = "";761
form.innerHTML = "";@@ -722,6 +810,17 @@ function buildForm (form, {722
section.append(panel.root);810
section.append(panel.root);723
onEquipmentStatsPanelReady?.(panel);811
onEquipmentStatsPanelReady?.(panel);724
}812
}813
else if (category.panel === "gameAdmins")814
{815
const panel = buildGameAdminsPanel({816
onGrant (username)817
{ form.dispatchEvent(new CustomEvent("game-admin-grant", { detail: { username } })); },818
onRevoke (authSubject, confirmSelf)819
{ form.dispatchEvent(new CustomEvent("game-admin-revoke", { detail: { authSubject, confirmSelf } })); }820
});821
section.append(panel.root);822
onGameAdminsPanelReady?.(panel);823
}725
else824
else726
{825
{727
for (const field of category.fields)826
for (const field of category.fields)@@ -848,6 +947,38 @@ function buildSeedPricePanel ({ onSearch, onPrev, onNext })848
return { root, search, meta, list, prev, next, pageLabel };947
return { root, search, meta, list, prev, next, pageLabel };849
}948
}850
949
950
function buildGameAdminsPanel ({ onGrant, onRevoke })951
{952
const root = document.createElement("div");953
root.className = "game-admins-panel";954
955
const hint = document.createElement("p");956
hint.className = "hint";957
hint.textContent = "Game admins can use the world editor. The first account to sign in becomes admin. Others must sign in once before you can promote them by username.";958
959
const list = document.createElement("div");960
list.className = "game-admins-list";961
962
const addRow = document.createElement("div");963
addRow.className = "game-admin-add";964
const input = document.createElement("input");965
input.type = "text";966
input.placeholder = "Username";967
input.autocomplete = "off";968
const addBtn = document.createElement("button");969
addBtn.type = "button";970
addBtn.textContent = "Grant admin";971
addBtn.addEventListener("click", () =>972
{973
onGrant?.(input.value);974
input.value = "";975
});976
addRow.append(input, addBtn);977
978
root.append(hint, list, addRow);979
return { root, list };980
}981
851
function buildStarterEquipmentPanel ({ onAddInventory })982
function buildStarterEquipmentPanel ({ onAddInventory })852
{983
{853
const root = document.createElement("div");984
const root = document.createElement("div");@@ -0,0 +1,28 @@
1
export async function fetchAuthStatus ()
2
{
3
const response = await fetch("/auth/status");
4
if (!response.ok)
5
{ return { authenticated: false }; }
6
return response.json();
7
}
8
9
export function loginUrl (returnTo = location.pathname + location.search)
10
{
11
return `/auth/login?return_to=${encodeURIComponent(returnTo)}`;
12
}
13
14
export function logoutUrl (returnTo = "/")
15
{
16
return `/auth/logout?return_to=${encodeURIComponent(returnTo)}`;
17
}
18
19
export function formatAccountLabel (status)
20
{
21
if (!status?.authenticated)
22
{ return "Signed out"; }
23
if (status.username)
24
{ return status.username; }
25
if (status.email)
26
{ return status.email; }
27
return status.authSubject ?? "Signed in";
28
}
@@ -0,0 +1,28 @@1
export async function fetchAuthStatus ()2
{3
const response = await fetch("/auth/status");4
if (!response.ok)5
{ return { authenticated: false }; }6
return response.json();7
}8
9
export function loginUrl (returnTo = location.pathname + location.search)10
{11
return `/auth/login?return_to=${encodeURIComponent(returnTo)}`;12
}13
14
export function logoutUrl (returnTo = "/")15
{16
return `/auth/logout?return_to=${encodeURIComponent(returnTo)}`;17
}18
19
export function formatAccountLabel (status)20
{21
if (!status?.authenticated)22
{ return "Signed out"; }23
if (status.username)24
{ return status.username; }25
if (status.email)26
{ return status.email; }27
return status.authSubject ?? "Signed in";28
}@@ -3,6 +3,7 @@ import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
3
3
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
4
4
import { OVERWORLD_ID } from "/shared/world/dimensions.js";
5
5
import { GameSocket, defaultSocketUrl } from "../net/socket.js";
6
import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";
6
7
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
7
8
import { WorldView } from "../render/worldView.js";
8
9
import { initSocial } from "./social.js";
@@ -989,6 +990,15 @@ function startPlay (payload)
989
990
990
991
async function main ()
991
992
{
993
const authStatus = await fetchAuthStatus();
994
updateAuthUi(authStatus);
995
if (!authStatus.authenticated)
996
{
997
statusEl.textContent = "Sign in to play Questward.";
998
showError("");
999
return;
1000
}
1001
992
1002
catalog = await loadSpriteCatalog();
993
1003
await preloadCatalogImages(game, catalog);
994
1004
applySpriteSheets(game.images, catalog);
@@ -1172,7 +1182,7 @@ async function main ()
1172
1182
{
1173
1183
case MessageType.session:
1174
1184
session = message;
1175
statusEl.textContent = `Signed in as ${message.authSubject} (stub admin)`;
1185
statusEl.textContent = `Signed in as ${message.username ?? message.authSubject}${message.isAdmin ? " · admin" : ""}`;
1176
1186
renderCharacters(message.characters);
1177
1187
break;
1178
1188
case MessageType.characterList:
@@ -1870,3 +1880,26 @@ function chebyshev (ax, ay, bx, by)
1870
1880
{
1871
1881
return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
1872
1882
}
1883
1884
function updateAuthUi (authStatus)
1885
{
1886
const signIn = document.getElementById("auth-sign-in");
1887
const signOut = document.getElementById("auth-sign-out");
1888
const exportLink = document.getElementById("auth-export");
1889
if (signIn)
1890
{
1891
signIn.hidden = !!authStatus?.authenticated;
1892
signIn.href = loginUrl("/");
1893
}
1894
if (signOut)
1895
{
1896
signOut.hidden = !authStatus?.authenticated;
1897
signOut.href = logoutUrl("/");
1898
}
1899
if (exportLink)
1900
{ exportLink.hidden = !authStatus?.authenticated; }
1901
if (authStatus?.authenticated && !session)
1902
{
1903
statusEl.textContent = `Signed in as ${formatAccountLabel(authStatus)}`;
1904
}
1905
}
@@ -3,6 +3,7 @@ import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";3
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";3
import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";4
import { OVERWORLD_ID } from "/shared/world/dimensions.js";4
import { OVERWORLD_ID } from "/shared/world/dimensions.js";5
import { GameSocket, defaultSocketUrl } from "../net/socket.js";5
import { GameSocket, defaultSocketUrl } from "../net/socket.js";6
import { fetchAuthStatus, formatAccountLabel, loginUrl, logoutUrl } from "../net/auth.js";6
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";7
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";7
import { WorldView } from "../render/worldView.js";8
import { WorldView } from "../render/worldView.js";8
import { initSocial } from "./social.js";9
import { initSocial } from "./social.js";@@ -989,6 +990,15 @@ function startPlay (payload)989
990
990
async function main ()991
async function main ()991
{992
{993
const authStatus = await fetchAuthStatus();994
updateAuthUi(authStatus);995
if (!authStatus.authenticated)996
{997
statusEl.textContent = "Sign in to play Questward.";998
showError("");999
return;1000
}1001
992
catalog = await loadSpriteCatalog();1002
catalog = await loadSpriteCatalog();993
await preloadCatalogImages(game, catalog);1003
await preloadCatalogImages(game, catalog);994
applySpriteSheets(game.images, catalog);1004
applySpriteSheets(game.images, catalog);@@ -1172,7 +1182,7 @@ async function main ()1172
{1182
{1173
case MessageType.session:1183
case MessageType.session:1174
session = message;1184
session = message;1175
statusEl.textContent = `Signed in as ${message.authSubject} (stub admin)`;1185
statusEl.textContent = `Signed in as ${message.username ?? message.authSubject}${message.isAdmin ? " · admin" : ""}`;1176
renderCharacters(message.characters);1186
renderCharacters(message.characters);1177
break;1187
break;1178
case MessageType.characterList:1188
case MessageType.characterList:@@ -1870,3 +1880,26 @@ function chebyshev (ax, ay, bx, by)1870
{1880
{1871
return Math.max(Math.abs(ax - bx), Math.abs(ay - by));1881
return Math.max(Math.abs(ax - bx), Math.abs(ay - by));1872
}1882
}1883
1884
function updateAuthUi (authStatus)1885
{1886
const signIn = document.getElementById("auth-sign-in");1887
const signOut = document.getElementById("auth-sign-out");1888
const exportLink = document.getElementById("auth-export");1889
if (signIn)1890
{1891
signIn.hidden = !!authStatus?.authenticated;1892
signIn.href = loginUrl("/");1893
}1894
if (signOut)1895
{1896
signOut.hidden = !authStatus?.authenticated;1897
signOut.href = logoutUrl("/");1898
}1899
if (exportLink)1900
{ exportLink.hidden = !authStatus?.authenticated; }1901
if (authStatus?.authenticated && !session)1902
{1903
statusEl.textContent = `Signed in as ${formatAccountLabel(authStatus)}`;1904
}1905
}@@ -18,7 +18,7 @@ systemd runs the update script above.
18
18
## Install on the host
19
19
20
20
```bash
21
cd /srv/tile-mmo/current # or your clone
21
cd /srv/questward/current # or your clone
22
22
sudo ./deploy/install-service.sh
23
23
```
24
24
@@ -26,15 +26,20 @@ Optional env overrides:
26
26
27
27
| Variable | Default |
28
28
|----------|---------|
29
| `TILE_MMO_REPO` | parent of `deploy/` |
30
| `TILE_MMO_USER` | `tilemmo` |
31
| `TILE_MMO_GIT_BRANCH` | `master` |
29
| `QUESTWARD_REPO` | parent of `deploy/` |
30
| `QUESTWARD_USER` | `questward` |
31
| `QUESTWARD_GIT_BRANCH` | `master` |
32
| `QUESTWARD_AUTH_CLIENT_SECRET` | (unset — stub auth) |
33
34
See root `README.md` for OAuth / auth.timfalken.com setup.
35
36
`TILE_MMO_*` env vars are still accepted as fallbacks for older installs.
32
37
33
38
## Manual ops
34
39
35
40
```bash
36
sudo systemctl restart tile-mmo
37
journalctl -u tile-mmo -f
41
sudo systemctl restart questward
42
journalctl -u questward -f
38
43
```
39
44
40
Disable the in-process schedule locally with `TILE_MMO_DEPLOY_SCHEDULER=0`.
45
Disable the in-process schedule locally with `QUESTWARD_DEPLOY_SCHEDULER=0`.
@@ -18,7 +18,7 @@ systemd runs the update script above.18
## Install on the host18
## Install on the host19
19
20
```bash20
```bash21
cd /srv/tile-mmo/current # or your clone21
cd /srv/questward/current # or your clone22
sudo ./deploy/install-service.sh22
sudo ./deploy/install-service.sh23
```23
```24
24
@@ -26,15 +26,20 @@ Optional env overrides:26
26
27
| Variable | Default |27
| Variable | Default |28
|----------|---------|28
|----------|---------|29
| `TILE_MMO_REPO` | parent of `deploy/` |29
| `QUESTWARD_REPO` | parent of `deploy/` |30
| `TILE_MMO_USER` | `tilemmo` |30
| `QUESTWARD_USER` | `questward` |31
| `TILE_MMO_GIT_BRANCH` | `master` |31
| `QUESTWARD_GIT_BRANCH` | `master` |32
| `QUESTWARD_AUTH_CLIENT_SECRET` | (unset — stub auth) |33
34
See root `README.md` for OAuth / auth.timfalken.com setup.35
36
`TILE_MMO_*` env vars are still accepted as fallbacks for older installs.32
37
33
## Manual ops38
## Manual ops34
39
35
```bash40
```bash36
sudo systemctl restart tile-mmo41
sudo systemctl restart questward37
journalctl -u tile-mmo -f42
journalctl -u questward -f38
```43
```39
44
40
Disable the in-process schedule locally with `TILE_MMO_DEPLOY_SCHEDULER=0`.45
Disable the in-process schedule locally with `QUESTWARD_DEPLOY_SCHEDULER=0`.@@ -1,12 +1,12 @@
1
1
#!/usr/bin/env bash
2
# Install and start the Tile MMO systemd unit (run as root on the game host).
2
# Install and start the Questward systemd unit (run as root on the game host).
3
3
set -euo pipefail
4
4
5
5
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
6
REPO="${TILE_MMO_REPO:-$(cd "$SCRIPT_DIR/.." && pwd)}"
7
UNIT_SRC="$SCRIPT_DIR/tile-mmo.service"
8
UNIT_DST="/etc/systemd/system/tile-mmo.service"
9
SERVICE_USER="${TILE_MMO_USER:-tilemmo}"
6
REPO="${QUESTWARD_REPO:-${TILE_MMO_REPO:-$(cd "$SCRIPT_DIR/.." && pwd)}}"
7
UNIT_SRC="$SCRIPT_DIR/questward.service"
8
UNIT_DST="/etc/systemd/system/questward.service"
9
SERVICE_USER="${QUESTWARD_USER:-${TILE_MMO_USER:-questward}}"
10
10
11
11
if [[ "$(id -u)" -ne 0 ]]; then
12
12
echo "Run as root: sudo $0" >&2
@@ -23,7 +23,7 @@ chmod +x "$SCRIPT_DIR/start-server.sh" "$SCRIPT_DIR/update-if-requested.mjs" 2>/
23
23
# Rewrite WorkingDirectory / paths for this checkout.
24
24
tmp="$(mktemp)"
25
25
sed \
26
-e "s|/srv/tile-mmo/current|$REPO|g" \
26
-e "s|/srv/questward/current|$REPO|g" \
27
27
-e "s|^User=.*|User=$SERVICE_USER|" \
28
28
-e "s|^Group=.*|Group=$SERVICE_USER|" \
29
29
"$UNIT_SRC" > "$tmp"
@@ -31,11 +31,11 @@ install -m 0644 "$tmp" "$UNIT_DST"
31
31
rm -f "$tmp"
32
32
33
33
systemctl daemon-reload
34
systemctl enable tile-mmo.service
35
systemctl restart tile-mmo.service
36
systemctl --no-pager --full status tile-mmo.service || true
34
systemctl enable questward.service
35
systemctl restart questward.service
36
systemctl --no-pager --full status questward.service || true
37
37
38
38
echo
39
39
echo "Installed $UNIT_DST"
40
40
echo "Repo: $REPO"
41
echo "Logs: journalctl -u tile-mmo -f"
41
echo "Logs: journalctl -u questward -f"
@@ -1,12 +1,12 @@1
#!/usr/bin/env bash1
#!/usr/bin/env bash2
# Install and start the Tile MMO systemd unit (run as root on the game host).2
# Install and start the Questward systemd unit (run as root on the game host).3
set -euo pipefail3
set -euo pipefail4
4
5
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"5
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"6
REPO="${TILE_MMO_REPO:-$(cd "$SCRIPT_DIR/.." && pwd)}"6
REPO="${QUESTWARD_REPO:-${TILE_MMO_REPO:-$(cd "$SCRIPT_DIR/.." && pwd)}}"7
UNIT_SRC="$SCRIPT_DIR/tile-mmo.service"7
UNIT_SRC="$SCRIPT_DIR/questward.service"8
UNIT_DST="/etc/systemd/system/tile-mmo.service"8
UNIT_DST="/etc/systemd/system/questward.service"9
SERVICE_USER="${TILE_MMO_USER:-tilemmo}"9
SERVICE_USER="${QUESTWARD_USER:-${TILE_MMO_USER:-questward}}"10
10
11
if [[ "$(id -u)" -ne 0 ]]; then11
if [[ "$(id -u)" -ne 0 ]]; then12
echo "Run as root: sudo $0" >&212
echo "Run as root: sudo $0" >&2@@ -23,7 +23,7 @@ chmod +x "$SCRIPT_DIR/start-server.sh" "$SCRIPT_DIR/update-if-requested.mjs" 2>/23
# Rewrite WorkingDirectory / paths for this checkout.23
# Rewrite WorkingDirectory / paths for this checkout.24
tmp="$(mktemp)"24
tmp="$(mktemp)"25
sed \25
sed \26
-e "s|/srv/tile-mmo/current|$REPO|g" \26
-e "s|/srv/questward/current|$REPO|g" \27
-e "s|^User=.*|User=$SERVICE_USER|" \27
-e "s|^User=.*|User=$SERVICE_USER|" \28
-e "s|^Group=.*|Group=$SERVICE_USER|" \28
-e "s|^Group=.*|Group=$SERVICE_USER|" \29
"$UNIT_SRC" > "$tmp"29
"$UNIT_SRC" > "$tmp"@@ -31,11 +31,11 @@ install -m 0644 "$tmp" "$UNIT_DST"31
rm -f "$tmp"31
rm -f "$tmp"32
32
33
systemctl daemon-reload33
systemctl daemon-reload34
systemctl enable tile-mmo.service34
systemctl enable questward.service35
systemctl restart tile-mmo.service35
systemctl restart questward.service36
systemctl --no-pager --full status tile-mmo.service || true36
systemctl --no-pager --full status questward.service || true37
37
38
echo38
echo39
echo "Installed $UNIT_DST"39
echo "Installed $UNIT_DST"40
echo "Repo: $REPO"40
echo "Repo: $REPO"41
echo "Logs: journalctl -u tile-mmo -f"41
echo "Logs: journalctl -u questward -f"@@ -1,19 +1,19 @@
1
1
[Unit]
2
Description=Tile MMO Server
2
Description=Questward Server
3
3
After=network-online.target
4
4
Wants=network-online.target
5
5
6
6
[Service]
7
7
Type=simple
8
User=tilemmo
9
Group=tilemmo
10
WorkingDirectory=/srv/tile-mmo/current
8
User=questward
9
Group=questward
10
WorkingDirectory=/srv/questward/current
11
11
Environment=NODE_ENV=production
12
Environment=TILE_MMO_GIT_BRANCH=master
13
Environment=TILE_MMO_REPO=/srv/tile-mmo/current
14
Environment=TILE_MMO_DATA=/srv/tile-mmo/current/server/data
12
Environment=QUESTWARD_GIT_BRANCH=master
13
Environment=QUESTWARD_REPO=/srv/questward/current
14
Environment=QUESTWARD_DATA=/srv/questward/current/server/data
15
15
# Every start (including crash recovery) hard-resets, pulls, npm installs, then runs Node.
16
ExecStart=/srv/tile-mmo/current/deploy/start-server.sh
16
ExecStart=/srv/questward/current/deploy/start-server.sh
17
17
Restart=always
18
18
RestartSec=5s
19
19
TimeoutStartSec=600s
@@ -1,19 +1,19 @@1
[Unit]1
[Unit]2
Description=Tile MMO Server2
Description=Questward Server3
After=network-online.target3
After=network-online.target4
Wants=network-online.target4
Wants=network-online.target5
5
6
[Service]6
[Service]7
Type=simple7
Type=simple8
User=tilemmo8
User=questward9
Group=tilemmo9
Group=questward10
WorkingDirectory=/srv/tile-mmo/current10
WorkingDirectory=/srv/questward/current11
Environment=NODE_ENV=production11
Environment=NODE_ENV=production12
Environment=TILE_MMO_GIT_BRANCH=master12
Environment=QUESTWARD_GIT_BRANCH=master13
Environment=TILE_MMO_REPO=/srv/tile-mmo/current13
Environment=QUESTWARD_REPO=/srv/questward/current14
Environment=TILE_MMO_DATA=/srv/tile-mmo/current/server/data14
Environment=QUESTWARD_DATA=/srv/questward/current/server/data15
# Every start (including crash recovery) hard-resets, pulls, npm installs, then runs Node.15
# Every start (including crash recovery) hard-resets, pulls, npm installs, then runs Node.16
ExecStart=/srv/tile-mmo/current/deploy/start-server.sh16
ExecStart=/srv/questward/current/deploy/start-server.sh17
Restart=always17
Restart=always18
RestartSec=5s18
RestartSec=5s19
TimeoutStartSec=600s19
TimeoutStartSec=600s@@ -4,8 +4,8 @@
4
4
# can pick up a fix from origin (intentional — do not skip pull on crash).
5
5
set -euo pipefail
6
6
7
REPO="${TILE_MMO_REPO:-$(cd "$(dirname "$0")/.." && pwd)}"
8
BRANCH="${TILE_MMO_GIT_BRANCH:-master}"
7
REPO="${QUESTWARD_REPO:-${TILE_MMO_REPO:-$(cd "$(dirname "$0")/.." && pwd)}}"
8
BRANCH="${QUESTWARD_GIT_BRANCH:-${TILE_MMO_GIT_BRANCH:-master}}"
9
9
cd "$REPO"
10
10
11
11
echo "[deploy] Working tree: $REPO (branch $BRANCH)"
@@ -4,8 +4,8 @@4
# can pick up a fix from origin (intentional — do not skip pull on crash).4
# can pick up a fix from origin (intentional — do not skip pull on crash).5
set -euo pipefail5
set -euo pipefail6
6
7
REPO="${TILE_MMO_REPO:-$(cd "$(dirname "$0")/.." && pwd)}"7
REPO="${QUESTWARD_REPO:-${TILE_MMO_REPO:-$(cd "$(dirname "$0")/.." && pwd)}}"8
BRANCH="${TILE_MMO_GIT_BRANCH:-master}"8
BRANCH="${QUESTWARD_GIT_BRANCH:-${TILE_MMO_GIT_BRANCH:-master}}"9
cd "$REPO"9
cd "$REPO"10
10
11
echo "[deploy] Working tree: $REPO (branch $BRANCH)"11
echo "[deploy] Working tree: $REPO (branch $BRANCH)"@@ -4,17 +4,18 @@
4
4
* requested a code deployment. Crashes without a manifest never pull.
5
5
*
6
6
* Env:
7
* TILE_MMO_REPO — git working tree (default: cwd)
8
* TILE_MMO_DATA — directory containing restart-request.json (default: <repo>/server/data)
9
* TILE_MMO_GIT_BRANCH — remote branch (default: master)
7
* QUESTWARD_REPO — git working tree (default: cwd)
8
* QUESTWARD_DATA — directory containing restart-request.json (default: <repo>/server/data)
9
* QUESTWARD_GIT_BRANCH — remote branch (default: master)
10
* (TILE_MMO_* env vars are still accepted as fallbacks.)
10
11
*/
11
12
import { spawnSync } from "node:child_process";
12
13
import { join } from "node:path";
13
14
import { consumeRestartManifest, restartManifestPath } from "../server/src/deploy/manifest.js";
14
15
15
const repo = process.env.TILE_MMO_REPO || process.cwd();
16
const dataDir = process.env.TILE_MMO_DATA || join(repo, "server", "data");
17
const branch = process.env.TILE_MMO_GIT_BRANCH || "master";
16
const repo = process.env.QUESTWARD_REPO || process.env.TILE_MMO_REPO || process.cwd();
17
const dataDir = process.env.QUESTWARD_DATA || process.env.TILE_MMO_DATA || join(repo, "server", "data");
18
const branch = process.env.QUESTWARD_GIT_BRANCH || process.env.TILE_MMO_GIT_BRANCH || "master";
18
19
const manifestPath = restartManifestPath(dataDir);
19
20
20
21
const manifest = consumeRestartManifest(manifestPath);
@@ -4,17 +4,18 @@4
* requested a code deployment. Crashes without a manifest never pull.4
* requested a code deployment. Crashes without a manifest never pull.5
*5
*6
* Env:6
* Env:7
* TILE_MMO_REPO — git working tree (default: cwd)7
* QUESTWARD_REPO — git working tree (default: cwd)8
* TILE_MMO_DATA — directory containing restart-request.json (default: <repo>/server/data)8
* QUESTWARD_DATA — directory containing restart-request.json (default: <repo>/server/data)9
* TILE_MMO_GIT_BRANCH — remote branch (default: master)9
* QUESTWARD_GIT_BRANCH — remote branch (default: master)10
* (TILE_MMO_* env vars are still accepted as fallbacks.)10
*/11
*/11
import { spawnSync } from "node:child_process";12
import { spawnSync } from "node:child_process";12
import { join } from "node:path";13
import { join } from "node:path";13
import { consumeRestartManifest, restartManifestPath } from "../server/src/deploy/manifest.js";14
import { consumeRestartManifest, restartManifestPath } from "../server/src/deploy/manifest.js";14
15
15
const repo = process.env.TILE_MMO_REPO || process.cwd();16
const repo = process.env.QUESTWARD_REPO || process.env.TILE_MMO_REPO || process.cwd();16
const dataDir = process.env.TILE_MMO_DATA || join(repo, "server", "data");17
const dataDir = process.env.QUESTWARD_DATA || process.env.TILE_MMO_DATA || join(repo, "server", "data");17
const branch = process.env.TILE_MMO_GIT_BRANCH || "master";18
const branch = process.env.QUESTWARD_GIT_BRANCH || process.env.TILE_MMO_GIT_BRANCH || "master";18
const manifestPath = restartManifestPath(dataDir);19
const manifestPath = restartManifestPath(dataDir);19
20
20
const manifest = consumeRestartManifest(manifestPath);21
const manifest = consumeRestartManifest(manifestPath);@@ -1,6 +1,6 @@
1
1
# Feature implementation tracker
2
2
3
Living companion to `tile_mmo_server_technical_design_v0.6.md`.
3
Living companion to `questward_server_technical_design_v0.6.md`.
4
4
Statuses: **not implemented** · **partial** · **full**.
5
5
6
6
Each entry is a short note on behaviour and where the code lives. Update this file in the same commit as the feature it describes.
@@ -91,10 +91,16 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
91
91
**Spec:** JSON WebSocket on `/ws`, HTTP static files for the client. Connections belong to the gateway. Clients send intentions that are queued onto the simulation tick. Editor messages are admin-only.
92
92
**Code:** `server/src/gateway/websocket.js`, `server/src/gateway/http.js`, `server/src/index.js`
93
93
94
## Stub authentication
94
## Authentication (auth.timfalken.com)
95
95
96
**Status:** full
97
**Spec:** Until auth.timfalken.com exists, each connection is `admin-<n>`. `n` starts at connected-count+1 and skips names already in use so two live sessions cannot share a stub id. Stub accounts are admins.
96
**Status:** partial
97
**Spec:** OAuth2 authorization-code flow via **auth.timfalken.com**. Sign in at `/auth/login`; callback at `/auth/callback` sets an HttpOnly session cookie. WebSocket `/ws` requires that cookie (or stub mode). The **first account** to sign in becomes a **game admin**; further admins are granted in the world editor **Settings → Admins** tab (username must have signed in once). Removing the last admin is blocked; removing yourself requires confirmation. `GET /settings/export` returns a JSON data export (integrator requirement). Stub mode (`QUESTWARD_AUTH_STUB=1` or missing client secret) keeps dev `admin-<n>` identities (all admins).
98
**Code:** `server/src/auth/`, `server/src/gateway/http.js`, `server/src/gateway/websocket.js`, `client/src/net/auth.js`, `client/src/editor/settingsModal.js` (Admins tab), tests in `server/tests/authAccounts.test.js`
99
100
## Stub authentication (dev only)
101
102
**Status:** full (when stub mode active)
103
**Spec:** Each connection is `admin-<n>` with full admin rights when OAuth is not configured.
98
104
**Code:** `server/src/auth/stub.js`
99
105
100
106
## Characters
@@ -185,7 +191,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
185
191
186
192
**Status:** full
187
193
**Spec:** The live process periodically `git fetch`es and compares `HEAD` to `origin/<branch>` (default `master`). When the remote is **ahead**, a graceful restart is scheduled for the next **server-local midnight**. From **3 hours before** midnight, every connected player gets a **permanent toast** with a live countdown. At midnight the server writes `server/data/restart-request.json`, force-logs out sessions, unloads/persists the world, and exits. **systemd** (`Restart=always`) relaunches via `deploy/start-server.sh`, which **always** hard-resets to `origin/<branch>`, pulls, runs `npm install`, then starts Node — including after crashes or power loss (intentional, so a fixed commit can recover a bad build). Install with `sudo ./deploy/install-service.sh`. World editor **Console** tab streams live server stdout to admins.
188
**Code:** `shared/deploy/schedule.js`, `server/src/deploy/`, `server/src/index.js`, `server/src/logging/consoleCapture.js`, `deploy/start-server.sh`, `deploy/install-service.sh`, `deploy/tile-mmo.service`, `client/src/play/toasts.js`, `client/src/editor/main.js`, tests in `server/tests/deploy.test.js`
194
**Code:** `shared/deploy/schedule.js`, `server/src/deploy/`, `server/src/index.js`, `server/src/logging/consoleCapture.js`, `deploy/start-server.sh`, `deploy/install-service.sh`, `deploy/questward.service`, `client/src/play/toasts.js`, `client/src/editor/main.js`, tests in `server/tests/deploy.test.js`
189
195
190
196
## Spawners
191
197
@@ -1,6 +1,6 @@1
# Feature implementation tracker
1
# Feature implementation tracker
2
2
3
Living companion to `tile_mmo_server_technical_design_v0.6.md`.
3
Living companion to `questward_server_technical_design_v0.6.md`.
4
Statuses: **not implemented** · **partial** · **full**.
4
Statuses: **not implemented** · **partial** · **full**.
5
5
6
Each entry is a short note on behaviour and where the code lives. Update this file in the same commit as the feature it describes.
6
Each entry is a short note on behaviour and where the code lives. Update this file in the same commit as the feature it describes.
@@ -91,10 +91,16 @@ Each entry is a short note on behaviour and where the code lives. Update this fi91
**Spec:** JSON WebSocket on `/ws`, HTTP static files for the client. Connections belong to the gateway. Clients send intentions that are queued onto the simulation tick. Editor messages are admin-only.
91
**Spec:** JSON WebSocket on `/ws`, HTTP static files for the client. Connections belong to the gateway. Clients send intentions that are queued onto the simulation tick. Editor messages are admin-only.
92
**Code:** `server/src/gateway/websocket.js`, `server/src/gateway/http.js`, `server/src/index.js`
92
**Code:** `server/src/gateway/websocket.js`, `server/src/gateway/http.js`, `server/src/index.js`
93
93
94
## Stub authentication
94
## Authentication (auth.timfalken.com)
95
95
96
**Status:** full
96
**Status:** partial
97
**Spec:** Until auth.timfalken.com exists, each connection is `admin-<n>`. `n` starts at connected-count+1 and skips names already in use so two live sessions cannot share a stub id. Stub accounts are admins.
97
**Spec:** OAuth2 authorization-code flow via **auth.timfalken.com**. Sign in at `/auth/login`; callback at `/auth/callback` sets an HttpOnly session cookie. WebSocket `/ws` requires that cookie (or stub mode). The **first account** to sign in becomes a **game admin**; further admins are granted in the world editor **Settings → Admins** tab (username must have signed in once). Removing the last admin is blocked; removing yourself requires confirmation. `GET /settings/export` returns a JSON data export (integrator requirement). Stub mode (`QUESTWARD_AUTH_STUB=1` or missing client secret) keeps dev `admin-<n>` identities (all admins).
98
**Code:** `server/src/auth/`, `server/src/gateway/http.js`, `server/src/gateway/websocket.js`, `client/src/net/auth.js`, `client/src/editor/settingsModal.js` (Admins tab), tests in `server/tests/authAccounts.test.js`
99
100
## Stub authentication (dev only)
101
102
**Status:** full (when stub mode active)
103
**Spec:** Each connection is `admin-<n>` with full admin rights when OAuth is not configured.
98
**Code:** `server/src/auth/stub.js`
104
**Code:** `server/src/auth/stub.js`
99
105
100
## Characters
106
## Characters
@@ -185,7 +191,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi185
191
186
**Status:** full
192
**Status:** full
187
**Spec:** The live process periodically `git fetch`es and compares `HEAD` to `origin/<branch>` (default `master`). When the remote is **ahead**, a graceful restart is scheduled for the next **server-local midnight**. From **3 hours before** midnight, every connected player gets a **permanent toast** with a live countdown. At midnight the server writes `server/data/restart-request.json`, force-logs out sessions, unloads/persists the world, and exits. **systemd** (`Restart=always`) relaunches via `deploy/start-server.sh`, which **always** hard-resets to `origin/<branch>`, pulls, runs `npm install`, then starts Node — including after crashes or power loss (intentional, so a fixed commit can recover a bad build). Install with `sudo ./deploy/install-service.sh`. World editor **Console** tab streams live server stdout to admins.
193
**Spec:** The live process periodically `git fetch`es and compares `HEAD` to `origin/<branch>` (default `master`). When the remote is **ahead**, a graceful restart is scheduled for the next **server-local midnight**. From **3 hours before** midnight, every connected player gets a **permanent toast** with a live countdown. At midnight the server writes `server/data/restart-request.json`, force-logs out sessions, unloads/persists the world, and exits. **systemd** (`Restart=always`) relaunches via `deploy/start-server.sh`, which **always** hard-resets to `origin/<branch>`, pulls, runs `npm install`, then starts Node — including after crashes or power loss (intentional, so a fixed commit can recover a bad build). Install with `sudo ./deploy/install-service.sh`. World editor **Console** tab streams live server stdout to admins.
188
**Code:** `shared/deploy/schedule.js`, `server/src/deploy/`, `server/src/index.js`, `server/src/logging/consoleCapture.js`, `deploy/start-server.sh`, `deploy/install-service.sh`, `deploy/tile-mmo.service`, `client/src/play/toasts.js`, `client/src/editor/main.js`, tests in `server/tests/deploy.test.js`
194
**Code:** `shared/deploy/schedule.js`, `server/src/deploy/`, `server/src/index.js`, `server/src/logging/consoleCapture.js`, `deploy/start-server.sh`, `deploy/install-service.sh`, `deploy/questward.service`, `client/src/play/toasts.js`, `client/src/editor/main.js`, tests in `server/tests/deploy.test.js`
189
195
190
## Spawners
196
## Spawners
191
197
@@ -1,7 +1,7 @@
1
1
# Player scripts (AFK / offline)
2
2
3
3
**Status:** not implemented (design only)
4
**Related:** `tile_mmo_server_technical_design_v0.6.md` §18 (controller abstraction, offline entity, sandbox rules)
4
**Related:** `questward_server_technical_design_v0.6.md` §18 (controller abstraction, offline entity, sandbox rules)
5
5
6
6
Scripts are a **sandboxed language** interpreted on the **server**. They never mutate world state directly; they emit the same player **intents** as a human client (`moveTo`, gather, craft, attack, shop, equip, …). The server validates every step.
7
7
@@ -1,7 +1,7 @@1
# Player scripts (AFK / offline)
1
# Player scripts (AFK / offline)
2
2
3
**Status:** not implemented (design only)
3
**Status:** not implemented (design only)
4
**Related:** `tile_mmo_server_technical_design_v0.6.md` §18 (controller abstraction, offline entity, sandbox rules)
4
**Related:** `questward_server_technical_design_v0.6.md` §18 (controller abstraction, offline entity, sandbox rules)
5
5
6
Scripts are a **sandboxed language** interpreted on the **server**. They never mutate world state directly; they emit the same player **intents** as a human client (`moveTo`, gather, craft, attack, shop, equip, …). The server validates every step.
6
Scripts are a **sandboxed language** interpreted on the **server**. They never mutate world state directly; they emit the same player **intents** as a human client (`moveTo`, gather, craft, attack, shop, equip, …). The server validates every step.
7
7
@@ -1,10 +1,10 @@
1
1
{
2
"name": "tile-mmo",
2
"name": "questward",
3
3
"lockfileVersion": 3,
4
4
"requires": true,
5
5
"packages": {
6
6
"": {
7
"name": "tile-mmo",
7
"name": "questward",
8
8
"dependencies": {
9
9
"ws": "^8.18.3"
10
10
},
@@ -1,10 +1,10 @@1
{1
{2
"name": "tile-mmo",2
"name": "questward",3
"lockfileVersion": 3,3
"lockfileVersion": 3,4
"requires": true,4
"requires": true,5
"packages": {5
"packages": {6
"": {6
"": {7
"name": "tile-mmo",7
"name": "questward",8
"dependencies": {8
"dependencies": {9
"ws": "^8.18.3"9
"ws": "^8.18.3"10
},10
},@@ -1,5 +1,5 @@
1
1
{
2
"name": "tile-mmo",
2
"name": "questward",
3
3
"private": true,
4
4
"type": "module",
5
5
"engines": {
@@ -1,5 +1,5 @@1
{1
{2
"name": "tile-mmo",2
"name": "questward",3
"private": true,3
"private": true,4
"type": "module",4
"type": "module",5
"engines": {5
"engines": {@@ -1,11 +1,11 @@
1
1
---
2
title: Tile MMO Server Technical Design
2
title: Questward Server Technical Design
3
3
version: 0.21
4
4
status: proposed
5
5
format: living-design-document
6
6
---
7
7
8
# Tile MMO Server Technical Design
8
# Questward Server Technical Design
9
9
10
10
**Version:** 0.21
11
11
**Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
@@ -1312,21 +1312,21 @@ A production unit can conceptually look like this:
1312
1312
1313
1313
```ini
1314
1314
[Unit]
1315
Description=Tile MMO Server
1315
Description=Questward Server
1316
1316
After=network-online.target
1317
1317
Wants=network-online.target
1318
1318
1319
1319
[Service]
1320
1320
Type=simple
1321
User=tilemmo
1322
Group=tilemmo
1323
WorkingDirectory=/srv/tile-mmo/current
1321
User=questward
1322
Group=questward
1323
WorkingDirectory=/srv/questward/current
1324
1324
1325
1325
# This hook checks the restart manifest. It pulls/builds only when an
1326
1326
# intentional deployment was requested. Prefixing with '+' optionally
1327
1327
# allows the hook to run with privileges different from the game user.
1328
ExecStartPre=+/usr/local/sbin/tile-mmo-update-if-requested
1329
ExecStart=/usr/bin/node /srv/tile-mmo/current/dist/server.js
1328
ExecStartPre=+/usr/local/sbin/questward-update-if-requested
1329
ExecStart=/usr/bin/node /srv/questward/current/dist/server.js
1330
1330
1331
1331
Restart=always
1332
1332
RestartSec=5s
@@ -1338,7 +1338,7 @@ WantedBy=multi-user.target
1338
1338
```
1339
1339
1340
1340
`Restart=always` is appropriate here because an explicit
1341
`systemctl stop tile-mmo` does not cause systemd to restart the unit,
1341
`systemctl stop questward` does not cause systemd to restart the unit,
1342
1342
while a clean in-game restart exit and an unexpected crash both do.
1343
1343
1344
1344
The exact paths, build command and privilege split are deployment
@@ -1,11 +1,11 @@1
---1
---2
title: Tile MMO Server Technical Design2
title: Questward Server Technical Design3
version: 0.213
version: 0.214
status: proposed4
status: proposed5
format: living-design-document5
format: living-design-document6
---6
---7
7
8
# Tile MMO Server Technical Design8
# Questward Server Technical Design9
9
10
**Version:** 0.21 10
**Version:** 0.21 11
**Status:** Proposed architecture; intended to be iterated as implementation decisions are made. 11
**Status:** Proposed architecture; intended to be iterated as implementation decisions are made. @@ -1312,21 +1312,21 @@ A production unit can conceptually look like this:1312
1312
1313
```ini1313
```ini1314
[Unit]1314
[Unit]1315
Description=Tile MMO Server1315
Description=Questward Server1316
After=network-online.target1316
After=network-online.target1317
Wants=network-online.target1317
Wants=network-online.target1318
1318
1319
[Service]1319
[Service]1320
Type=simple1320
Type=simple1321
User=tilemmo1321
User=questward1322
Group=tilemmo1322
Group=questward1323
WorkingDirectory=/srv/tile-mmo/current1323
WorkingDirectory=/srv/questward/current1324
1324
1325
# This hook checks the restart manifest. It pulls/builds only when an1325
# This hook checks the restart manifest. It pulls/builds only when an1326
# intentional deployment was requested. Prefixing with '+' optionally1326
# intentional deployment was requested. Prefixing with '+' optionally1327
# allows the hook to run with privileges different from the game user.1327
# allows the hook to run with privileges different from the game user.1328
ExecStartPre=+/usr/local/sbin/tile-mmo-update-if-requested1328
ExecStartPre=+/usr/local/sbin/questward-update-if-requested1329
ExecStart=/usr/bin/node /srv/tile-mmo/current/dist/server.js1329
ExecStart=/usr/bin/node /srv/questward/current/dist/server.js1330
1330
1331
Restart=always1331
Restart=always1332
RestartSec=5s1332
RestartSec=5s@@ -1338,7 +1338,7 @@ WantedBy=multi-user.target1338
```1338
```1339
1339
1340
`Restart=always` is appropriate here because an explicit1340
`Restart=always` is appropriate here because an explicit1341
`systemctl stop tile-mmo` does not cause systemd to restart the unit,1341
`systemctl stop questward` does not cause systemd to restart the unit,1342
while a clean in-game restart exit and an unexpected crash both do.1342
while a clean in-game restart exit and an unexpected crash both do.1343
1343
1344
The exact paths, build command and privilege split are deployment1344
The exact paths, build command and privilege split are deployment@@ -0,0 +1,112 @@
1
export class AuthClient
2
{
3
constructor (config)
4
{
5
this.config = config;
6
this.cache = new Map();
7
}
8
9
async exchangeCode ({ code, redirectUri })
10
{
11
const body = new URLSearchParams({
12
grant_type: "authorization_code",
13
code,
14
redirect_uri: redirectUri,
15
client_id: this.config.clientId,
16
client_secret: this.config.clientSecret
17
});
18
const response = await fetch(`${this.config.baseUrl}/oauth/token`, {
19
method: "POST",
20
headers: {
21
"Content-Type": "application/x-www-form-urlencoded",
22
"Accept": "application/json",
23
"User-Agent": this.config.userAgent
24
},
25
body
26
});
27
const payload = await response.json().catch(() => ({}));
28
if (!response.ok)
29
{
30
const error = new Error(payload.error ?? "Token exchange failed.");
31
error.status = response.status;
32
throw error;
33
}
34
return payload;
35
}
36
37
async fetchMe (accessToken)
38
{
39
const cached = this.cache.get(accessToken);
40
if (cached && cached.expiresAt > Date.now())
41
{ return cached.user; }
42
43
const response = await fetch(`${this.config.baseUrl}/api/me`, {
44
headers: {
45
"Authorization": `Bearer ${accessToken}`,
46
"Accept": "application/json",
47
"User-Agent": this.config.userAgent
48
}
49
});
50
const payload = await response.json().catch(() => ({}));
51
if (!response.ok)
52
{
53
this.cache.delete(accessToken);
54
return null;
55
}
56
const user = payload.user ?? null;
57
if (user)
58
{
59
this.cache.set(accessToken, {
60
user,
61
expiresAt: Date.now() + 60_000
62
});
63
}
64
return user;
65
}
66
67
async extendSession (accessToken)
68
{
69
const response = await fetch(`${this.config.baseUrl}/api/session/extend`, {
70
method: "POST",
71
headers: {
72
"Authorization": `Bearer ${accessToken}`,
73
"Accept": "application/json",
74
"User-Agent": this.config.userAgent
75
}
76
});
77
if (!response.ok)
78
{ return false; }
79
this.cache.delete(accessToken);
80
return true;
81
}
82
83
async revokeToken (accessToken)
84
{
85
this.cache.delete(accessToken);
86
if (!accessToken)
87
{ return; }
88
await fetch(`${this.config.baseUrl}/api/logout`, {
89
method: "POST",
90
headers: {
91
"Authorization": `Bearer ${accessToken}`,
92
"Accept": "application/json",
93
"User-Agent": this.config.userAgent
94
}
95
}).catch(() => {});
96
}
97
}
98
99
export function authSubjectForUser (user)
100
{
101
return `auth:${user.id}`;
102
}
103
104
export function identityFromUser (user, accessToken = null)
105
{
106
return {
107
authSubject: authSubjectForUser(user),
108
email: user.email ?? null,
109
username: user.username ?? null,
110
accessToken
111
};
112
}
@@ -0,0 +1,112 @@1
export class AuthClient2
{3
constructor (config)4
{5
this.config = config;6
this.cache = new Map();7
}8
9
async exchangeCode ({ code, redirectUri })10
{11
const body = new URLSearchParams({12
grant_type: "authorization_code",13
code,14
redirect_uri: redirectUri,15
client_id: this.config.clientId,16
client_secret: this.config.clientSecret17
});18
const response = await fetch(`${this.config.baseUrl}/oauth/token`, {19
method: "POST",20
headers: {21
"Content-Type": "application/x-www-form-urlencoded",22
"Accept": "application/json",23
"User-Agent": this.config.userAgent24
},25
body26
});27
const payload = await response.json().catch(() => ({}));28
if (!response.ok)29
{30
const error = new Error(payload.error ?? "Token exchange failed.");31
error.status = response.status;32
throw error;33
}34
return payload;35
}36
37
async fetchMe (accessToken)38
{39
const cached = this.cache.get(accessToken);40
if (cached && cached.expiresAt > Date.now())41
{ return cached.user; }42
43
const response = await fetch(`${this.config.baseUrl}/api/me`, {44
headers: {45
"Authorization": `Bearer ${accessToken}`,46
"Accept": "application/json",47
"User-Agent": this.config.userAgent48
}49
});50
const payload = await response.json().catch(() => ({}));51
if (!response.ok)52
{53
this.cache.delete(accessToken);54
return null;55
}56
const user = payload.user ?? null;57
if (user)58
{59
this.cache.set(accessToken, {60
user,61
expiresAt: Date.now() + 60_00062
});63
}64
return user;65
}66
67
async extendSession (accessToken)68
{69
const response = await fetch(`${this.config.baseUrl}/api/session/extend`, {70
method: "POST",71
headers: {72
"Authorization": `Bearer ${accessToken}`,73
"Accept": "application/json",74
"User-Agent": this.config.userAgent75
}76
});77
if (!response.ok)78
{ return false; }79
this.cache.delete(accessToken);80
return true;81
}82
83
async revokeToken (accessToken)84
{85
this.cache.delete(accessToken);86
if (!accessToken)87
{ return; }88
await fetch(`${this.config.baseUrl}/api/logout`, {89
method: "POST",90
headers: {91
"Authorization": `Bearer ${accessToken}`,92
"Accept": "application/json",93
"User-Agent": this.config.userAgent94
}95
}).catch(() => {});96
}97
}98
99
export function authSubjectForUser (user)100
{101
return `auth:${user.id}`;102
}103
104
export function identityFromUser (user, accessToken = null)105
{106
return {107
authSubject: authSubjectForUser(user),108
email: user.email ?? null,109
username: user.username ?? null,110
accessToken111
};112
}@@ -0,0 +1,22 @@
1
export function authConfig ()
2
{
3
const clientSecret = process.env.QUESTWARD_AUTH_CLIENT_SECRET
4
?? process.env.TILE_MMO_AUTH_CLIENT_SECRET
5
?? "";
6
7
return Object.freeze({
8
stub: process.env.QUESTWARD_AUTH_STUB === "1",
9
baseUrl: (process.env.QUESTWARD_AUTH_URL ?? "https://auth.timfalken.com").replace(/\/$/, ""),
10
clientId: process.env.QUESTWARD_AUTH_CLIENT_ID ?? "timfalken.com",
11
clientSecret,
12
redirectUri: process.env.QUESTWARD_AUTH_REDIRECT_URI ?? "",
13
tokenCookie: "questward_access_token",
14
stateCookie: "questward_oauth_state",
15
userAgent: "QuestwardServer/1.0"
16
});
17
}
18
19
export function useAuthStub (config)
20
{
21
return config.stub || !config.clientSecret;
22
}
@@ -0,0 +1,22 @@1
export function authConfig ()2
{3
const clientSecret = process.env.QUESTWARD_AUTH_CLIENT_SECRET4
?? process.env.TILE_MMO_AUTH_CLIENT_SECRET5
?? "";6
7
return Object.freeze({8
stub: process.env.QUESTWARD_AUTH_STUB === "1",9
baseUrl: (process.env.QUESTWARD_AUTH_URL ?? "https://auth.timfalken.com").replace(/\/$/, ""),10
clientId: process.env.QUESTWARD_AUTH_CLIENT_ID ?? "timfalken.com",11
clientSecret,12
redirectUri: process.env.QUESTWARD_AUTH_REDIRECT_URI ?? "",13
tokenCookie: "questward_access_token",14
stateCookie: "questward_oauth_state",15
userAgent: "QuestwardServer/1.0"16
});17
}18
19
export function useAuthStub (config)20
{21
return config.stub || !config.clientSecret;22
}@@ -0,0 +1,55 @@
1
export function parseCookies (header)
2
{
3
const out = Object.create(null);
4
if (!header)
5
{ return out; }
6
for (const part of String(header).split(";"))
7
{
8
const trimmed = part.trim();
9
if (!trimmed)
10
{ continue; }
11
const eq = trimmed.indexOf("=");
12
if (eq <= 0)
13
{ continue; }
14
const key = trimmed.slice(0, eq);
15
const value = trimmed.slice(eq + 1);
16
out[key] = decodeURIComponent(value);
17
}
18
return out;
19
}
20
21
export function publicOrigin (req)
22
{
23
const host = req.headers["x-forwarded-host"] ?? req.headers.host ?? "localhost";
24
const proto = req.headers["x-forwarded-proto"] ?? "http";
25
return `${proto}://${host}`;
26
}
27
28
export function isSecureRequest (req)
29
{
30
const proto = req.headers["x-forwarded-proto"];
31
if (proto)
32
{ return proto === "https"; }
33
return false;
34
}
35
36
export function setCookie (res, name, value, { maxAgeSec, httpOnly = true, sameSite = "Lax", secure = false, path = "/" } = {})
37
{
38
const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${path}`, `SameSite=${sameSite}`];
39
if (httpOnly)
40
{ parts.push("HttpOnly"); }
41
if (secure)
42
{ parts.push("Secure"); }
43
if (maxAgeSec != null)
44
{ parts.push(`Max-Age=${maxAgeSec}`); }
45
res.appendHeader("Set-Cookie", parts.join("; "));
46
}
47
48
export function clearCookie (res, name, { secure = false, path = "/" } = {})
49
{
50
const parts = [`${name}=`, `Path=${path}`, "Max-Age=0", "SameSite=Lax"];
51
parts.push("HttpOnly");
52
if (secure)
53
{ parts.push("Secure"); }
54
res.appendHeader("Set-Cookie", parts.join("; "));
55
}
@@ -0,0 +1,55 @@1
export function parseCookies (header)2
{3
const out = Object.create(null);4
if (!header)5
{ return out; }6
for (const part of String(header).split(";"))7
{8
const trimmed = part.trim();9
if (!trimmed)10
{ continue; }11
const eq = trimmed.indexOf("=");12
if (eq <= 0)13
{ continue; }14
const key = trimmed.slice(0, eq);15
const value = trimmed.slice(eq + 1);16
out[key] = decodeURIComponent(value);17
}18
return out;19
}20
21
export function publicOrigin (req)22
{23
const host = req.headers["x-forwarded-host"] ?? req.headers.host ?? "localhost";24
const proto = req.headers["x-forwarded-proto"] ?? "http";25
return `${proto}://${host}`;26
}27
28
export function isSecureRequest (req)29
{30
const proto = req.headers["x-forwarded-proto"];31
if (proto)32
{ return proto === "https"; }33
return false;34
}35
36
export function setCookie (res, name, value, { maxAgeSec, httpOnly = true, sameSite = "Lax", secure = false, path = "/" } = {})37
{38
const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${path}`, `SameSite=${sameSite}`];39
if (httpOnly)40
{ parts.push("HttpOnly"); }41
if (secure)42
{ parts.push("Secure"); }43
if (maxAgeSec != null)44
{ parts.push(`Max-Age=${maxAgeSec}`); }45
res.appendHeader("Set-Cookie", parts.join("; "));46
}47
48
export function clearCookie (res, name, { secure = false, path = "/" } = {})49
{50
const parts = [`${name}=`, `Path=${path}`, "Max-Age=0", "SameSite=Lax"];51
parts.push("HttpOnly");52
if (secure)53
{ parts.push("Secure"); }54
res.appendHeader("Set-Cookie", parts.join("; "));55
}@@ -0,0 +1,34 @@
1
import { publicCharacter } from "../characters/service.js";
2
3
export function buildAccountDataExport ({ stateDb }, account)
4
{
5
const characterRows = stateDb.listCharacters(account.account_id);
6
const exportedCharacters = characterRows.map((row) =>
7
{
8
const bag = stateDb.getBag(row.character_id);
9
const skills = stateDb.getSkills(row.character_id);
10
const spells = stateDb.getSpells(row.character_id);
11
return {
12
...publicCharacter(row),
13
inventory: bag?.inventory ?? [],
14
equipment: bag?.equipment ?? {},
15
currency: bag?.currency ?? 0,
16
vault: bag?.vault ?? [],
17
vaultReserved: bag?.vaultReserved ?? [],
18
skills,
19
spells
20
};
21
});
22
23
return {
24
exported_at: new Date().toISOString(),
25
account: {
26
authSubject: account.auth_subject,
27
username: account.username ?? null,
28
email: account.email ?? null,
29
isAdmin: !!account.is_admin
30
},
31
characters: exportedCharacters,
32
inheritance: stateDb.getInheritance(account.account_id)
33
};
34
}
@@ -0,0 +1,34 @@1
import { publicCharacter } from "../characters/service.js";2
3
export function buildAccountDataExport ({ stateDb }, account)4
{5
const characterRows = stateDb.listCharacters(account.account_id);6
const exportedCharacters = characterRows.map((row) =>7
{8
const bag = stateDb.getBag(row.character_id);9
const skills = stateDb.getSkills(row.character_id);10
const spells = stateDb.getSpells(row.character_id);11
return {12
...publicCharacter(row),13
inventory: bag?.inventory ?? [],14
equipment: bag?.equipment ?? {},15
currency: bag?.currency ?? 0,16
vault: bag?.vault ?? [],17
vaultReserved: bag?.vaultReserved ?? [],18
skills,19
spells20
};21
});22
23
return {24
exported_at: new Date().toISOString(),25
account: {26
authSubject: account.auth_subject,27
username: account.username ?? null,28
email: account.email ?? null,29
isAdmin: !!account.is_admin30
},31
characters: exportedCharacters,32
inheritance: stateDb.getInheritance(account.account_id)33
};34
}@@ -0,0 +1,17 @@
1
import { authConfig, useAuthStub } from "./config.js";
2
import { StubAuth } from "./stub.js";
3
import { OAuthAuth } from "./oauth.js";
4
5
export function createAuth ()
6
{
7
const config = authConfig();
8
if (useAuthStub(config))
9
{
10
console.log("[auth] Using stub identities (set QUESTWARD_AUTH_CLIENT_SECRET for auth.timfalken.com).");
11
return new StubAuth();
12
}
13
console.log(`[auth] OAuth via ${config.baseUrl} (client_id=${config.clientId}).`);
14
return new OAuthAuth(config);
15
}
16
17
export { authConfig, useAuthStub };
@@ -0,0 +1,17 @@1
import { authConfig, useAuthStub } from "./config.js";2
import { StubAuth } from "./stub.js";3
import { OAuthAuth } from "./oauth.js";4
5
export function createAuth ()6
{7
const config = authConfig();8
if (useAuthStub(config))9
{10
console.log("[auth] Using stub identities (set QUESTWARD_AUTH_CLIENT_SECRET for auth.timfalken.com).");11
return new StubAuth();12
}13
console.log(`[auth] OAuth via ${config.baseUrl} (client_id=${config.clientId}).`);14
return new OAuthAuth(config);15
}16
17
export { authConfig, useAuthStub };@@ -0,0 +1,161 @@
1
import { randomBytes } from "node:crypto";
2
import { AuthClient, authSubjectForUser, identityFromUser } from "./client.js";
3
import { parseCookies, publicOrigin, isSecureRequest, setCookie, clearCookie } from "./cookies.js";
4
5
const EXTEND_INTERVAL_MS = 45 * 60 * 1000;
6
7
export class OAuthAuth
8
{
9
constructor (config, client = new AuthClient(config))
10
{
11
this.config = config;
12
this.client = client;
13
this.sessions = new Set();
14
}
15
16
register (session)
17
{
18
this.sessions.add(session);
19
}
20
21
release (session)
22
{
23
this.sessions.delete(session);
24
if (session.extendTimer)
25
{
26
clearInterval(session.extendTimer);
27
session.extendTimer = null;
28
}
29
}
30
31
redirectUriFor (req)
32
{
33
if (this.config.redirectUri)
34
{ return this.config.redirectUri; }
35
return `${publicOrigin(req)}/auth/callback`;
36
}
37
38
beginLogin (req, res, returnTo = "/")
39
{
40
const state = randomBytes(24).toString("hex");
41
const secure = isSecureRequest(req);
42
setCookie(res, this.config.stateCookie, state, {
43
maxAgeSec: 600,
44
secure,
45
httpOnly: true
46
});
47
setCookie(res, "questward_return_to", safeReturnTo(returnTo), {
48
maxAgeSec: 600,
49
secure,
50
httpOnly: true
51
});
52
const redirectUri = encodeURIComponent(this.redirectUriFor(req));
53
const clientId = encodeURIComponent(this.config.clientId);
54
const location = `${this.config.baseUrl}/oauth/authorize`
55
+ `?client_id=${clientId}`
56
+ `&redirect_uri=${redirectUri}`
57
+ `&response_type=code`
58
+ `&state=${state}`;
59
res.writeHead(302, { Location: location });
60
res.end();
61
}
62
63
async finishLogin (req, res)
64
{
65
const url = new URL(req.url ?? "/", publicOrigin(req));
66
const code = url.searchParams.get("code");
67
const state = url.searchParams.get("state");
68
const secure = isSecureRequest(req);
69
const cookies = parseCookies(req.headers.cookie);
70
const expectedState = cookies[this.config.stateCookie];
71
const returnTo = safeReturnTo(cookies.questward_return_to ?? "/");
72
clearCookie(res, this.config.stateCookie, { secure });
73
clearCookie(res, "questward_return_to", { secure });
74
75
if (!code || !state || !expectedState || state !== expectedState)
76
{
77
res.writeHead(302, { Location: `/auth/error?message=${encodeURIComponent("Sign-in failed. Please try again.")}` });
78
res.end();
79
return;
80
}
81
82
try
83
{
84
const tokenPayload = await this.client.exchangeCode({
85
code,
86
redirectUri: this.redirectUriFor(req)
87
});
88
setCookie(res, this.config.tokenCookie, tokenPayload.access_token, {
89
maxAgeSec: tokenPayload.expires_in ?? 3600,
90
secure,
91
httpOnly: true
92
});
93
res.writeHead(302, { Location: returnTo });
94
res.end();
95
}
96
catch (error)
97
{
98
res.writeHead(302, {
99
Location: `/auth/error?message=${encodeURIComponent(error.message ?? "Sign-in failed.")}`
100
});
101
res.end();
102
}
103
}
104
105
async logout (req, res, returnTo = "/")
106
{
107
const secure = isSecureRequest(req);
108
const cookies = parseCookies(req.headers.cookie);
109
const token = cookies[this.config.tokenCookie];
110
await this.client.revokeToken(token);
111
clearCookie(res, this.config.tokenCookie, { secure });
112
res.writeHead(302, { Location: safeReturnTo(returnTo) });
113
res.end();
114
}
115
116
async statusFromRequest (req)
117
{
118
const identity = await this.authenticateRequest(req);
119
if (!identity)
120
{ return { authenticated: false }; }
121
return {
122
authenticated: true,
123
authSubject: identity.authSubject,
124
username: identity.username,
125
email: identity.email
126
};
127
}
128
129
async authenticateRequest (req)
130
{
131
const cookies = parseCookies(req.headers.cookie);
132
const token = cookies[this.config.tokenCookie];
133
if (!token)
134
{ return null; }
135
const user = await this.client.fetchMe(token);
136
if (!user)
137
{ return null; }
138
return identityFromUser(user, token);
139
}
140
141
startSessionMaintenance (session)
142
{
143
if (!session.accessToken)
144
{ return; }
145
session.extendTimer = setInterval(() =>
146
{
147
void this.client.extendSession(session.accessToken);
148
}, EXTEND_INTERVAL_MS);
149
if (typeof session.extendTimer.unref === "function")
150
{ session.extendTimer.unref(); }
151
}
152
}
153
154
function safeReturnTo (value)
155
{
156
if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//"))
157
{ return "/"; }
158
return value;
159
}
160
161
export { authSubjectForUser, identityFromUser };
@@ -0,0 +1,161 @@1
import { randomBytes } from "node:crypto";2
import { AuthClient, authSubjectForUser, identityFromUser } from "./client.js";3
import { parseCookies, publicOrigin, isSecureRequest, setCookie, clearCookie } from "./cookies.js";4
5
const EXTEND_INTERVAL_MS = 45 * 60 * 1000;6
7
export class OAuthAuth8
{9
constructor (config, client = new AuthClient(config))10
{11
this.config = config;12
this.client = client;13
this.sessions = new Set();14
}15
16
register (session)17
{18
this.sessions.add(session);19
}20
21
release (session)22
{23
this.sessions.delete(session);24
if (session.extendTimer)25
{26
clearInterval(session.extendTimer);27
session.extendTimer = null;28
}29
}30
31
redirectUriFor (req)32
{33
if (this.config.redirectUri)34
{ return this.config.redirectUri; }35
return `${publicOrigin(req)}/auth/callback`;36
}37
38
beginLogin (req, res, returnTo = "/")39
{40
const state = randomBytes(24).toString("hex");41
const secure = isSecureRequest(req);42
setCookie(res, this.config.stateCookie, state, {43
maxAgeSec: 600,44
secure,45
httpOnly: true46
});47
setCookie(res, "questward_return_to", safeReturnTo(returnTo), {48
maxAgeSec: 600,49
secure,50
httpOnly: true51
});52
const redirectUri = encodeURIComponent(this.redirectUriFor(req));53
const clientId = encodeURIComponent(this.config.clientId);54
const location = `${this.config.baseUrl}/oauth/authorize`55
+ `?client_id=${clientId}`56
+ `&redirect_uri=${redirectUri}`57
+ `&response_type=code`58
+ `&state=${state}`;59
res.writeHead(302, { Location: location });60
res.end();61
}62
63
async finishLogin (req, res)64
{65
const url = new URL(req.url ?? "/", publicOrigin(req));66
const code = url.searchParams.get("code");67
const state = url.searchParams.get("state");68
const secure = isSecureRequest(req);69
const cookies = parseCookies(req.headers.cookie);70
const expectedState = cookies[this.config.stateCookie];71
const returnTo = safeReturnTo(cookies.questward_return_to ?? "/");72
clearCookie(res, this.config.stateCookie, { secure });73
clearCookie(res, "questward_return_to", { secure });74
75
if (!code || !state || !expectedState || state !== expectedState)76
{77
res.writeHead(302, { Location: `/auth/error?message=${encodeURIComponent("Sign-in failed. Please try again.")}` });78
res.end();79
return;80
}81
82
try83
{84
const tokenPayload = await this.client.exchangeCode({85
code,86
redirectUri: this.redirectUriFor(req)87
});88
setCookie(res, this.config.tokenCookie, tokenPayload.access_token, {89
maxAgeSec: tokenPayload.expires_in ?? 3600,90
secure,91
httpOnly: true92
});93
res.writeHead(302, { Location: returnTo });94
res.end();95
}96
catch (error)97
{98
res.writeHead(302, {99
Location: `/auth/error?message=${encodeURIComponent(error.message ?? "Sign-in failed.")}`100
});101
res.end();102
}103
}104
105
async logout (req, res, returnTo = "/")106
{107
const secure = isSecureRequest(req);108
const cookies = parseCookies(req.headers.cookie);109
const token = cookies[this.config.tokenCookie];110
await this.client.revokeToken(token);111
clearCookie(res, this.config.tokenCookie, { secure });112
res.writeHead(302, { Location: safeReturnTo(returnTo) });113
res.end();114
}115
116
async statusFromRequest (req)117
{118
const identity = await this.authenticateRequest(req);119
if (!identity)120
{ return { authenticated: false }; }121
return {122
authenticated: true,123
authSubject: identity.authSubject,124
username: identity.username,125
email: identity.email126
};127
}128
129
async authenticateRequest (req)130
{131
const cookies = parseCookies(req.headers.cookie);132
const token = cookies[this.config.tokenCookie];133
if (!token)134
{ return null; }135
const user = await this.client.fetchMe(token);136
if (!user)137
{ return null; }138
return identityFromUser(user, token);139
}140
141
startSessionMaintenance (session)142
{143
if (!session.accessToken)144
{ return; }145
session.extendTimer = setInterval(() =>146
{147
void this.client.extendSession(session.accessToken);148
}, EXTEND_INTERVAL_MS);149
if (typeof session.extendTimer.unref === "function")150
{ session.extendTimer.unref(); }151
}152
}153
154
function safeReturnTo (value)155
{156
if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//"))157
{ return "/"; }158
return value;159
}160
161
export { authSubjectForUser, identityFromUser };@@ -0,0 +1,119 @@
1
import { buildAccountDataExport } from "./dataExport.js";
2
3
export async function handleAuthRoute (req, res, url, { auth, stateDb })
4
{
5
try
6
{
7
if (url.pathname === "/auth/status" && req.method === "GET")
8
{
9
const status = await auth.statusFromRequest(req);
10
sendJson(res, 200, status);
11
return true;
12
}
13
14
if (url.pathname === "/auth/login" && req.method === "GET")
15
{
16
if (typeof auth.beginLogin !== "function")
17
{
18
sendText(res, 501, "OAuth login is not configured.");
19
return true;
20
}
21
auth.beginLogin(req, res, url.searchParams.get("return_to") ?? "/");
22
return true;
23
}
24
25
if (url.pathname === "/auth/callback" && req.method === "GET")
26
{
27
if (typeof auth.finishLogin !== "function")
28
{
29
sendText(res, 501, "OAuth login is not configured.");
30
return true;
31
}
32
await auth.finishLogin(req, res);
33
return true;
34
}
35
36
if (url.pathname === "/auth/logout" && (req.method === "GET" || req.method === "POST"))
37
{
38
const returnTo = url.searchParams.get("return_to") ?? "/";
39
if (typeof auth.logout === "function")
40
{ await auth.logout(req, res, returnTo); }
41
else
42
{
43
res.writeHead(302, { Location: returnTo });
44
res.end();
45
}
46
return true;
47
}
48
49
if (url.pathname === "/auth/error" && req.method === "GET")
50
{
51
const message = url.searchParams.get("message") ?? "Sign-in failed.";
52
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
53
res.end(`<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Sign-in failed</title></head>`
54
+ `<body><main><h1>Sign-in failed</h1><p>${escapeHtml(message)}</p>`
55
+ `<p><a href="/auth/login">Try again</a></p></main></body></html>`);
56
return true;
57
}
58
59
if (url.pathname === "/settings/export" && req.method === "GET")
60
{
61
const identity = await auth.authenticateRequest(req);
62
if (!identity)
63
{
64
sendJson(res, 401, { error: "Sign in required." });
65
return true;
66
}
67
const account = stateDb.getAccountBySubject(identity.authSubject);
68
if (!account)
69
{
70
sendJson(res, 404, { error: "Account not found." });
71
return true;
72
}
73
const payload = buildAccountDataExport({ stateDb }, account);
74
res.writeHead(200, {
75
"content-type": "application/json; charset=utf-8",
76
"content-disposition": 'attachment; filename="questward-data-export.json"'
77
});
78
res.end(JSON.stringify(payload, null, 2));
79
return true;
80
}
81
82
return false;
83
}
84
catch (error)
85
{
86
sendJson(res, 500, { error: error.message ?? "Auth route failed." });
87
return true;
88
}
89
}
90
91
export async function resolveAccount (stateDb, identity)
92
{
93
return stateDb.resolveAccountFromAuth({
94
authSubject: identity.authSubject,
95
email: identity.email ?? null,
96
username: identity.username ?? null
97
});
98
}
99
100
function sendJson (res, status, body)
101
{
102
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
103
res.end(JSON.stringify(body));
104
}
105
106
function sendText (res, status, text)
107
{
108
res.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
109
res.end(text);
110
}
111
112
function escapeHtml (text)
113
{
114
return String(text)
115
.replaceAll("&", "&")
116
.replaceAll("<", "<")
117
.replaceAll(">", ">")
118
.replaceAll("\"", """);
119
}
@@ -0,0 +1,119 @@1
import { buildAccountDataExport } from "./dataExport.js";2
3
export async function handleAuthRoute (req, res, url, { auth, stateDb })4
{5
try6
{7
if (url.pathname === "/auth/status" && req.method === "GET")8
{9
const status = await auth.statusFromRequest(req);10
sendJson(res, 200, status);11
return true;12
}13
14
if (url.pathname === "/auth/login" && req.method === "GET")15
{16
if (typeof auth.beginLogin !== "function")17
{18
sendText(res, 501, "OAuth login is not configured.");19
return true;20
}21
auth.beginLogin(req, res, url.searchParams.get("return_to") ?? "/");22
return true;23
}24
25
if (url.pathname === "/auth/callback" && req.method === "GET")26
{27
if (typeof auth.finishLogin !== "function")28
{29
sendText(res, 501, "OAuth login is not configured.");30
return true;31
}32
await auth.finishLogin(req, res);33
return true;34
}35
36
if (url.pathname === "/auth/logout" && (req.method === "GET" || req.method === "POST"))37
{38
const returnTo = url.searchParams.get("return_to") ?? "/";39
if (typeof auth.logout === "function")40
{ await auth.logout(req, res, returnTo); }41
else42
{43
res.writeHead(302, { Location: returnTo });44
res.end();45
}46
return true;47
}48
49
if (url.pathname === "/auth/error" && req.method === "GET")50
{51
const message = url.searchParams.get("message") ?? "Sign-in failed.";52
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });53
res.end(`<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Sign-in failed</title></head>`54
+ `<body><main><h1>Sign-in failed</h1><p>${escapeHtml(message)}</p>`55
+ `<p><a href="/auth/login">Try again</a></p></main></body></html>`);56
return true;57
}58
59
if (url.pathname === "/settings/export" && req.method === "GET")60
{61
const identity = await auth.authenticateRequest(req);62
if (!identity)63
{64
sendJson(res, 401, { error: "Sign in required." });65
return true;66
}67
const account = stateDb.getAccountBySubject(identity.authSubject);68
if (!account)69
{70
sendJson(res, 404, { error: "Account not found." });71
return true;72
}73
const payload = buildAccountDataExport({ stateDb }, account);74
res.writeHead(200, {75
"content-type": "application/json; charset=utf-8",76
"content-disposition": 'attachment; filename="questward-data-export.json"'77
});78
res.end(JSON.stringify(payload, null, 2));79
return true;80
}81
82
return false;83
}84
catch (error)85
{86
sendJson(res, 500, { error: error.message ?? "Auth route failed." });87
return true;88
}89
}90
91
export async function resolveAccount (stateDb, identity)92
{93
return stateDb.resolveAccountFromAuth({94
authSubject: identity.authSubject,95
email: identity.email ?? null,96
username: identity.username ?? null97
});98
}99
100
function sendJson (res, status, body)101
{102
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });103
res.end(JSON.stringify(body));104
}105
106
function sendText (res, status, text)107
{108
res.writeHead(status, { "content-type": "text/plain; charset=utf-8" });109
res.end(text);110
}111
112
function escapeHtml (text)113
{114
return String(text)115
.replaceAll("&", "&")116
.replaceAll("<", "<")117
.replaceAll(">", ">")118
.replaceAll("\"", """);119
}@@ -22,7 +22,27 @@ export class StubAuth
22
22
return {
23
23
authSubject: `admin-${n}`,
24
24
isAdmin: true,
25
email: null
25
email: null,
26
username: `admin-${n}`,
27
accessToken: null,
28
stub: true
29
};
30
}
31
32
async authenticateRequest (_req)
33
{
34
return this.claimIdentity();
35
}
36
37
async statusFromRequest (_req)
38
{
39
const identity = this.claimIdentity();
40
return {
41
authenticated: true,
42
authSubject: identity.authSubject,
43
username: identity.username,
44
email: identity.email,
45
stub: true
26
46
};
27
47
}
28
48
@@ -35,4 +55,9 @@ export class StubAuth
35
55
{
36
56
this.sessions.delete(session);
37
57
}
58
59
startSessionMaintenance (_session)
60
{
61
// no-op
62
}
38
63
}
@@ -22,7 +22,27 @@ export class StubAuth22
return {22
return {23
authSubject: `admin-${n}`,23
authSubject: `admin-${n}`,24
isAdmin: true,24
isAdmin: true,25
email: null25
email: null,26
username: `admin-${n}`,27
accessToken: null,28
stub: true29
};30
}31
32
async authenticateRequest (_req)33
{34
return this.claimIdentity();35
}36
37
async statusFromRequest (_req)38
{39
const identity = this.claimIdentity();40
return {41
authenticated: true,42
authSubject: identity.authSubject,43
username: identity.username,44
email: identity.email,45
stub: true26
};46
};27
}47
}28
48
@@ -35,4 +55,9 @@ export class StubAuth35
{55
{36
this.sessions.delete(session);56
this.sessions.delete(session);37
}57
}58
59
startSessionMaintenance (_session)60
{61
// no-op62
}38
}63
}@@ -28,13 +28,21 @@ export class DeployScheduler
28
28
constructor (options)
29
29
{
30
30
this.repoRoot = options.repoRoot;
31
this.branch = options.branch ?? process.env.TILE_MMO_GIT_BRANCH ?? "master";
31
this.branch = options.branch
32
?? process.env.QUESTWARD_GIT_BRANCH
33
?? process.env.TILE_MMO_GIT_BRANCH
34
?? "master";
32
35
this.checkIntervalMs = Math.max(
33
36
30_000,
34
Number(options.checkIntervalMs ?? process.env.TILE_MMO_DEPLOY_CHECK_MS) || DEFAULT_DEPLOY_CHECK_MS
37
Number(
38
options.checkIntervalMs
39
?? process.env.QUESTWARD_DEPLOY_CHECK_MS
40
?? process.env.TILE_MMO_DEPLOY_CHECK_MS
41
) || DEFAULT_DEPLOY_CHECK_MS
35
42
);
36
43
this.warnBeforeMs = options.warnBeforeMs ?? RESTART_WARN_BEFORE_MS;
37
this.enabled = options.enabled ?? process.env.TILE_MMO_DEPLOY_SCHEDULER !== "0";
44
this.enabled = options.enabled
45
?? (process.env.QUESTWARD_DEPLOY_SCHEDULER ?? process.env.TILE_MMO_DEPLOY_SCHEDULER) !== "0";
38
46
this.now = options.now ?? (() => Date.now());
39
47
this.checkRemote = options.checkRemote ?? checkGitRemoteAhead;
40
48
this.onStatusChange = options.onStatusChange ?? (() => {});
@@ -28,13 +28,21 @@ export class DeployScheduler28
constructor (options)28
constructor (options)29
{29
{30
this.repoRoot = options.repoRoot;30
this.repoRoot = options.repoRoot;31
this.branch = options.branch ?? process.env.TILE_MMO_GIT_BRANCH ?? "master";31
this.branch = options.branch32
?? process.env.QUESTWARD_GIT_BRANCH33
?? process.env.TILE_MMO_GIT_BRANCH34
?? "master";32
this.checkIntervalMs = Math.max(35
this.checkIntervalMs = Math.max(33
30_000,36
30_000,34
Number(options.checkIntervalMs ?? process.env.TILE_MMO_DEPLOY_CHECK_MS) || DEFAULT_DEPLOY_CHECK_MS37
Number(38
options.checkIntervalMs39
?? process.env.QUESTWARD_DEPLOY_CHECK_MS40
?? process.env.TILE_MMO_DEPLOY_CHECK_MS41
) || DEFAULT_DEPLOY_CHECK_MS35
);42
);36
this.warnBeforeMs = options.warnBeforeMs ?? RESTART_WARN_BEFORE_MS;43
this.warnBeforeMs = options.warnBeforeMs ?? RESTART_WARN_BEFORE_MS;37
this.enabled = options.enabled ?? process.env.TILE_MMO_DEPLOY_SCHEDULER !== "0";44
this.enabled = options.enabled45
?? (process.env.QUESTWARD_DEPLOY_SCHEDULER ?? process.env.TILE_MMO_DEPLOY_SCHEDULER) !== "0";38
this.now = options.now ?? (() => Date.now());46
this.now = options.now ?? (() => Date.now());39
this.checkRemote = options.checkRemote ?? checkGitRemoteAhead;47
this.checkRemote = options.checkRemote ?? checkGitRemoteAhead;40
this.onStatusChange = options.onStatusChange ?? (() => {});48
this.onStatusChange = options.onStatusChange ?? (() => {});@@ -3,6 +3,7 @@ import { createReadStream, existsSync, statSync } from "node:fs";
3
3
import { extname, join, normalize, relative, sep } from "node:path";
4
4
import { fileURLToPath } from "node:url";
5
5
import { buildSpriteCatalog } from "../assets/spriteCatalog.js";
6
import { handleAuthRoute } from "../auth/routes.js";
6
7
7
8
const MIME = {
8
9
".html": "text/html; charset=utf-8",
@@ -14,7 +15,7 @@ const MIME = {
14
15
".ico": "image/x-icon"
15
16
};
16
17
17
export function createHttpServer (rootDir)
18
export function createHttpServer (rootDir, { auth = null, stateDb = null } = {})
18
19
{
19
20
const clientDir = join(rootDir, "client");
20
21
const sharedDir = join(rootDir, "shared");
@@ -22,30 +23,37 @@ export function createHttpServer (rootDir)
22
23
23
24
return createServer((req, res) =>
24
25
{
25
try
26
void handleRequest(req, res);
27
28
async function handleRequest (request, response)
26
29
{
27
const url = new URL(req.url ?? "/", "http://localhost");
28
if (url.pathname === "/assets/catalog.json")
30
try
29
31
{
30
const catalog = spriteCatalogFor(clientDir);
31
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
32
res.end(JSON.stringify(catalog));
33
return;
32
const url = new URL(request.url ?? "/", "http://localhost");
33
if (auth && stateDb && await handleAuthRoute(request, response, url, { auth, stateDb }))
34
{ return; }
35
if (url.pathname === "/assets/catalog.json")
36
{
37
const catalog = spriteCatalogFor(clientDir);
38
response.writeHead(200, { "content-type": "application/json; charset=utf-8" });
39
response.end(JSON.stringify(catalog));
40
return;
41
}
42
const filePath = resolvePublicPath(url.pathname, clientDir, sharedDir, frameworkDir);
43
if (!filePath)
44
{
45
response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
46
response.end("Not found");
47
return;
48
}
49
response.writeHead(200, { "content-type": MIME[extname(filePath)] ?? "application/octet-stream" });
50
createReadStream(filePath).pipe(response);
34
51
}
35
const filePath = resolvePublicPath(url.pathname, clientDir, sharedDir, frameworkDir);
36
if (!filePath)
52
catch (error)
37
53
{
38
res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
39
res.end("Not found");
40
return;
54
response.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
55
response.end(error.message);
41
56
}
42
res.writeHead(200, { "content-type": MIME[extname(filePath)] ?? "application/octet-stream" });
43
createReadStream(filePath).pipe(res);
44
}
45
catch (error)
46
{
47
res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
48
res.end(error.message);
49
57
}
50
58
});
51
59
}
@@ -3,6 +3,7 @@ import { createReadStream, existsSync, statSync } from "node:fs";3
import { extname, join, normalize, relative, sep } from "node:path";3
import { extname, join, normalize, relative, sep } from "node:path";4
import { fileURLToPath } from "node:url";4
import { fileURLToPath } from "node:url";5
import { buildSpriteCatalog } from "../assets/spriteCatalog.js";5
import { buildSpriteCatalog } from "../assets/spriteCatalog.js";6
import { handleAuthRoute } from "../auth/routes.js";6
7
7
const MIME = {8
const MIME = {8
".html": "text/html; charset=utf-8",9
".html": "text/html; charset=utf-8",@@ -14,7 +15,7 @@ const MIME = {14
".ico": "image/x-icon"15
".ico": "image/x-icon"15
};16
};16
17
17
export function createHttpServer (rootDir)18
export function createHttpServer (rootDir, { auth = null, stateDb = null } = {})18
{19
{19
const clientDir = join(rootDir, "client");20
const clientDir = join(rootDir, "client");20
const sharedDir = join(rootDir, "shared");21
const sharedDir = join(rootDir, "shared");@@ -22,30 +23,37 @@ export function createHttpServer (rootDir)22
23
23
return createServer((req, res) =>24
return createServer((req, res) =>24
{25
{25
try26
void handleRequest(req, res);27
28
async function handleRequest (request, response)26
{29
{27
const url = new URL(req.url ?? "/", "http://localhost");30
try28
if (url.pathname === "/assets/catalog.json")29
{31
{30
const catalog = spriteCatalogFor(clientDir);32
const url = new URL(request.url ?? "/", "http://localhost");31
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });33
if (auth && stateDb && await handleAuthRoute(request, response, url, { auth, stateDb }))32
res.end(JSON.stringify(catalog));34
{ return; }33
return;35
if (url.pathname === "/assets/catalog.json")36
{37
const catalog = spriteCatalogFor(clientDir);38
response.writeHead(200, { "content-type": "application/json; charset=utf-8" });39
response.end(JSON.stringify(catalog));40
return;41
}42
const filePath = resolvePublicPath(url.pathname, clientDir, sharedDir, frameworkDir);43
if (!filePath)44
{45
response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });46
response.end("Not found");47
return;48
}49
response.writeHead(200, { "content-type": MIME[extname(filePath)] ?? "application/octet-stream" });50
createReadStream(filePath).pipe(response);34
}51
}35
const filePath = resolvePublicPath(url.pathname, clientDir, sharedDir, frameworkDir);52
catch (error)36
if (!filePath)37
{53
{38
res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });54
response.writeHead(500, { "content-type": "text/plain; charset=utf-8" });39
res.end("Not found");55
response.end(error.message);40
return;41
}56
}42
res.writeHead(200, { "content-type": MIME[extname(filePath)] ?? "application/octet-stream" });43
createReadStream(filePath).pipe(res);44
}45
catch (error)46
{47
res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });48
res.end(error.message);49
}57
}50
});58
});51
}59
}@@ -32,15 +32,39 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
32
32
}
33
33
});
34
34
35
wss.on("connection", (socket) =>
35
wss.on("connection", (socket, req) =>
36
36
{
37
const identity = auth.claimIdentity();
38
const account = stateDb.ensureAccount(identity.authSubject, identity.isAdmin, identity.email);
37
void openSession(socket, req);
38
});
39
40
async function openSession (socket, req)
41
{
42
let identity;
43
try
44
{
45
identity = await auth.authenticateRequest(req);
46
}
47
catch
48
{
49
socket.close(1011, "Authentication failed.");
50
return;
51
}
52
if (!identity)
53
{
54
socket.close(4401, "Authentication required.");
55
return;
56
}
57
58
const account = identity.stub
59
? stateDb.ensureAccount(identity.authSubject, true, identity.email, identity.username)
60
: await resolveAccount(stateDb, identity);
39
61
const session = {
40
62
id: nextSessionId++,
41
63
socket,
42
64
account,
43
65
authSubject: identity.authSubject,
66
username: identity.username ?? account.username ?? null,
67
accessToken: identity.accessToken ?? null,
44
68
characterId: null,
45
69
entityId: null,
46
70
/** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */
@@ -52,11 +76,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
52
76
staticSubscribed: new Set()
53
77
};
54
78
auth.register(session);
79
auth.startSessionMaintenance?.(session);
55
80
sessions.set(session.id, session);
56
81
send(session, {
57
82
type: MessageType.session,
58
83
accountId: account.account_id,
59
84
authSubject: account.auth_subject,
85
username: session.username,
86
email: account.email ?? null,
60
87
isAdmin: !!account.is_admin,
61
88
characters: characters.list(account.account_id)
62
89
});
@@ -88,7 +115,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
88
115
auth.release(session);
89
116
sessions.delete(session.id);
90
117
});
91
});
118
}
92
119
93
120
function handleMessage (session, message)
94
121
{
@@ -828,6 +855,40 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
828
855
itemLastSales: simulation.itemLastSalesSnapshot?.() ?? {}
829
856
});
830
857
break;
858
case MessageType.editorLoadGameAdmins:
859
requireAdmin(session);
860
send(session, {
861
type: MessageType.editorGameAdmins,
862
admins: listPublicGameAdmins()
863
});
864
break;
865
case MessageType.editorGrantGameAdmin:
866
requireAdmin(session);
867
{
868
const updated = stateDb.grantGameAdminByUsername(message.username);
869
refreshAccountAdminSessions(updated.auth_subject);
870
send(session, {
871
type: MessageType.editorGameAdmins,
872
admins: listPublicGameAdmins()
873
});
874
}
875
break;
876
case MessageType.editorRevokeGameAdmin:
877
requireAdmin(session);
878
{
879
const target = String(message.authSubject ?? "").trim();
880
if (!target)
881
{ throw userError("Admin account is required."); }
882
if (target === session.authSubject && !message.confirmSelf)
883
{ throw userError("Confirm removing your own admin access."); }
884
const updated = stateDb.setGameAdmin(target, false);
885
refreshAccountAdminSessions(updated.auth_subject);
886
send(session, {
887
type: MessageType.editorGameAdmins,
888
admins: listPublicGameAdmins()
889
});
890
}
891
break;
831
892
case MessageType.editorConsoleSubscribe:
832
893
requireAdmin(session);
833
894
session.consoleSubscribed = true;
@@ -1106,6 +1167,44 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1106
1167
}
1107
1168
}
1108
1169
1170
function userError (message)
1171
{
1172
const error = new Error(message);
1173
error.userFacing = true;
1174
return error;
1175
}
1176
1177
function listPublicGameAdmins ()
1178
{
1179
return stateDb.listGameAdmins().map((row) => ({
1180
authSubject: row.auth_subject,
1181
username: row.username ?? null,
1182
email: row.email ?? null
1183
}));
1184
}
1185
1186
function refreshAccountAdminSessions (authSubject)
1187
{
1188
const account = stateDb.getAccountBySubject(authSubject);
1189
if (!account)
1190
{ return; }
1191
for (const session of sessions.values())
1192
{
1193
if (session.authSubject !== authSubject)
1194
{ continue; }
1195
session.account = account;
1196
send(session, {
1197
type: MessageType.session,
1198
accountId: account.account_id,
1199
authSubject: account.auth_subject,
1200
username: session.username ?? account.username ?? null,
1201
email: account.email ?? null,
1202
isAdmin: !!account.is_admin,
1203
characters: characters.list(account.account_id)
1204
});
1205
}
1206
}
1207
1109
1208
function requireAdmin (session)
1110
1209
{
1111
1210
if (!session.account.is_admin)
@@ -32,15 +32,39 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,32
}32
}33
});33
});34
34
35
wss.on("connection", (socket) =>35
wss.on("connection", (socket, req) =>36
{36
{37
const identity = auth.claimIdentity();37
void openSession(socket, req);38
const account = stateDb.ensureAccount(identity.authSubject, identity.isAdmin, identity.email);38
});39
40
async function openSession (socket, req)41
{42
let identity;43
try44
{45
identity = await auth.authenticateRequest(req);46
}47
catch48
{49
socket.close(1011, "Authentication failed.");50
return;51
}52
if (!identity)53
{54
socket.close(4401, "Authentication required.");55
return;56
}57
58
const account = identity.stub59
? stateDb.ensureAccount(identity.authSubject, true, identity.email, identity.username)60
: await resolveAccount(stateDb, identity);39
const session = {61
const session = {40
id: nextSessionId++,62
id: nextSessionId++,41
socket,63
socket,42
account,64
account,43
authSubject: identity.authSubject,65
authSubject: identity.authSubject,66
username: identity.username ?? account.username ?? null,67
accessToken: identity.accessToken ?? null,44
characterId: null,68
characterId: null,45
entityId: null,69
entityId: null,46
/** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */70
/** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */@@ -52,11 +76,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,52
staticSubscribed: new Set()76
staticSubscribed: new Set()53
};77
};54
auth.register(session);78
auth.register(session);79
auth.startSessionMaintenance?.(session);55
sessions.set(session.id, session);80
sessions.set(session.id, session);56
send(session, {81
send(session, {57
type: MessageType.session,82
type: MessageType.session,58
accountId: account.account_id,83
accountId: account.account_id,59
authSubject: account.auth_subject,84
authSubject: account.auth_subject,85
username: session.username,86
email: account.email ?? null,60
isAdmin: !!account.is_admin,87
isAdmin: !!account.is_admin,61
characters: characters.list(account.account_id)88
characters: characters.list(account.account_id)62
});89
});@@ -88,7 +115,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,88
auth.release(session);115
auth.release(session);89
sessions.delete(session.id);116
sessions.delete(session.id);90
});117
});91
});118
}92
119
93
function handleMessage (session, message)120
function handleMessage (session, message)94
{121
{@@ -828,6 +855,40 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,828
itemLastSales: simulation.itemLastSalesSnapshot?.() ?? {}855
itemLastSales: simulation.itemLastSalesSnapshot?.() ?? {}829
});856
});830
break;857
break;858
case MessageType.editorLoadGameAdmins:859
requireAdmin(session);860
send(session, {861
type: MessageType.editorGameAdmins,862
admins: listPublicGameAdmins()863
});864
break;865
case MessageType.editorGrantGameAdmin:866
requireAdmin(session);867
{868
const updated = stateDb.grantGameAdminByUsername(message.username);869
refreshAccountAdminSessions(updated.auth_subject);870
send(session, {871
type: MessageType.editorGameAdmins,872
admins: listPublicGameAdmins()873
});874
}875
break;876
case MessageType.editorRevokeGameAdmin:877
requireAdmin(session);878
{879
const target = String(message.authSubject ?? "").trim();880
if (!target)881
{ throw userError("Admin account is required."); }882
if (target === session.authSubject && !message.confirmSelf)883
{ throw userError("Confirm removing your own admin access."); }884
const updated = stateDb.setGameAdmin(target, false);885
refreshAccountAdminSessions(updated.auth_subject);886
send(session, {887
type: MessageType.editorGameAdmins,888
admins: listPublicGameAdmins()889
});890
}891
break;831
case MessageType.editorConsoleSubscribe:892
case MessageType.editorConsoleSubscribe:832
requireAdmin(session);893
requireAdmin(session);833
session.consoleSubscribed = true;894
session.consoleSubscribed = true;@@ -1106,6 +1167,44 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,1106
}1167
}1107
}1168
}1108
1169
1170
function userError (message)1171
{1172
const error = new Error(message);1173
error.userFacing = true;1174
return error;1175
}1176
1177
function listPublicGameAdmins ()1178
{1179
return stateDb.listGameAdmins().map((row) => ({1180
authSubject: row.auth_subject,1181
username: row.username ?? null,1182
email: row.email ?? null1183
}));1184
}1185
1186
function refreshAccountAdminSessions (authSubject)1187
{1188
const account = stateDb.getAccountBySubject(authSubject);1189
if (!account)1190
{ return; }1191
for (const session of sessions.values())1192
{1193
if (session.authSubject !== authSubject)1194
{ continue; }1195
session.account = account;1196
send(session, {1197
type: MessageType.session,1198
accountId: account.account_id,1199
authSubject: account.auth_subject,1200
username: session.username ?? account.username ?? null,1201
email: account.email ?? null,1202
isAdmin: !!account.is_admin,1203
characters: characters.list(account.account_id)1204
});1205
}1206
}1207
1109
function requireAdmin (session)1208
function requireAdmin (session)1110
{1209
{1111
if (!session.account.is_admin)1210
if (!session.account.is_admin)@@ -4,7 +4,7 @@ import { StateDatabase } from "./persistence/stateDb.js";
4
4
import { EditorService } from "./editor/service.js";
5
5
import { CharacterService } from "./characters/service.js";
6
6
import { FriendService } from "./friends/service.js";
7
import { StubAuth } from "./auth/stub.js";
7
import { createAuth } from "./auth/index.js";
8
8
import { Simulation } from "./simulation/simulation.js";
9
9
import { createHttpServer, repoRootFrom } from "./gateway/http.js";
10
10
import { attachGateway } from "./gateway/websocket.js";
@@ -24,8 +24,8 @@ const editor = new EditorService(worldDb);
24
24
const characters = new CharacterService(stateDb, console);
25
25
const friends = new FriendService(stateDb);
26
26
const simulation = new Simulation(worldDb, stateDb);
27
const auth = new StubAuth();
28
const httpServer = createHttpServer(rootDir);
27
const auth = createAuth();
28
const httpServer = createHttpServer(rootDir, { auth, stateDb });
29
29
30
30
const deployBridge = {
31
31
getStatus ()
@@ -83,7 +83,7 @@ deployScheduler.start();
83
83
84
84
httpServer.listen(port, () =>
85
85
{
86
console.log(`Tile MMO listening on http://localhost:${port}`);
86
console.log(`Questward listening on http://localhost:${port}`);
87
87
console.log(`World editor: http://localhost:${port}/editor`);
88
88
});
89
89
@@ -4,7 +4,7 @@ import { StateDatabase } from "./persistence/stateDb.js";4
import { EditorService } from "./editor/service.js";4
import { EditorService } from "./editor/service.js";5
import { CharacterService } from "./characters/service.js";5
import { CharacterService } from "./characters/service.js";6
import { FriendService } from "./friends/service.js";6
import { FriendService } from "./friends/service.js";7
import { StubAuth } from "./auth/stub.js";7
import { createAuth } from "./auth/index.js";8
import { Simulation } from "./simulation/simulation.js";8
import { Simulation } from "./simulation/simulation.js";9
import { createHttpServer, repoRootFrom } from "./gateway/http.js";9
import { createHttpServer, repoRootFrom } from "./gateway/http.js";10
import { attachGateway } from "./gateway/websocket.js";10
import { attachGateway } from "./gateway/websocket.js";@@ -24,8 +24,8 @@ const editor = new EditorService(worldDb);24
const characters = new CharacterService(stateDb, console);24
const characters = new CharacterService(stateDb, console);25
const friends = new FriendService(stateDb);25
const friends = new FriendService(stateDb);26
const simulation = new Simulation(worldDb, stateDb);26
const simulation = new Simulation(worldDb, stateDb);27
const auth = new StubAuth();27
const auth = createAuth();28
const httpServer = createHttpServer(rootDir);28
const httpServer = createHttpServer(rootDir, { auth, stateDb });29
29
30
const deployBridge = {30
const deployBridge = {31
getStatus ()31
getStatus ()@@ -83,7 +83,7 @@ deployScheduler.start();83
83
84
httpServer.listen(port, () =>84
httpServer.listen(port, () =>85
{85
{86
console.log(`Tile MMO listening on http://localhost:${port}`);86
console.log(`Questward listening on http://localhost:${port}`);87
console.log(`World editor: http://localhost:${port}/editor`);87
console.log(`World editor: http://localhost:${port}/editor`);88
});88
});89
89
@@ -251,6 +251,9 @@ export class StateDatabase
251
251
}
252
252
if (!characterColumns.some((column) => column.name === "health_current"))
253
253
{ this.db.exec("ALTER TABLE characters ADD COLUMN health_current INTEGER"); }
254
const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();
255
if (!accountColumns.some((column) => column.name === "username"))
256
{ this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }
254
257
this.#grantLanternsToExistingCharacters();
255
258
}
256
259
@@ -300,23 +303,126 @@ export class StateDatabase
300
303
return this.db.prepare("SELECT * FROM accounts WHERE auth_subject = ?").get(authSubject) ?? null;
301
304
}
302
305
303
createAccount (authSubject, isAdmin, email = null)
306
countAccounts ()
304
307
{
305
this.db.prepare("INSERT INTO accounts (auth_subject, email, is_admin) VALUES (?, ?, ?)").run(
308
return this.db.prepare("SELECT COUNT(*) AS count FROM accounts").get().count;
309
}
310
311
countGameAdmins ()
312
{
313
return this.db.prepare("SELECT COUNT(*) AS count FROM accounts WHERE is_admin = 1").get().count;
314
}
315
316
findAccountByUsername (username)
317
{
318
const normalized = String(username ?? "").trim().toLowerCase();
319
if (!normalized)
320
{ return null; }
321
return this.db.prepare(`
322
SELECT * FROM accounts
323
WHERE lower(username) = ?
324
ORDER BY account_id ASC
325
LIMIT 1
326
`).get(normalized) ?? null;
327
}
328
329
listGameAdmins ()
330
{
331
return this.db.prepare(`
332
SELECT account_id, auth_subject, username, email, is_admin
333
FROM accounts
334
WHERE is_admin = 1
335
ORDER BY account_id ASC
336
`).all();
337
}
338
339
#syncAccountProfile (accountId, { email, username })
340
{
341
const fields = [];
342
const values = [];
343
if (email != null)
344
{
345
fields.push("email = ?");
346
values.push(email);
347
}
348
if (username != null)
349
{
350
fields.push("username = ?");
351
values.push(username);
352
}
353
if (!fields.length)
354
{ return; }
355
values.push(accountId);
356
this.db.prepare(`UPDATE accounts SET ${fields.join(", ")} WHERE account_id = ?`).run(...values);
357
}
358
359
resolveAccountFromAuth ({ authSubject, email = null, username = null })
360
{
361
const existing = this.getAccountBySubject(authSubject);
362
if (existing)
363
{
364
this.#syncAccountProfile(existing.account_id, { email, username });
365
return this.getAccountBySubject(authSubject);
366
}
367
const isFirstAccount = this.countAccounts() === 0;
368
return this.createAccount(authSubject, isFirstAccount, email, username);
369
}
370
371
setGameAdmin (authSubject, isAdmin)
372
{
373
const account = this.getAccountBySubject(authSubject);
374
if (!account)
375
{
376
const error = new Error("Account not found.");
377
error.userFacing = true;
378
throw error;
379
}
380
if (!isAdmin && account.is_admin && this.countGameAdmins() <= 1)
381
{
382
const error = new Error("Cannot remove the last game admin.");
383
error.userFacing = true;
384
throw error;
385
}
386
this.db.prepare("UPDATE accounts SET is_admin = ? WHERE auth_subject = ?").run(isAdmin ? 1 : 0, authSubject);
387
return this.getAccountBySubject(authSubject);
388
}
389
390
grantGameAdminByUsername (username)
391
{
392
const account = this.findAccountByUsername(username);
393
if (!account)
394
{
395
const error = new Error("No account with that username has signed in yet.");
396
error.userFacing = true;
397
throw error;
398
}
399
return this.setGameAdmin(account.auth_subject, true);
400
}
401
402
createAccount (authSubject, isAdmin, email = null, username = null)
403
{
404
this.db.prepare(`
405
INSERT INTO accounts (auth_subject, email, username, is_admin)
406
VALUES (?, ?, ?, ?)
407
`).run(
306
408
authSubject,
307
409
email,
410
username,
308
411
isAdmin ? 1 : 0
309
412
);
310
413
return this.getAccountBySubject(authSubject);
311
414
}
312
415
313
ensureAccount (authSubject, isAdmin, email = null)
416
ensureAccount (authSubject, isAdmin, email = null, username = null)
314
417
{
315
418
const existing = this.getAccountBySubject(authSubject);
316
419
if (existing)
317
{ return existing; }
420
{
421
this.#syncAccountProfile(existing.account_id, { email, username });
422
return existing;
423
}
318
424
319
return this.createAccount(authSubject, isAdmin, email);
425
return this.createAccount(authSubject, isAdmin, email, username);
320
426
}
321
427
322
428
listCharacters (accountId)
@@ -251,6 +251,9 @@ export class StateDatabase251
}251
}252
if (!characterColumns.some((column) => column.name === "health_current"))252
if (!characterColumns.some((column) => column.name === "health_current"))253
{ this.db.exec("ALTER TABLE characters ADD COLUMN health_current INTEGER"); }253
{ this.db.exec("ALTER TABLE characters ADD COLUMN health_current INTEGER"); }254
const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();255
if (!accountColumns.some((column) => column.name === "username"))256
{ this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }254
this.#grantLanternsToExistingCharacters();257
this.#grantLanternsToExistingCharacters();255
}258
}256
259
@@ -300,23 +303,126 @@ export class StateDatabase300
return this.db.prepare("SELECT * FROM accounts WHERE auth_subject = ?").get(authSubject) ?? null;303
return this.db.prepare("SELECT * FROM accounts WHERE auth_subject = ?").get(authSubject) ?? null;301
}304
}302
305
303
createAccount (authSubject, isAdmin, email = null)306
countAccounts ()304
{307
{305
this.db.prepare("INSERT INTO accounts (auth_subject, email, is_admin) VALUES (?, ?, ?)").run(308
return this.db.prepare("SELECT COUNT(*) AS count FROM accounts").get().count;309
}310
311
countGameAdmins ()312
{313
return this.db.prepare("SELECT COUNT(*) AS count FROM accounts WHERE is_admin = 1").get().count;314
}315
316
findAccountByUsername (username)317
{318
const normalized = String(username ?? "").trim().toLowerCase();319
if (!normalized)320
{ return null; }321
return this.db.prepare(`322
SELECT * FROM accounts323
WHERE lower(username) = ?324
ORDER BY account_id ASC325
LIMIT 1326
`).get(normalized) ?? null;327
}328
329
listGameAdmins ()330
{331
return this.db.prepare(`332
SELECT account_id, auth_subject, username, email, is_admin333
FROM accounts334
WHERE is_admin = 1335
ORDER BY account_id ASC336
`).all();337
}338
339
#syncAccountProfile (accountId, { email, username })340
{341
const fields = [];342
const values = [];343
if (email != null)344
{345
fields.push("email = ?");346
values.push(email);347
}348
if (username != null)349
{350
fields.push("username = ?");351
values.push(username);352
}353
if (!fields.length)354
{ return; }355
values.push(accountId);356
this.db.prepare(`UPDATE accounts SET ${fields.join(", ")} WHERE account_id = ?`).run(...values);357
}358
359
resolveAccountFromAuth ({ authSubject, email = null, username = null })360
{361
const existing = this.getAccountBySubject(authSubject);362
if (existing)363
{364
this.#syncAccountProfile(existing.account_id, { email, username });365
return this.getAccountBySubject(authSubject);366
}367
const isFirstAccount = this.countAccounts() === 0;368
return this.createAccount(authSubject, isFirstAccount, email, username);369
}370
371
setGameAdmin (authSubject, isAdmin)372
{373
const account = this.getAccountBySubject(authSubject);374
if (!account)375
{376
const error = new Error("Account not found.");377
error.userFacing = true;378
throw error;379
}380
if (!isAdmin && account.is_admin && this.countGameAdmins() <= 1)381
{382
const error = new Error("Cannot remove the last game admin.");383
error.userFacing = true;384
throw error;385
}386
this.db.prepare("UPDATE accounts SET is_admin = ? WHERE auth_subject = ?").run(isAdmin ? 1 : 0, authSubject);387
return this.getAccountBySubject(authSubject);388
}389
390
grantGameAdminByUsername (username)391
{392
const account = this.findAccountByUsername(username);393
if (!account)394
{395
const error = new Error("No account with that username has signed in yet.");396
error.userFacing = true;397
throw error;398
}399
return this.setGameAdmin(account.auth_subject, true);400
}401
402
createAccount (authSubject, isAdmin, email = null, username = null)403
{404
this.db.prepare(`405
INSERT INTO accounts (auth_subject, email, username, is_admin)406
VALUES (?, ?, ?, ?)407
`).run(306
authSubject,408
authSubject,307
email,409
email,410
username,308
isAdmin ? 1 : 0411
isAdmin ? 1 : 0309
);412
);310
return this.getAccountBySubject(authSubject);413
return this.getAccountBySubject(authSubject);311
}414
}312
415
313
ensureAccount (authSubject, isAdmin, email = null)416
ensureAccount (authSubject, isAdmin, email = null, username = null)314
{417
{315
const existing = this.getAccountBySubject(authSubject);418
const existing = this.getAccountBySubject(authSubject);316
if (existing)419
if (existing)317
{ return existing; }420
{421
this.#syncAccountProfile(existing.account_id, { email, username });422
return existing;423
}318
424
319
return this.createAccount(authSubject, isAdmin, email);425
return this.createAccount(authSubject, isAdmin, email, username);320
}426
}321
427
322
listCharacters (accountId)428
listCharacters (accountId)@@ -0,0 +1,50 @@
1
import test from "node:test";
2
import assert from "node:assert/strict";
3
import { mkdtempSync } from "node:fs";
4
import { tmpdir } from "node:os";
5
import { join } from "node:path";
6
import { StateDatabase } from "../src/persistence/stateDb.js";
7
8
test("first account from auth becomes game admin", () =>
9
{
10
const dir = mkdtempSync(join(tmpdir(), "questward-auth-"));
11
const db = new StateDatabase(join(dir, "state.sqlite"));
12
const first = db.resolveAccountFromAuth({
13
authSubject: "auth:1",
14
email: "first@example.com",
15
username: "first"
16
});
17
assert.equal(first.is_admin, 1);
18
const second = db.resolveAccountFromAuth({
19
authSubject: "auth:2",
20
email: "second@example.com",
21
username: "second"
22
});
23
assert.equal(second.is_admin, 0);
24
});
25
26
test("grant admin by username and block removing last admin", () =>
27
{
28
const dir = mkdtempSync(join(tmpdir(), "questward-auth-"));
29
const db = new StateDatabase(join(dir, "state.sqlite"));
30
db.resolveAccountFromAuth({ authSubject: "auth:10", username: "alpha", email: "a@b.c" });
31
db.resolveAccountFromAuth({ authSubject: "auth:11", username: "beta", email: "b@c.d" });
32
db.grantGameAdminByUsername("beta");
33
assert.equal(db.listGameAdmins().length, 2);
34
db.setGameAdmin("auth:11", false);
35
assert.equal(db.listGameAdmins().length, 1);
36
assert.throws(
37
() => db.setGameAdmin("auth:10", false),
38
(err) => err.userFacing && /last game admin/i.test(err.message)
39
);
40
});
41
42
test("grant admin by username requires prior sign-in", () =>
43
{
44
const dir = mkdtempSync(join(tmpdir(), "questward-auth-"));
45
const db = new StateDatabase(join(dir, "state.sqlite"));
46
assert.throws(
47
() => db.grantGameAdminByUsername("nobody"),
48
(err) => err.userFacing && /signed in yet/i.test(err.message)
49
);
50
});
@@ -0,0 +1,50 @@1
import test from "node:test";2
import assert from "node:assert/strict";3
import { mkdtempSync } from "node:fs";4
import { tmpdir } from "node:os";5
import { join } from "node:path";6
import { StateDatabase } from "../src/persistence/stateDb.js";7
8
test("first account from auth becomes game admin", () =>9
{10
const dir = mkdtempSync(join(tmpdir(), "questward-auth-"));11
const db = new StateDatabase(join(dir, "state.sqlite"));12
const first = db.resolveAccountFromAuth({13
authSubject: "auth:1",14
email: "first@example.com",15
username: "first"16
});17
assert.equal(first.is_admin, 1);18
const second = db.resolveAccountFromAuth({19
authSubject: "auth:2",20
email: "second@example.com",21
username: "second"22
});23
assert.equal(second.is_admin, 0);24
});25
26
test("grant admin by username and block removing last admin", () =>27
{28
const dir = mkdtempSync(join(tmpdir(), "questward-auth-"));29
const db = new StateDatabase(join(dir, "state.sqlite"));30
db.resolveAccountFromAuth({ authSubject: "auth:10", username: "alpha", email: "a@b.c" });31
db.resolveAccountFromAuth({ authSubject: "auth:11", username: "beta", email: "b@c.d" });32
db.grantGameAdminByUsername("beta");33
assert.equal(db.listGameAdmins().length, 2);34
db.setGameAdmin("auth:11", false);35
assert.equal(db.listGameAdmins().length, 1);36
assert.throws(37
() => db.setGameAdmin("auth:10", false),38
(err) => err.userFacing && /last game admin/i.test(err.message)39
);40
});41
42
test("grant admin by username requires prior sign-in", () =>43
{44
const dir = mkdtempSync(join(tmpdir(), "questward-auth-"));45
const db = new StateDatabase(join(dir, "state.sqlite"));46
assert.throws(47
() => db.grantGameAdminByUsername("nobody"),48
(err) => err.userFacing && /signed in yet/i.test(err.message)49
);50
});