BlueGit

timfa questward

Persist OAuth sign-in in a local session cookie for game and editor.

After login via auth.timfalken.com, store a long-lived questward_session in SQLite so HTTP and WebSocket no longer re-call the auth API on every connect when the remote check is unreachable.

timfa Tim Falken · pushed by timfa

Authored 2026-08-28 · 2 months ago

Hash
95b625ccd15d5d102e4eab910df34e94ff4db275
Parent
59b7e9f0
7 files changed +184 −11
server/src/auth/config.js +3 −0
@@ -11,6 +11,9 @@ export function authConfig ()
11 11 clientSecret,
12 12 redirectUri: process.env.QUESTWARD_AUTH_REDIRECT_URI ?? "",
13 13 tokenCookie: "questward_access_token",
14 sessionCookie: "questward_session",
15 /** Local session lifetime after OAuth sign-in (seconds). Survives auth API hiccups. */
16 sessionMaxAgeSec: Number(process.env.QUESTWARD_SESSION_MAX_AGE_SEC ?? 30 * 24 * 3600),
14 17 stateCookie: "questward_oauth_state",
15 18 userAgent: "QuestwardServer/1.0"
16 19 });
@@ -11,6 +11,9 @@ export function authConfig ()
11 clientSecret,
11 clientSecret,
12 redirectUri: process.env.QUESTWARD_AUTH_REDIRECT_URI ?? "",
12 redirectUri: process.env.QUESTWARD_AUTH_REDIRECT_URI ?? "",
13 tokenCookie: "questward_access_token",
13 tokenCookie: "questward_access_token",
14 sessionCookie: "questward_session",
15 /** Local session lifetime after OAuth sign-in (seconds). Survives auth API hiccups. */
16 sessionMaxAgeSec: Number(process.env.QUESTWARD_SESSION_MAX_AGE_SEC ?? 30 * 24 * 3600),
14 stateCookie: "questward_oauth_state",
17 stateCookie: "questward_oauth_state",
15 userAgent: "QuestwardServer/1.0"
18 userAgent: "QuestwardServer/1.0"
16 });
19 });
server/src/auth/index.js +2 −2
@@ -2,7 +2,7 @@ import { authConfig, useAuthStub } from "./config.js";
2 2 import { StubAuth } from "./stub.js";
3 3 import { OAuthAuth } from "./oauth.js";
4 4
5 export function createAuth ()
5 export function createAuth (stateDb = null)
6 6 {
7 7 const config = authConfig();
8 8 if (useAuthStub(config))
@@ -11,7 +11,7 @@ export function createAuth ()
11 11 return new StubAuth();
12 12 }
13 13 console.log(`[auth] OAuth via ${config.baseUrl} (client_id=${config.clientId}).`);
14 return new OAuthAuth(config);
14 return new OAuthAuth(config, undefined, stateDb);
15 15 }
16 16
17 17 export { authConfig, useAuthStub };
@@ -2,7 +2,7 @@ import { authConfig, useAuthStub } from "./config.js";
2import { StubAuth } from "./stub.js";
2import { StubAuth } from "./stub.js";
3import { OAuthAuth } from "./oauth.js";
3import { OAuthAuth } from "./oauth.js";
4
4
5export function createAuth ()
5export function createAuth (stateDb = null)
6{
6{
7 const config = authConfig();
7 const config = authConfig();
8 if (useAuthStub(config))
8 if (useAuthStub(config))
@@ -11,7 +11,7 @@ export function createAuth ()
11 return new StubAuth();
11 return new StubAuth();
12 }
12 }
13 console.log(`[auth] OAuth via ${config.baseUrl} (client_id=${config.clientId}).`);
13 console.log(`[auth] OAuth via ${config.baseUrl} (client_id=${config.clientId}).`);
14 return new OAuthAuth(config);
14 return new OAuthAuth(config, undefined, stateDb);
15}
15}
16
16
17export { authConfig, useAuthStub };
17export { authConfig, useAuthStub };
server/src/auth/oauth.js +94 −7
@@ -6,10 +6,11 @@ const EXTEND_INTERVAL_MS = 45 * 60 * 1000;
6 6
7 7 export class OAuthAuth
8 8 {
9 constructor (config, client = new AuthClient(config))
9 constructor (config, client = new AuthClient(config), stateDb = null)
10 10 {
11 11 this.config = config;
12 12 this.client = client;
13 this.stateDb = stateDb;
13 14 this.sessions = new Set();
14 15 }
15 16
@@ -85,11 +86,20 @@ export class OAuthAuth
85 86 code,
86 87 redirectUri: this.redirectUriFor(req)
87 88 });
88 setCookie(res, this.config.tokenCookie, tokenPayload.access_token, {
89 const token = tokenPayload.access_token;
90 const user = await this.client.fetchMe(token);
91 if (!user)
92 {
93 throw new Error("Could not load your account profile after sign-in.");
94 }
95 const identity = identityFromUser(user, token);
96 this.#clearLocalSession(res, req, cookies);
97 setCookie(res, this.config.tokenCookie, token, {
89 98 maxAgeSec: tokenPayload.expires_in ?? 3600,
90 99 secure,
91 100 httpOnly: true
92 101 });
102 this.#issueLocalSession(res, req, identity);
93 103 res.writeHead(302, { Location: returnTo });
94 104 res.end();
95 105 }
@@ -107,15 +117,16 @@ export class OAuthAuth
107 117 const secure = isSecureRequest(req);
108 118 const cookies = parseCookies(req.headers.cookie);
109 119 const token = cookies[this.config.tokenCookie];
120 this.#clearLocalSession(res, req, cookies);
110 121 await this.client.revokeToken(token);
111 122 clearCookie(res, this.config.tokenCookie, { secure });
112 123 res.writeHead(302, { Location: safeReturnTo(returnTo) });
113 124 res.end();
114 125 }
115 126
116 async statusFromRequest (req)
127 async statusFromRequest (req, res = null)
117 128 {
118 const identity = await this.authenticateRequest(req);
129 const identity = await this.authenticateRequest(req, res);
119 130 if (!identity)
120 131 { return { authenticated: false }; }
121 132 return {
@@ -126,16 +137,36 @@ export class OAuthAuth
126 137 };
127 138 }
128 139
129 async authenticateRequest (req)
140 async authenticateRequest (req, res = null)
130 141 {
131 142 const cookies = parseCookies(req.headers.cookie);
143 const localIdentity = this.#identityFromLocalSession(cookies);
144 if (localIdentity)
145 { return localIdentity; }
146
132 147 const token = cookies[this.config.tokenCookie];
133 148 if (!token)
134 149 { return null; }
135 const user = await this.client.fetchMe(token);
150
151 let user;
152 try
153 {
154 user = await this.client.fetchMe(token);
155 }
156 catch
157 {
158 return null;
159 }
136 160 if (!user)
137 161 { return null; }
138 return identityFromUser(user, token);
162
163 const identity = identityFromUser(user, token);
164 if (res)
165 {
166 this.#clearLocalSession(res, req, cookies);
167 this.#issueLocalSession(res, req, identity);
168 }
169 return identity;
139 170 }
140 171
141 172 startSessionMaintenance (session)
@@ -149,6 +180,62 @@ export class OAuthAuth
149 180 if (typeof session.extendTimer.unref === "function")
150 181 { session.extendTimer.unref(); }
151 182 }
183
184 #identityFromLocalSession (cookies)
185 {
186 if (!this.stateDb)
187 { return null; }
188 const sessionId = cookies[this.config.sessionCookie];
189 if (!sessionId)
190 { return null; }
191 const row = this.stateDb.getAuthSession(sessionId);
192 if (!row)
193 { return null; }
194 if (row.expires_at <= Date.now())
195 {
196 this.stateDb.deleteAuthSession(sessionId);
197 return null;
198 }
199 return {
200 authSubject: row.auth_subject,
201 username: row.username ?? null,
202 email: row.email ?? null,
203 accessToken: row.access_token ?? null,
204 localSession: true
205 };
206 }
207
208 #issueLocalSession (res, req, identity)
209 {
210 if (!this.stateDb)
211 { return; }
212 const secure = isSecureRequest(req);
213 const sessionId = randomBytes(32).toString("hex");
214 const maxAgeSec = this.config.sessionMaxAgeSec;
215 this.stateDb.createAuthSession({
216 sessionId,
217 authSubject: identity.authSubject,
218 username: identity.username ?? null,
219 email: identity.email ?? null,
220 accessToken: identity.accessToken ?? null,
221 expiresAtMs: Date.now() + maxAgeSec * 1000
222 });
223 setCookie(res, this.config.sessionCookie, sessionId, {
224 maxAgeSec,
225 secure,
226 httpOnly: true
227 });
228 }
229
230 #clearLocalSession (res, req, cookies)
231 {
232 if (!this.stateDb)
233 { return; }
234 const secure = isSecureRequest(req);
235 const sessionId = cookies[this.config.sessionCookie];
236 this.stateDb.deleteAuthSession(sessionId);
237 clearCookie(res, this.config.sessionCookie, { secure });
238 }
152 239 }
153 240
154 241 function safeReturnTo (value)
@@ -6,10 +6,11 @@ const EXTEND_INTERVAL_MS = 45 * 60 * 1000;
6
6
7export class OAuthAuth
7export class OAuthAuth
8{
8{
9 constructor (config, client = new AuthClient(config))
9 constructor (config, client = new AuthClient(config), stateDb = null)
10 {
10 {
11 this.config = config;
11 this.config = config;
12 this.client = client;
12 this.client = client;
13 this.stateDb = stateDb;
13 this.sessions = new Set();
14 this.sessions = new Set();
14 }
15 }
15
16
@@ -85,11 +86,20 @@ export class OAuthAuth
85 code,
86 code,
86 redirectUri: this.redirectUriFor(req)
87 redirectUri: this.redirectUriFor(req)
87 });
88 });
88 setCookie(res, this.config.tokenCookie, tokenPayload.access_token, {
89 const token = tokenPayload.access_token;
90 const user = await this.client.fetchMe(token);
91 if (!user)
92 {
93 throw new Error("Could not load your account profile after sign-in.");
94 }
95 const identity = identityFromUser(user, token);
96 this.#clearLocalSession(res, req, cookies);
97 setCookie(res, this.config.tokenCookie, token, {
89 maxAgeSec: tokenPayload.expires_in ?? 3600,
98 maxAgeSec: tokenPayload.expires_in ?? 3600,
90 secure,
99 secure,
91 httpOnly: true
100 httpOnly: true
92 });
101 });
102 this.#issueLocalSession(res, req, identity);
93 res.writeHead(302, { Location: returnTo });
103 res.writeHead(302, { Location: returnTo });
94 res.end();
104 res.end();
95 }
105 }
@@ -107,15 +117,16 @@ export class OAuthAuth
107 const secure = isSecureRequest(req);
117 const secure = isSecureRequest(req);
108 const cookies = parseCookies(req.headers.cookie);
118 const cookies = parseCookies(req.headers.cookie);
109 const token = cookies[this.config.tokenCookie];
119 const token = cookies[this.config.tokenCookie];
120 this.#clearLocalSession(res, req, cookies);
110 await this.client.revokeToken(token);
121 await this.client.revokeToken(token);
111 clearCookie(res, this.config.tokenCookie, { secure });
122 clearCookie(res, this.config.tokenCookie, { secure });
112 res.writeHead(302, { Location: safeReturnTo(returnTo) });
123 res.writeHead(302, { Location: safeReturnTo(returnTo) });
113 res.end();
124 res.end();
114 }
125 }
115
126
116 async statusFromRequest (req)
127 async statusFromRequest (req, res = null)
117 {
128 {
118 const identity = await this.authenticateRequest(req);
129 const identity = await this.authenticateRequest(req, res);
119 if (!identity)
130 if (!identity)
120 { return { authenticated: false }; }
131 { return { authenticated: false }; }
121 return {
132 return {
@@ -126,16 +137,36 @@ export class OAuthAuth
126 };
137 };
127 }
138 }
128
139
129 async authenticateRequest (req)
140 async authenticateRequest (req, res = null)
130 {
141 {
131 const cookies = parseCookies(req.headers.cookie);
142 const cookies = parseCookies(req.headers.cookie);
143 const localIdentity = this.#identityFromLocalSession(cookies);
144 if (localIdentity)
145 { return localIdentity; }
146
132 const token = cookies[this.config.tokenCookie];
147 const token = cookies[this.config.tokenCookie];
133 if (!token)
148 if (!token)
134 { return null; }
149 { return null; }
135 const user = await this.client.fetchMe(token);
150
151 let user;
152 try
153 {
154 user = await this.client.fetchMe(token);
155 }
156 catch
157 {
158 return null;
159 }
136 if (!user)
160 if (!user)
137 { return null; }
161 { return null; }
138 return identityFromUser(user, token);
162
163 const identity = identityFromUser(user, token);
164 if (res)
165 {
166 this.#clearLocalSession(res, req, cookies);
167 this.#issueLocalSession(res, req, identity);
168 }
169 return identity;
139 }
170 }
140
171
141 startSessionMaintenance (session)
172 startSessionMaintenance (session)
@@ -149,6 +180,62 @@ export class OAuthAuth
149 if (typeof session.extendTimer.unref === "function")
180 if (typeof session.extendTimer.unref === "function")
150 { session.extendTimer.unref(); }
181 { session.extendTimer.unref(); }
151 }
182 }
183
184 #identityFromLocalSession (cookies)
185 {
186 if (!this.stateDb)
187 { return null; }
188 const sessionId = cookies[this.config.sessionCookie];
189 if (!sessionId)
190 { return null; }
191 const row = this.stateDb.getAuthSession(sessionId);
192 if (!row)
193 { return null; }
194 if (row.expires_at <= Date.now())
195 {
196 this.stateDb.deleteAuthSession(sessionId);
197 return null;
198 }
199 return {
200 authSubject: row.auth_subject,
201 username: row.username ?? null,
202 email: row.email ?? null,
203 accessToken: row.access_token ?? null,
204 localSession: true
205 };
206 }
207
208 #issueLocalSession (res, req, identity)
209 {
210 if (!this.stateDb)
211 { return; }
212 const secure = isSecureRequest(req);
213 const sessionId = randomBytes(32).toString("hex");
214 const maxAgeSec = this.config.sessionMaxAgeSec;
215 this.stateDb.createAuthSession({
216 sessionId,
217 authSubject: identity.authSubject,
218 username: identity.username ?? null,
219 email: identity.email ?? null,
220 accessToken: identity.accessToken ?? null,
221 expiresAtMs: Date.now() + maxAgeSec * 1000
222 });
223 setCookie(res, this.config.sessionCookie, sessionId, {
224 maxAgeSec,
225 secure,
226 httpOnly: true
227 });
228 }
229
230 #clearLocalSession (res, req, cookies)
231 {
232 if (!this.stateDb)
233 { return; }
234 const secure = isSecureRequest(req);
235 const sessionId = cookies[this.config.sessionCookie];
236 this.stateDb.deleteAuthSession(sessionId);
237 clearCookie(res, this.config.sessionCookie, { secure });
238 }
152}
239}
153
240
154function safeReturnTo (value)
241function safeReturnTo (value)
server/src/auth/routes.js +1 −1
@@ -6,7 +6,7 @@ export async function handleAuthRoute (req, res, url, { auth, stateDb })
6 6 {
7 7 if (url.pathname === "/auth/status" && req.method === "GET")
8 8 {
9 const status = await auth.statusFromRequest(req);
9 const status = await auth.statusFromRequest(req, res);
10 10 sendJson(res, 200, status);
11 11 return true;
12 12 }
@@ -6,7 +6,7 @@ export async function handleAuthRoute (req, res, url, { auth, stateDb })
6 {
6 {
7 if (url.pathname === "/auth/status" && req.method === "GET")
7 if (url.pathname === "/auth/status" && req.method === "GET")
8 {
8 {
9 const status = await auth.statusFromRequest(req);
9 const status = await auth.statusFromRequest(req, res);
10 sendJson(res, 200, status);
10 sendJson(res, 200, status);
11 return true;
11 return true;
12 }
12 }
server/src/index.js +1 −1
@@ -24,7 +24,7 @@ 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 = createAuth();
27 const auth = createAuth(stateDb);
28 28 const httpServer = createHttpServer(rootDir, { auth, stateDb });
29 29
30 30 const deployBridge = {
@@ -24,7 +24,7 @@ const editor = new EditorService(worldDb);
24const characters = new CharacterService(stateDb, console);
24const characters = new CharacterService(stateDb, console);
25const friends = new FriendService(stateDb);
25const friends = new FriendService(stateDb);
26const simulation = new Simulation(worldDb, stateDb);
26const simulation = new Simulation(worldDb, stateDb);
27const auth = createAuth();
27const auth = createAuth(stateDb);
28const httpServer = createHttpServer(rootDir, { auth, stateDb });
28const httpServer = createHttpServer(rootDir, { auth, stateDb });
29
29
30const deployBridge = {
30const deployBridge = {
server/src/persistence/stateDb.js +37 −0
@@ -254,9 +254,46 @@ export class StateDatabase
254 254 const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();
255 255 if (!accountColumns.some((column) => column.name === "username"))
256 256 { this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }
257 this.db.exec(`
258 CREATE TABLE IF NOT EXISTS auth_sessions (
259 session_id TEXT PRIMARY KEY,
260 auth_subject TEXT NOT NULL,
261 username TEXT,
262 email TEXT,
263 access_token TEXT,
264 expires_at INTEGER NOT NULL
265 )
266 `);
267 this.db.exec(`
268 CREATE INDEX IF NOT EXISTS auth_sessions_subject ON auth_sessions(auth_subject)
269 `);
257 270 this.#grantLanternsToExistingCharacters();
258 271 }
259 272
273 createAuthSession ({ sessionId, authSubject, username = null, email = null, accessToken = null, expiresAtMs })
274 {
275 this.db.prepare(`
276 INSERT INTO auth_sessions (session_id, auth_subject, username, email, access_token, expires_at)
277 VALUES (?, ?, ?, ?, ?, ?)
278 `).run(sessionId, authSubject, username, email, accessToken, expiresAtMs);
279 }
280
281 getAuthSession (sessionId)
282 {
283 return this.db.prepare(`
284 SELECT session_id, auth_subject, username, email, access_token, expires_at
285 FROM auth_sessions
286 WHERE session_id = ?
287 `).get(sessionId) ?? null;
288 }
289
290 deleteAuthSession (sessionId)
291 {
292 if (!sessionId)
293 { return; }
294 this.db.prepare("DELETE FROM auth_sessions WHERE session_id = ?").run(sessionId);
295 }
296
260 297 #grantLanternsToExistingCharacters ()
261 298 {
262 299 const def = itemDefinition(ItemId.lantern);
@@ -254,9 +254,46 @@ export class StateDatabase
254 const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();
254 const accountColumns = this.db.prepare("PRAGMA table_info(accounts)").all();
255 if (!accountColumns.some((column) => column.name === "username"))
255 if (!accountColumns.some((column) => column.name === "username"))
256 { this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }
256 { this.db.exec("ALTER TABLE accounts ADD COLUMN username TEXT"); }
257 this.db.exec(`
258 CREATE TABLE IF NOT EXISTS auth_sessions (
259 session_id TEXT PRIMARY KEY,
260 auth_subject TEXT NOT NULL,
261 username TEXT,
262 email TEXT,
263 access_token TEXT,
264 expires_at INTEGER NOT NULL
265 )
266 `);
267 this.db.exec(`
268 CREATE INDEX IF NOT EXISTS auth_sessions_subject ON auth_sessions(auth_subject)
269 `);
257 this.#grantLanternsToExistingCharacters();
270 this.#grantLanternsToExistingCharacters();
258 }
271 }
259
272
273 createAuthSession ({ sessionId, authSubject, username = null, email = null, accessToken = null, expiresAtMs })
274 {
275 this.db.prepare(`
276 INSERT INTO auth_sessions (session_id, auth_subject, username, email, access_token, expires_at)
277 VALUES (?, ?, ?, ?, ?, ?)
278 `).run(sessionId, authSubject, username, email, accessToken, expiresAtMs);
279 }
280
281 getAuthSession (sessionId)
282 {
283 return this.db.prepare(`
284 SELECT session_id, auth_subject, username, email, access_token, expires_at
285 FROM auth_sessions
286 WHERE session_id = ?
287 `).get(sessionId) ?? null;
288 }
289
290 deleteAuthSession (sessionId)
291 {
292 if (!sessionId)
293 { return; }
294 this.db.prepare("DELETE FROM auth_sessions WHERE session_id = ?").run(sessionId);
295 }
296
260 #grantLanternsToExistingCharacters ()
297 #grantLanternsToExistingCharacters ()
261 {
298 {
262 const def = itemDefinition(ItemId.lantern);
299 const def = itemDefinition(ItemId.lantern);
server/tests/authSession.test.js added +46 −0
@@ -0,0 +1,46 @@
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 { OAuthAuth } from "../src/auth/oauth.js";
7 import { authConfig } from "../src/auth/config.js";
8 import { StateDatabase } from "../src/persistence/stateDb.js";
9
10 test("local auth session resolves identity without calling auth API", async () =>
11 {
12 const dir = mkdtempSync(join(tmpdir(), "questward-auth-session-"));
13 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
14 const config = {
15 ...authConfig(),
16 sessionCookie: "questward_session",
17 sessionMaxAgeSec: 3600,
18 tokenCookie: "questward_access_token"
19 };
20 const auth = new OAuthAuth(config, {
21 async fetchMe ()
22 {
23 throw new Error("auth API should not be called when local session is valid");
24 }
25 }, stateDb);
26
27 const sessionId = "test-session-id";
28 stateDb.createAuthSession({
29 sessionId,
30 authSubject: "auth:42",
31 username: "player",
32 email: "player@example.com",
33 accessToken: "remote-token",
34 expiresAtMs: Date.now() + 3600_000
35 });
36
37 const identity = await auth.authenticateRequest({
38 headers: {
39 cookie: `questward_session=${sessionId}; questward_access_token=ignored`
40 }
41 });
42
43 assert.equal(identity?.authSubject, "auth:42");
44 assert.equal(identity?.username, "player");
45 assert.equal(identity?.localSession, true);
46 });
@@ -0,0 +1,46 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { mkdtempSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6import { OAuthAuth } from "../src/auth/oauth.js";
7import { authConfig } from "../src/auth/config.js";
8import { StateDatabase } from "../src/persistence/stateDb.js";
9
10test("local auth session resolves identity without calling auth API", async () =>
11{
12 const dir = mkdtempSync(join(tmpdir(), "questward-auth-session-"));
13 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
14 const config = {
15 ...authConfig(),
16 sessionCookie: "questward_session",
17 sessionMaxAgeSec: 3600,
18 tokenCookie: "questward_access_token"
19 };
20 const auth = new OAuthAuth(config, {
21 async fetchMe ()
22 {
23 throw new Error("auth API should not be called when local session is valid");
24 }
25 }, stateDb);
26
27 const sessionId = "test-session-id";
28 stateDb.createAuthSession({
29 sessionId,
30 authSubject: "auth:42",
31 username: "player",
32 email: "player@example.com",
33 accessToken: "remote-token",
34 expiresAtMs: Date.now() + 3600_000
35 });
36
37 const identity = await auth.authenticateRequest({
38 headers: {
39 cookie: `questward_session=${sessionId}; questward_access_token=ignored`
40 }
41 });
42
43 assert.equal(identity?.authSubject, "auth:42");
44 assert.equal(identity?.username, "player");
45 assert.equal(identity?.localSession, true);
46});