BlueGit

timfa questward

Improve editor WebSocket reliability and production auth deploy.

Show editor loading/connecting progress and clear errors on WS failure, avoid stale auth status caching, add auth fetch timeout and server-side WS logging, and load OAuth secrets from /etc/questward/env in systemd.

timfa Tim Falken · pushed by timfa

Authored 2026-08-28 · 2 months ago

Hash
59b7e9f074c3b7cbb24ccbb2c3830c17d1e8a189
Parent
a75d35b0
9 files changed +181 −111
README.md +18 −1
@@ -34,6 +34,23 @@ Sign in via [auth.timfalken.com](https://auth.timfalken.com) (OAuth). Without `Q
34 34 | `QUESTWARD_AUTH_URL` | Auth base URL (default `https://auth.timfalken.com`) |
35 35 | `QUESTWARD_AUTH_STUB=1` | Force stub auth |
36 36
37 Register `questward.timfalken.com` (or your host) with callback path `/auth/callback` in the auth admin panel.
37 Register `timfalken.com` in auth admin with callback path `/auth/callback` and allowed port `1234` if using `:1234`.
38
39 ### Production env file (systemd)
40
41 On the game host, put secrets outside git:
42
43 ```bash
44 sudo mkdir -p /etc/questward
45 sudo nano /etc/questward/env # QUESTWARD_AUTH_CLIENT_SECRET=...
46 sudo chmod 600 /etc/questward/env
47 ```
48
49 The systemd unit loads `/etc/questward/env` automatically (`EnvironmentFile=-/...` — missing file is OK). Reinstall or `daemon-reload` after edits.
50
51 ```bash
52 cd ~/questward
53 sudo QUESTWARD_USER=timfa QUESTWARD_REPO="$HOME/questward" ./deploy/install-service.sh
54 ```
38 55
39 56 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.
@@ -34,6 +34,23 @@ Sign in via [auth.timfalken.com](https://auth.timfalken.com) (OAuth). Without `Q
34| `QUESTWARD_AUTH_URL` | Auth base URL (default `https://auth.timfalken.com`) |
34| `QUESTWARD_AUTH_URL` | Auth base URL (default `https://auth.timfalken.com`) |
35| `QUESTWARD_AUTH_STUB=1` | Force stub auth |
35| `QUESTWARD_AUTH_STUB=1` | Force stub auth |
36
36
37Register `questward.timfalken.com` (or your host) with callback path `/auth/callback` in the auth admin panel.
37Register `timfalken.com` in auth admin with callback path `/auth/callback` and allowed port `1234` if using `:1234`.
38
39### Production env file (systemd)
40
41On the game host, put secrets outside git:
42
43```bash
44sudo mkdir -p /etc/questward
45sudo nano /etc/questward/env # QUESTWARD_AUTH_CLIENT_SECRET=...
46sudo chmod 600 /etc/questward/env
47```
48
49The systemd unit loads `/etc/questward/env` automatically (`EnvironmentFile=-/...` — missing file is OK). Reinstall or `daemon-reload` after edits.
50
51```bash
52cd ~/questward
53sudo QUESTWARD_USER=timfa QUESTWARD_REPO="$HOME/questward" ./deploy/install-service.sh
54```
38
55
39The 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.
56The 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.
client/src/editor/main.js +64 −33
@@ -1,33 +1,33 @@
1 1 import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2 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";
3 {
4 GROUND_DEFINITIONS,
5 BLOCK_DEFINITIONS,
6 GroundType,
7 BlockType,
8 normalizeGround,
9 normalizeBlock,
10 listPlaceableBlockPaletteEntries
11 } from "/shared/definitions/tiles.js";
12 12 import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
13 13 import
14 {
15 SeasonId,
16 seasonIdAt,
17 seasonalCycleStates,
18 seasonIdFromVisualState,
19 placeableStatesForType
20 } from "/shared/world/season.js";
14 {
15 SeasonId,
16 seasonIdAt,
17 seasonalCycleStates,
18 seasonIdFromVisualState,
19 placeableStatesForType
20 } from "/shared/world/season.js";
21 21 import { loadGraphicsSettings } from "/shared/graphics/settings.js";
22 22 import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
23 23 import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
24 24 import
25 {
26 computeNeighborConnectMask,
27 composeNeighborConnectState,
28 definitionUsesNeighborConnect,
29 neighborConnectBlocksMatch
30 } from "/shared/world/neighborConnect.js";
25 {
26 computeNeighborConnectMask,
27 composeNeighborConnectState,
28 definitionUsesNeighborConnect,
29 neighborConnectBlocksMatch
30 } from "/shared/world/neighborConnect.js";
31 31 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
32 32 import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";
33 33 import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
@@ -39,11 +39,11 @@ import { initQuestsModal } from "./questsModal.js";
39 39 import { initDialoguesModal } from "./dialoguesModal.js";
40 40 import { createDimensionCombobox } from "./dimensionCombobox.js";
41 41 import
42 {
43 OVERWORLD_ID,
44 normalizeDimensionId,
45 isOverworld
46 } from "/shared/world/dimensions.js";
42 {
43 OVERWORLD_ID,
44 normalizeDimensionId,
45 isOverworld
46 } from "/shared/world/dimensions.js";
47 47
48 48 const game = new Game();
49 49 let socket;
@@ -741,14 +741,21 @@ function zoomEditor (direction)
741 741
742 742 function requestChunks (coords)
743 743 {
744 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
745 { return; }
744 746 for (const coord of coords)
745 747 {
746 socket.send({
747 type: MessageType.editorLoadChunk,
748 chunkX: coord.chunkX,
749 chunkY: coord.chunkY,
750 dimensionId: selectedDimensionId
751 });
748 try
749 {
750 socket.send({
751 type: MessageType.editorLoadChunk,
752 chunkX: coord.chunkX,
753 chunkY: coord.chunkY,
754 dimensionId: selectedDimensionId
755 });
756 }
757 catch (_)
758 { break; }
752 759 }
753 760 }
754 761
@@ -881,6 +888,9 @@ async function main ()
881 888 return;
882 889 }
883 890
891 const accountLabel = authStatus.username ?? authStatus.email ?? authStatus.authSubject ?? "Signed in";
892 $("who").textContent = `${accountLabel} · loading sprites…`;
893
884 894 catalog = await loadSpriteCatalog();
885 895 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
886 896 await preloadCatalogImages(game, catalog);
@@ -1034,6 +1044,8 @@ async function main ()
1034 1044 scene.addObject(ticker);
1035 1045 window.addEventListener("resize", layoutScene);
1036 1046
1047 $("who").textContent = `${accountLabel} · connecting…`;
1048
1037 1049 socket = new GameSocket(defaultSocketUrl(), (message) =>
1038 1050 {
1039 1051 if (message.type === MessageType.session)
@@ -1116,6 +1128,25 @@ async function main ()
1116 1128 updateRevisionUI();
1117 1129 }
1118 1130 }
1131 }, {
1132 onClose (event)
1133 {
1134 if (event.code === 1000)
1135 { return; }
1136 const reasons = {
1137 4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1138 1011: "Server could not verify your account with auth.timfalken.com.",
1139 1006: "Connection dropped before the editor session started."
1140 };
1141 const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1142 $("who").textContent = "Connection failed";
1143 $("error").textContent = detail;
1144 },
1145 onError ()
1146 {
1147 $("who").textContent = "Connection failed";
1148 $("error").textContent = "Could not open a live connection to the server.";
1149 }
1119 1150 });
1120 1151 settingsModal = initSettingsModal({
1121 1152 socket,
@@ -1,33 +1,33 @@
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import
2import
3 {
3{
4 GROUND_DEFINITIONS,
4 GROUND_DEFINITIONS,
5 BLOCK_DEFINITIONS,
5 BLOCK_DEFINITIONS,
6 GroundType,
6 GroundType,
7 BlockType,
7 BlockType,
8 normalizeGround,
8 normalizeGround,
9 normalizeBlock,
9 normalizeBlock,
10 listPlaceableBlockPaletteEntries
10 listPlaceableBlockPaletteEntries
11 } from "/shared/definitions/tiles.js";
11} from "/shared/definitions/tiles.js";
12import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
12import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
13import
13import
14 {
14{
15 SeasonId,
15 SeasonId,
16 seasonIdAt,
16 seasonIdAt,
17 seasonalCycleStates,
17 seasonalCycleStates,
18 seasonIdFromVisualState,
18 seasonIdFromVisualState,
19 placeableStatesForType
19 placeableStatesForType
20 } from "/shared/world/season.js";
20} from "/shared/world/season.js";
21import { loadGraphicsSettings } from "/shared/graphics/settings.js";
21import { loadGraphicsSettings } from "/shared/graphics/settings.js";
22import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
22import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";
23import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
23import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";
24import
24import
25 {
25{
26 computeNeighborConnectMask,
26 computeNeighborConnectMask,
27 composeNeighborConnectState,
27 composeNeighborConnectState,
28 definitionUsesNeighborConnect,
28 definitionUsesNeighborConnect,
29 neighborConnectBlocksMatch
29 neighborConnectBlocksMatch
30 } from "/shared/world/neighborConnect.js";
30} from "/shared/world/neighborConnect.js";
31import { GameSocket, defaultSocketUrl } from "../net/socket.js";
31import { GameSocket, defaultSocketUrl } from "../net/socket.js";
32import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";
32import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";
33import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
33import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
@@ -39,11 +39,11 @@ import { initQuestsModal } from "./questsModal.js";
39import { initDialoguesModal } from "./dialoguesModal.js";
39import { initDialoguesModal } from "./dialoguesModal.js";
40import { createDimensionCombobox } from "./dimensionCombobox.js";
40import { createDimensionCombobox } from "./dimensionCombobox.js";
41import
41import
42 {
42{
43 OVERWORLD_ID,
43 OVERWORLD_ID,
44 normalizeDimensionId,
44 normalizeDimensionId,
45 isOverworld
45 isOverworld
46 } from "/shared/world/dimensions.js";
46} from "/shared/world/dimensions.js";
47
47
48const game = new Game();
48const game = new Game();
49let socket;
49let socket;
@@ -741,14 +741,21 @@ function zoomEditor (direction)
741
741
742function requestChunks (coords)
742function requestChunks (coords)
743{
743{
744 if (!socket?.socket || socket.socket.readyState !== WebSocket.OPEN)
745 { return; }
744 for (const coord of coords)
746 for (const coord of coords)
745 {
747 {
746 socket.send({
748 try
747 type: MessageType.editorLoadChunk,
749 {
748 chunkX: coord.chunkX,
750 socket.send({
749 chunkY: coord.chunkY,
751 type: MessageType.editorLoadChunk,
750 dimensionId: selectedDimensionId
752 chunkX: coord.chunkX,
751 });
753 chunkY: coord.chunkY,
754 dimensionId: selectedDimensionId
755 });
756 }
757 catch (_)
758 { break; }
752 }
759 }
753}
760}
754
761
@@ -881,6 +888,9 @@ async function main ()
881 return;
888 return;
882 }
889 }
883
890
891 const accountLabel = authStatus.username ?? authStatus.email ?? authStatus.authSubject ?? "Signed in";
892 $("who").textContent = `${accountLabel} · loading sprites…`;
893
884 catalog = await loadSpriteCatalog();
894 catalog = await loadSpriteCatalog();
885 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
895 imageUrlByName = new Map((catalog.images ?? []).map((entry) => [entry.name, entry.url]));
886 await preloadCatalogImages(game, catalog);
896 await preloadCatalogImages(game, catalog);
@@ -1034,6 +1044,8 @@ async function main ()
1034 scene.addObject(ticker);
1044 scene.addObject(ticker);
1035 window.addEventListener("resize", layoutScene);
1045 window.addEventListener("resize", layoutScene);
1036
1046
1047 $("who").textContent = `${accountLabel} · connecting…`;
1048
1037 socket = new GameSocket(defaultSocketUrl(), (message) =>
1049 socket = new GameSocket(defaultSocketUrl(), (message) =>
1038 {
1050 {
1039 if (message.type === MessageType.session)
1051 if (message.type === MessageType.session)
@@ -1116,6 +1128,25 @@ async function main ()
1116 updateRevisionUI();
1128 updateRevisionUI();
1117 }
1129 }
1118 }
1130 }
1131 }, {
1132 onClose (event)
1133 {
1134 if (event.code === 1000)
1135 { return; }
1136 const reasons = {
1137 4401: "Sign in expired or missing. Use Sign out, then sign in again.",
1138 1011: "Server could not verify your account with auth.timfalken.com.",
1139 1006: "Connection dropped before the editor session started."
1140 };
1141 const detail = reasons[event.code] ?? `Connection closed (code ${event.code}).`;
1142 $("who").textContent = "Connection failed";
1143 $("error").textContent = detail;
1144 },
1145 onError ()
1146 {
1147 $("who").textContent = "Connection failed";
1148 $("error").textContent = "Could not open a live connection to the server.";
1149 }
1119 });
1150 });
1120 settingsModal = initSettingsModal({
1151 settingsModal = initSettingsModal({
1121 socket,
1152 socket,
client/src/net/auth.js +1 −1
@@ -1,6 +1,6 @@
1 1 export async function fetchAuthStatus ()
2 2 {
3 const response = await fetch("/auth/status");
3 const response = await fetch("/auth/status", { cache: "no-store" });
4 4 if (!response.ok)
5 5 { return { authenticated: false }; }
6 6 return response.json();
@@ -1,6 +1,6 @@
1export async function fetchAuthStatus ()
1export async function fetchAuthStatus ()
2{
2{
3 const response = await fetch("/auth/status");
3 const response = await fetch("/auth/status", { cache: "no-store" });
4 if (!response.ok)
4 if (!response.ok)
5 { return { authenticated: false }; }
5 { return { authenticated: false }; }
6 return response.json();
6 return response.json();
client/src/net/socket.js +8 −1
@@ -1,10 +1,11 @@
1 1 export class GameSocket
2 2 {
3 constructor (url, onMessage, { onClose } = {})
3 constructor(url, onMessage, { onClose, onError } = {})
4 4 {
5 5 this.url = url;
6 6 this.onMessage = onMessage;
7 7 this.onClose = onClose;
8 this.onError = onError;
8 9 this.socket = null;
9 10 }
10 11
@@ -19,6 +20,10 @@ export class GameSocket
19 20 {
20 21 this.onClose?.(event);
21 22 });
23 this.socket.addEventListener("error", (event) =>
24 {
25 this.onError?.(event);
26 });
22 27 return new Promise((resolve, reject) =>
23 28 {
24 29 this.socket.addEventListener("open", resolve, { once: true });
@@ -28,6 +33,8 @@ export class GameSocket
28 33
29 34 send (payload)
30 35 {
36 if (!this.socket || this.socket.readyState !== WebSocket.OPEN)
37 { throw new Error("WebSocket is not connected."); }
31 38 this.socket.send(JSON.stringify(payload));
32 39 }
33 40 }
@@ -1,10 +1,11 @@
1export class GameSocket
1export class GameSocket
2{
2{
3 constructor (url, onMessage, { onClose } = {})
3 constructor(url, onMessage, { onClose, onError } = {})
4 {
4 {
5 this.url = url;
5 this.url = url;
6 this.onMessage = onMessage;
6 this.onMessage = onMessage;
7 this.onClose = onClose;
7 this.onClose = onClose;
8 this.onError = onError;
8 this.socket = null;
9 this.socket = null;
9 }
10 }
10
11
@@ -19,6 +20,10 @@ export class GameSocket
19 {
20 {
20 this.onClose?.(event);
21 this.onClose?.(event);
21 });
22 });
23 this.socket.addEventListener("error", (event) =>
24 {
25 this.onError?.(event);
26 });
22 return new Promise((resolve, reject) =>
27 return new Promise((resolve, reject) =>
23 {
28 {
24 this.socket.addEventListener("open", resolve, { once: true });
29 this.socket.addEventListener("open", resolve, { once: true });
@@ -28,6 +33,8 @@ export class GameSocket
28
33
29 send (payload)
34 send (payload)
30 {
35 {
36 if (!this.socket || this.socket.readyState !== WebSocket.OPEN)
37 { throw new Error("WebSocket is not connected."); }
31 this.socket.send(JSON.stringify(payload));
38 this.socket.send(JSON.stringify(payload));
32 }
39 }
33}
40}
deploy/install-service.sh +1 −1
@@ -18,7 +18,7 @@ if [[ ! -f "$UNIT_SRC" ]]; then
18 18 exit 1
19 19 fi
20 20
21 chmod +x "$SCRIPT_DIR/start-server.sh" "$SCRIPT_DIR/update-if-requested.mjs" 2>/dev/null || true
21 chmod +x "$SCRIPT_DIR/start-server.sh" "$SCRIPT_DIR/install-service.sh" "$SCRIPT_DIR/update-if-requested.mjs" 2>/dev/null || true
22 22
23 23 # Rewrite WorkingDirectory / paths for this checkout.
24 24 tmp="$(mktemp)"
@@ -18,7 +18,7 @@ if [[ ! -f "$UNIT_SRC" ]]; then
18 exit 1
18 exit 1
19fi
19fi
20
20
21chmod +x "$SCRIPT_DIR/start-server.sh" "$SCRIPT_DIR/update-if-requested.mjs" 2>/dev/null || true
21chmod +x "$SCRIPT_DIR/start-server.sh" "$SCRIPT_DIR/install-service.sh" "$SCRIPT_DIR/update-if-requested.mjs" 2>/dev/null || true
22
22
23# Rewrite WorkingDirectory / paths for this checkout.
23# Rewrite WorkingDirectory / paths for this checkout.
24tmp="$(mktemp)"
24tmp="$(mktemp)"
deploy/questward.service +1 −0
@@ -5,6 +5,7 @@ Wants=network-online.target
5 5
6 6 [Service]
7 7 Type=simple
8 EnvironmentFile=-/etc/questward/env
8 9 User=questward
9 10 Group=questward
10 11 WorkingDirectory=/srv/questward/current
@@ -5,6 +5,7 @@ Wants=network-online.target
5
5
6[Service]
6[Service]
7Type=simple
7Type=simple
8EnvironmentFile=-/etc/questward/env
8User=questward
9User=questward
9Group=questward
10Group=questward
10WorkingDirectory=/srv/questward/current
11WorkingDirectory=/srv/questward/current
deploy/start-server.sh +3 −0
@@ -14,6 +14,9 @@ git reset --hard "origin/$BRANCH"
14 14 git clean -fd
15 15 git pull --ff-only origin "$BRANCH" || true
16 16
17 DEPLOY_DIR="$(cd "$(dirname "$0")" && pwd)"
18 chmod +x "$DEPLOY_DIR/start-server.sh" "$DEPLOY_DIR/install-service.sh" "$DEPLOY_DIR/update-if-requested.mjs" 2>/dev/null || true
19
17 20 echo "[deploy] npm install…"
18 21 npm install --omit=dev
19 22
@@ -14,6 +14,9 @@ git reset --hard "origin/$BRANCH"
14git clean -fd
14git clean -fd
15git pull --ff-only origin "$BRANCH" || true
15git pull --ff-only origin "$BRANCH" || true
16
16
17DEPLOY_DIR="$(cd "$(dirname "$0")" && pwd)"
18chmod +x "$DEPLOY_DIR/start-server.sh" "$DEPLOY_DIR/install-service.sh" "$DEPLOY_DIR/update-if-requested.mjs" 2>/dev/null || true
19
17echo "[deploy] npm install…"
20echo "[deploy] npm install…"
18npm install --omit=dev
21npm install --omit=dev
19
22
server/src/auth/client.js +4 −3
@@ -1,6 +1,6 @@
1 1 export class AuthClient
2 2 {
3 constructor (config)
3 constructor(config)
4 4 {
5 5 this.config = config;
6 6 this.cache = new Map();
@@ -45,7 +45,8 @@ export class AuthClient
45 45 "Authorization": `Bearer ${accessToken}`,
46 46 "Accept": "application/json",
47 47 "User-Agent": this.config.userAgent
48 }
48 },
49 signal: AbortSignal.timeout(15_000)
49 50 });
50 51 const payload = await response.json().catch(() => ({}));
51 52 if (!response.ok)
@@ -92,7 +93,7 @@ export class AuthClient
92 93 "Accept": "application/json",
93 94 "User-Agent": this.config.userAgent
94 95 }
95 }).catch(() => {});
96 }).catch(() => { });
96 97 }
97 98 }
98 99
@@ -1,6 +1,6 @@
1export class AuthClient
1export class AuthClient
2{
2{
3 constructor (config)
3 constructor(config)
4 {
4 {
5 this.config = config;
5 this.config = config;
6 this.cache = new Map();
6 this.cache = new Map();
@@ -45,7 +45,8 @@ export class AuthClient
45 "Authorization": `Bearer ${accessToken}`,
45 "Authorization": `Bearer ${accessToken}`,
46 "Accept": "application/json",
46 "Accept": "application/json",
47 "User-Agent": this.config.userAgent
47 "User-Agent": this.config.userAgent
48 }
48 },
49 signal: AbortSignal.timeout(15_000)
49 });
50 });
50 const payload = await response.json().catch(() => ({}));
51 const payload = await response.json().catch(() => ({}));
51 if (!response.ok)
52 if (!response.ok)
@@ -92,7 +93,7 @@ export class AuthClient
92 "Accept": "application/json",
93 "Accept": "application/json",
93 "User-Agent": this.config.userAgent
94 "User-Agent": this.config.userAgent
94 }
95 }
95 }).catch(() => {});
96 }).catch(() => { });
96 }
97 }
97}
98}
98
99
server/src/gateway/websocket.js +81 −71
@@ -44,77 +44,87 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
44 44 {
45 45 identity = await auth.authenticateRequest(req);
46 46 }
47 catch
47 catch (error)
48 48 {
49 console.error("[ws] Authentication error:", error?.message ?? error);
49 50 socket.close(1011, "Authentication failed.");
50 51 return;
51 52 }
52 53 if (!identity)
53 54 {
55 console.warn("[ws] Connection rejected: no valid session cookie.");
54 56 socket.close(4401, "Authentication required.");
55 57 return;
56 58 }
57 59
58 const account = identity.stub
59 ? stateDb.ensureAccount(identity.authSubject, true, identity.email, identity.username)
60 : await resolveAccount(stateDb, identity);
61 const session = {
62 id: nextSessionId++,
63 socket,
64 account,
65 authSubject: identity.authSubject,
66 username: identity.username ?? account.username ?? null,
67 accessToken: identity.accessToken ?? null,
68 characterId: null,
69 entityId: null,
70 /** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */
71 viewDistance: ViewDistance.long,
72 consoleSubscribed: false,
73 /** Chunks where entity / ground-item replication is active (3×3). */
74 entitySubscribed: new Set(),
75 /** Chunks with map + baked lighting only (5×5 when long). */
76 staticSubscribed: new Set()
77 };
78 auth.register(session);
79 auth.startSessionMaintenance?.(session);
80 sessions.set(session.id, session);
81 send(session, {
82 type: MessageType.session,
83 accountId: account.account_id,
84 authSubject: account.auth_subject,
85 username: session.username,
86 email: account.email ?? null,
87 isAdmin: !!account.is_admin,
88 characters: characters.list(account.account_id)
89 });
90
91 socket.on("message", (raw) =>
60 try
92 61 {
93 let message;
94 try
95 { message = JSON.parse(String(raw)); }
96 catch
97 {
98 send(session, { type: MessageType.error, message: "Invalid JSON." });
99 return;
100 }
101 try
102 { handleMessage(session, message); }
103 catch (error)
62 const account = identity.stub
63 ? stateDb.ensureAccount(identity.authSubject, true, identity.email, identity.username)
64 : await resolveAccount(stateDb, identity);
65 const session = {
66 id: nextSessionId++,
67 socket,
68 account,
69 authSubject: identity.authSubject,
70 username: identity.username ?? account.username ?? null,
71 accessToken: identity.accessToken ?? null,
72 characterId: null,
73 entityId: null,
74 /** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */
75 viewDistance: ViewDistance.long,
76 consoleSubscribed: false,
77 /** Chunks where entity / ground-item replication is active (3×3). */
78 entitySubscribed: new Set(),
79 /** Chunks with map + baked lighting only (5×5 when long). */
80 staticSubscribed: new Set()
81 };
82 auth.register(session);
83 auth.startSessionMaintenance?.(session);
84 sessions.set(session.id, session);
85 send(session, {
86 type: MessageType.session,
87 accountId: account.account_id,
88 authSubject: account.auth_subject,
89 username: session.username,
90 email: account.email ?? null,
91 isAdmin: !!account.is_admin,
92 characters: characters.list(account.account_id)
93 });
94
95 socket.on("message", (raw) =>
104 96 {
105 send(session, {
106 type: MessageType.error,
107 message: error.userFacing ? error.message : "Request failed."
108 });
109 }
110 });
97 let message;
98 try
99 { message = JSON.parse(String(raw)); }
100 catch
101 {
102 send(session, { type: MessageType.error, message: "Invalid JSON." });
103 return;
104 }
105 try
106 { handleMessage(session, message); }
107 catch (error)
108 {
109 send(session, {
110 type: MessageType.error,
111 message: error.userFacing ? error.message : "Request failed."
112 });
113 }
114 });
111 115
112 socket.on("close", () =>
116 socket.on("close", () =>
117 {
118 leaveWorld(session);
119 auth.release(session);
120 sessions.delete(session.id);
121 });
122 }
123 catch (error)
113 124 {
114 leaveWorld(session);
115 auth.release(session);
116 sessions.delete(session.id);
117 });
125 console.error("[ws] Session setup failed:", error?.message ?? error);
126 socket.close(1011, "Session setup failed.");
127 }
118 128 }
119 129
120 130 function handleMessage (session, message)
@@ -344,20 +354,20 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
344 354 });
345 355 break;
346 356 case MessageType.openStation:
347 {
348 requirePlaying(session);
349 const stationId = typeof message.stationId === "string"
350 ? message.stationId
351 : null;
352 if (!stationId || !craftingStationDefinition(stationId))
353 { break; }
354 simulation.enqueue(session.id, {
355 type: "open-station",
356 characterId: session.characterId,
357 stationId
358 });
359 break;
360 }
357 {
358 requirePlaying(session);
359 const stationId = typeof message.stationId === "string"
360 ? message.stationId
361 : null;
362 if (!stationId || !craftingStationDefinition(stationId))
363 { break; }
364 simulation.enqueue(session.id, {
365 type: "open-station",
366 characterId: session.characterId,
367 stationId
368 });
369 break;
370 }
361 371 case MessageType.mine:
362 372 requirePlaying(session);
363 373 simulation.enqueue(session.id, {
@@ -44,77 +44,87 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
44 {
44 {
45 identity = await auth.authenticateRequest(req);
45 identity = await auth.authenticateRequest(req);
46 }
46 }
47 catch
47 catch (error)
48 {
48 {
49 console.error("[ws] Authentication error:", error?.message ?? error);
49 socket.close(1011, "Authentication failed.");
50 socket.close(1011, "Authentication failed.");
50 return;
51 return;
51 }
52 }
52 if (!identity)
53 if (!identity)
53 {
54 {
55 console.warn("[ws] Connection rejected: no valid session cookie.");
54 socket.close(4401, "Authentication required.");
56 socket.close(4401, "Authentication required.");
55 return;
57 return;
56 }
58 }
57
59
58 const account = identity.stub
60 try
59 ? stateDb.ensureAccount(identity.authSubject, true, identity.email, identity.username)
60 : await resolveAccount(stateDb, identity);
61 const session = {
62 id: nextSessionId++,
63 socket,
64 account,
65 authSubject: identity.authSubject,
66 username: identity.username ?? account.username ?? null,
67 accessToken: identity.accessToken ?? null,
68 characterId: null,
69 entityId: null,
70 /** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */
71 viewDistance: ViewDistance.long,
72 consoleSubscribed: false,
73 /** Chunks where entity / ground-item replication is active (3×3). */
74 entitySubscribed: new Set(),
75 /** Chunks with map + baked lighting only (5×5 when long). */
76 staticSubscribed: new Set()
77 };
78 auth.register(session);
79 auth.startSessionMaintenance?.(session);
80 sessions.set(session.id, session);
81 send(session, {
82 type: MessageType.session,
83 accountId: account.account_id,
84 authSubject: account.auth_subject,
85 username: session.username,
86 email: account.email ?? null,
87 isAdmin: !!account.is_admin,
88 characters: characters.list(account.account_id)
89 });
90
91 socket.on("message", (raw) =>
92 {
61 {
93 let message;
62 const account = identity.stub
94 try
63 ? stateDb.ensureAccount(identity.authSubject, true, identity.email, identity.username)
95 { message = JSON.parse(String(raw)); }
64 : await resolveAccount(stateDb, identity);
96 catch
65 const session = {
97 {
66 id: nextSessionId++,
98 send(session, { type: MessageType.error, message: "Invalid JSON." });
67 socket,
99 return;
68 account,
100 }
69 authSubject: identity.authSubject,
101 try
70 username: identity.username ?? account.username ?? null,
102 { handleMessage(session, message); }
71 accessToken: identity.accessToken ?? null,
103 catch (error)
72 characterId: null,
73 entityId: null,
74 /** Client graphics: long = STATIC_CHUNK_RADIUS map ring; short = VISIBLE_CHUNK_RADIUS. */
75 viewDistance: ViewDistance.long,
76 consoleSubscribed: false,
77 /** Chunks where entity / ground-item replication is active (3×3). */
78 entitySubscribed: new Set(),
79 /** Chunks with map + baked lighting only (5×5 when long). */
80 staticSubscribed: new Set()
81 };
82 auth.register(session);
83 auth.startSessionMaintenance?.(session);
84 sessions.set(session.id, session);
85 send(session, {
86 type: MessageType.session,
87 accountId: account.account_id,
88 authSubject: account.auth_subject,
89 username: session.username,
90 email: account.email ?? null,
91 isAdmin: !!account.is_admin,
92 characters: characters.list(account.account_id)
93 });
94
95 socket.on("message", (raw) =>
104 {
96 {
105 send(session, {
97 let message;
106 type: MessageType.error,
98 try
107 message: error.userFacing ? error.message : "Request failed."
99 { message = JSON.parse(String(raw)); }
108 });
100 catch
109 }
101 {
110 });
102 send(session, { type: MessageType.error, message: "Invalid JSON." });
103 return;
104 }
105 try
106 { handleMessage(session, message); }
107 catch (error)
108 {
109 send(session, {
110 type: MessageType.error,
111 message: error.userFacing ? error.message : "Request failed."
112 });
113 }
114 });
111
115
112 socket.on("close", () =>
116 socket.on("close", () =>
117 {
118 leaveWorld(session);
119 auth.release(session);
120 sessions.delete(session.id);
121 });
122 }
123 catch (error)
113 {
124 {
114 leaveWorld(session);
125 console.error("[ws] Session setup failed:", error?.message ?? error);
115 auth.release(session);
126 socket.close(1011, "Session setup failed.");
116 sessions.delete(session.id);
127 }
117 });
118 }
128 }
119
129
120 function handleMessage (session, message)
130 function handleMessage (session, message)
@@ -344,20 +354,20 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
344 });
354 });
345 break;
355 break;
346 case MessageType.openStation:
356 case MessageType.openStation:
347 {
357 {
348 requirePlaying(session);
358 requirePlaying(session);
349 const stationId = typeof message.stationId === "string"
359 const stationId = typeof message.stationId === "string"
350 ? message.stationId
360 ? message.stationId
351 : null;
361 : null;
352 if (!stationId || !craftingStationDefinition(stationId))
362 if (!stationId || !craftingStationDefinition(stationId))
353 { break; }
363 { break; }
354 simulation.enqueue(session.id, {
364 simulation.enqueue(session.id, {
355 type: "open-station",
365 type: "open-station",
356 characterId: session.characterId,
366 characterId: session.characterId,
357 stationId
367 stationId
358 });
368 });
359 break;
369 break;
360 }
370 }
361 case MessageType.mine:
371 case MessageType.mine:
362 requirePlaying(session);
372 requirePlaying(session);
363 simulation.enqueue(session.id, {
373 simulation.enqueue(session.id, {