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.
@@ -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 `Q34
| `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
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
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.
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.
@@ -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 @@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
import2
import3
{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
listPlaceableBlockPaletteEntries10
listPlaceableBlockPaletteEntries11
} from "/shared/definitions/tiles.js";11
} from "/shared/definitions/tiles.js";12
import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";12
import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";13
import13
import14
{14
{15
SeasonId,15
SeasonId,16
seasonIdAt,16
seasonIdAt,17
seasonalCycleStates,17
seasonalCycleStates,18
seasonIdFromVisualState,18
seasonIdFromVisualState,19
placeableStatesForType19
placeableStatesForType20
} from "/shared/world/season.js";20
} from "/shared/world/season.js";21
import { loadGraphicsSettings } from "/shared/graphics/settings.js";21
import { loadGraphicsSettings } from "/shared/graphics/settings.js";22
import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";22
import { randomFlowerColorId, flowerBlockState } from "/shared/definitions/dyes.js";23
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";23
import { defaultSpawnerConfig, normalizeSpawnerConfig, mobDefinition, mobSpriteName } from "/shared/definitions/mobs.js";24
import24
import25
{25
{26
computeNeighborConnectMask,26
computeNeighborConnectMask,27
composeNeighborConnectState,27
composeNeighborConnectState,28
definitionUsesNeighborConnect,28
definitionUsesNeighborConnect,29
neighborConnectBlocksMatch29
neighborConnectBlocksMatch30
} from "/shared/world/neighborConnect.js";30
} from "/shared/world/neighborConnect.js";31
import { GameSocket, defaultSocketUrl } from "../net/socket.js";31
import { GameSocket, defaultSocketUrl } from "../net/socket.js";32
import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";32
import { fetchAuthStatus, loginUrl, logoutUrl } from "../net/auth.js";33
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";33
import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";@@ -39,11 +39,11 @@ import { initQuestsModal } from "./questsModal.js";39
import { initDialoguesModal } from "./dialoguesModal.js";39
import { initDialoguesModal } from "./dialoguesModal.js";40
import { createDimensionCombobox } from "./dimensionCombobox.js";40
import { createDimensionCombobox } from "./dimensionCombobox.js";41
import41
import42
{42
{43
OVERWORLD_ID,43
OVERWORLD_ID,44
normalizeDimensionId,44
normalizeDimensionId,45
isOverworld45
isOverworld46
} from "/shared/world/dimensions.js";46
} from "/shared/world/dimensions.js";47
47
48
const game = new Game();48
const game = new Game();49
let socket;49
let socket;@@ -741,14 +741,21 @@ function zoomEditor (direction)741
741
742
function requestChunks (coords)742
function 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
try747
type: MessageType.editorLoadChunk,749
{748
chunkX: coord.chunkX,750
socket.send({749
chunkY: coord.chunkY,751
type: MessageType.editorLoadChunk,750
dimensionId: selectedDimensionId752
chunkX: coord.chunkX,751
});753
chunkY: coord.chunkY,754
dimensionId: selectedDimensionId755
});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,@@ -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 @@1
export async function fetchAuthStatus ()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
if (!response.ok)4
if (!response.ok)5
{ return { authenticated: false }; }5
{ return { authenticated: false }; }6
return response.json();6
return response.json();@@ -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 @@1
export class GameSocket1
export class GameSocket2
{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 GameSocket19
{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 GameSocket28
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
}@@ -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" ]]; then18
exit 118
exit 119
fi19
fi20
20
21
chmod +x "$SCRIPT_DIR/start-server.sh" "$SCRIPT_DIR/update-if-requested.mjs" 2>/dev/null || true21
chmod +x "$SCRIPT_DIR/start-server.sh" "$SCRIPT_DIR/install-service.sh" "$SCRIPT_DIR/update-if-requested.mjs" 2>/dev/null || true22
22
23
# Rewrite WorkingDirectory / paths for this checkout.23
# Rewrite WorkingDirectory / paths for this checkout.24
tmp="$(mktemp)"24
tmp="$(mktemp)"@@ -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.target5
5
6
[Service]6
[Service]7
Type=simple7
Type=simple8
EnvironmentFile=-/etc/questward/env8
User=questward9
User=questward9
Group=questward10
Group=questward10
WorkingDirectory=/srv/questward/current11
WorkingDirectory=/srv/questward/current@@ -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"14
git clean -fd14
git clean -fd15
git pull --ff-only origin "$BRANCH" || true15
git pull --ff-only origin "$BRANCH" || true16
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 || true19
17
echo "[deploy] npm install…"20
echo "[deploy] npm install…"18
npm install --omit=dev21
npm install --omit=dev19
22
@@ -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 @@1
export class AuthClient1
export class AuthClient2
{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 AuthClient45
"Authorization": `Bearer ${accessToken}`,45
"Authorization": `Bearer ${accessToken}`,46
"Accept": "application/json",46
"Accept": "application/json",47
"User-Agent": this.config.userAgent47
"User-Agent": this.config.userAgent48
}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 AuthClient92
"Accept": "application/json",93
"Accept": "application/json",93
"User-Agent": this.config.userAgent94
"User-Agent": this.config.userAgent94
}95
}95
}).catch(() => {});96
}).catch(() => { });96
}97
}97
}98
}98
99
@@ -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
catch47
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.stub60
try59
? 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.stub94
try63
? stateDb.ensureAccount(identity.authSubject, true, identity.email, identity.username)95
{ message = JSON.parse(String(raw)); }64
: await resolveAccount(stateDb, identity);96
catch65
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
try70
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
try107
message: error.userFacing ? error.message : "Request failed."99
{ message = JSON.parse(String(raw)); }108
});100
catch109
}101
{110
});102
send(session, { type: MessageType.error, message: "Invalid JSON." });103
return;104
}105
try106
{ 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.stationId360
? message.stationId351
: 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
stationId367
stationId358
});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, {