@genesislcap/mock-server 15.66.0 → 15.68.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -4,9 +4,10 @@ import { recordKey } from "./db/identity.js";
4
4
  import { compareRecordIds } from "./db/ordering.js";
5
5
  import { Store } from "./db/store.js";
6
6
  import { entriesReading, planView, } from "./db/views.js";
7
+ import { createAuthState } from "./handlers/auth.js";
7
8
  import { crudEventHandler } from "./handlers/crudEvents.js";
8
9
  import { pendingKey, viewRow, waitForPage } from "./handlers/dataLogon.js";
9
- import { createHttpRequestListener } from "./handlers/http.js";
10
+ import { cookieAuthentication, createHttpRequestListener, parseCookies, SESSION_AUTH_TOKEN_COOKIE, } from "./handlers/http.js";
10
11
  import { permittedQueryRow, requestingUser } from "./handlers/resourceAuth.js";
11
12
  import { Connection } from "./protocol/connection.js";
12
13
  import { isLegacyFidelity, liveModifyMode } from "./protocol/fidelity.js";
@@ -58,6 +59,8 @@ function oldestHeld(held) {
58
59
  }
59
60
  return oldest;
60
61
  }
62
+ // The status a cookie-authenticated router refuses an upgrade with.
63
+ const HTTP_UNAUTHORIZED = 401;
61
64
  export function createMockServer(config) {
62
65
  // Declared columns are held by type (db/values.ts), except under
63
66
  // fidelity: 'legacy', which keeps rows as given.
@@ -460,13 +463,14 @@ export function createMockServer(config) {
460
463
  }
461
464
  }
462
465
  };
463
- const httpSessions = new Map(); // sessionId -> username, for the HTTP login transport (see handlers/http.ts)
464
- // Every SESSION_AUTH_TOKEN/REFRESH_AUTH_TOKEN this server has issued (over
465
- // either transport) -> username. Lets a WS connection authenticate with a
466
- // token from an earlier HTTP login (foundation-comms sends the stored
467
- // SESSION_AUTH_TOKEN on every message, and its token-refresh path sends
468
- // EVENT_LOGIN_AUTH with only DETAILS.REFRESH_AUTH_TOKEN — no credentials).
469
- const issuedTokens = new Map();
466
+ // fidelity: 'legacy' HTTP sessions, MOCK_SESSION_ID -> username (handlers/http.ts).
467
+ const legacyHttpSessions = new Map();
468
+ // Sessions and tokens issued over either transport (handlers/auth.ts), so a
469
+ // WS connection can authenticate with a token from an earlier HTTP login
470
+ // (foundation-comms sends the stored SESSION_AUTH_TOKEN on every message, and
471
+ // its token refresh sends EVENT_LOGIN_AUTH with only
472
+ // DETAILS.REFRESH_AUTH_TOKEN, no credentials).
473
+ const auth = createAuthState();
470
474
  // Runtime override/extend API. Every handler reads off this same `config`
471
475
  // object at call time (both the WS path in routeMessage below and the HTTP
472
476
  // login transport, whose handler was created once in start() and holds a
@@ -527,10 +531,24 @@ export function createMockServer(config) {
527
531
  // node:http + the `ws` package rather than a runtime-specific API (e.g.
528
532
  // Bun.serve) so this runs unmodified under both Node (>=22.6, via
529
533
  // `node --experimental-strip-types`) and Bun.
530
- httpServer = http.createServer(createHttpRequestListener(config, httpSessions, issuedTokens));
531
- wss = new WebSocketServer({ server: httpServer });
532
- wss.on('connection', (ws) => {
534
+ httpServer = http.createServer(createHttpRequestListener(config, legacyHttpSessions, auth));
535
+ // A cookie-authenticated router answers an upgrade without a live
536
+ // sessionAuthToken cookie with HTTP 401 (PreHttpHandlerProvider.kt:61-95
537
+ // @v8.15.29). Read per upgrade, like every config field.
538
+ const cookieToken = (req) => parseCookies(req.headers.cookie)[SESSION_AUTH_TOKEN_COOKIE];
539
+ wss = new WebSocketServer({
540
+ server: httpServer,
541
+ verifyClient: ({ req }, done) => {
542
+ if (!cookieAuthentication(config))
543
+ return done(true);
544
+ const token = cookieToken(req);
545
+ done(token !== undefined && auth.sessions.has(token), HTTP_UNAUTHORIZED);
546
+ },
547
+ });
548
+ wss.on('connection', (ws, req) => {
533
549
  const connection = new Connection(ws);
550
+ if (cookieAuthentication(config))
551
+ connection.cookieSessionAuthToken = cookieToken(req);
534
552
  connections.add(connection);
535
553
  ws.on('message', (data) => {
536
554
  let message;
@@ -557,7 +575,7 @@ export function createMockServer(config) {
557
575
  if (hooked)
558
576
  message = hooked;
559
577
  }
560
- routeMessage(message, connection, config, store, { broadcast, broadcastTableChange }, issuedTokens);
578
+ routeMessage(message, connection, config, store, { broadcast, broadcastTableChange }, auth);
561
579
  }
562
580
  catch (error) {
563
581
  console.error(`[mock-server] Error handling ${message.MESSAGE_TYPE}:`, error);
package/dist/types.d.ts CHANGED
@@ -138,6 +138,19 @@ export interface AuthUser {
138
138
  profile?: string[];
139
139
  permission?: string[];
140
140
  user?: Row;
141
+ loginAck?: Row;
142
+ }
143
+ export interface CookieAuthenticationOptions {
144
+ httpOnly?: boolean;
145
+ secure?: boolean;
146
+ sameSite?: 'Strict' | 'Lax' | 'None';
147
+ path?: string;
148
+ domain?: string;
149
+ sessionCookies?: boolean;
150
+ }
151
+ export interface ProductDetails {
152
+ NAME: string;
153
+ VERSION: string;
141
154
  }
142
155
  export interface SsoIdentityProvider {
143
156
  ID: string;
@@ -149,6 +162,10 @@ export interface AuthConfig {
149
162
  users?: AuthUser[];
150
163
  ssoIdentityProviders?: SsoIdentityProvider[];
151
164
  heartbeatIntervalSecs?: number;
165
+ sessionTimeoutMins?: number;
166
+ refreshTokenExpirationMins?: number;
167
+ products?: ProductDetails[];
168
+ cookieAuthentication?: boolean | CookieAuthenticationOptions;
152
169
  httpAutoLogin?: string | true;
153
170
  requireAuth?: boolean;
154
171
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@genesislcap/mock-server",
3
- "version": "15.66.0",
3
+ "version": "15.68.0",
4
4
  "description": "Reusable in-memory Genesis WebSocket protocol mock server for client automation/CI, without a JVM or database.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1,9 +1,30 @@
1
1
  import crypto from 'node:crypto';
2
2
  import type { Connection } from '../protocol/connection.ts';
3
+ import { isLegacyFidelity } from '../protocol/fidelity.ts';
3
4
  import { MESSAGE_TYPE, ERROR_CODE } from '../protocol/messageTypes.ts';
4
- import type { AuthUser, GenesisMessage, MockServerConfig, Row } from '../types.ts';
5
+ import type { AuthUser, GenesisMessage, MockServerConfig, ProductDetails, Row } from '../types.ts';
5
6
 
6
- const DEFAULT_HEARTBEAT_INTERVAL_SECS = 30;
7
+ const LEGACY_HEARTBEAT_INTERVAL_SECS = 30;
8
+ // auth 8.15.5 AuthPreferencesDefinition.kt:17,19 defaults.
9
+ const DEFAULT_SESSION_TIMEOUT_MINS = 30;
10
+ const DEFAULT_REFRESH_TOKEN_EXPIRATION_MINS = 7200;
11
+ // LoginProcessor.kt:176-177 @auth v8.15.5: a user with no password expiry date.
12
+ const DAYS_TO_PASSWORD_EXPIRY_NONE = 730; // 2 * 365
13
+ // The versions this mock follows (test/conformance/README.md).
14
+ const DEFAULT_PRODUCTS: ProductDetails[] = [
15
+ { NAME: 'auth', VERSION: '8.15.5' },
16
+ { NAME: 'genesis', VERSION: '8.15.29' },
17
+ ];
18
+ // What a stock ZeroMQ install reports (LoginProcessor.kt:247-256 @auth
19
+ // v8.15.5; the values recorded in http-login.json). The mock has no update
20
+ // queue, and no client reads this.
21
+ const UPDATE_QUEUE_DETAILS: Row = {
22
+ UPDATE_QUEUE: 'ZeroMq',
23
+ ZERO_MQ_PROXY_MODE_ENABLED: false,
24
+ ZERO_MQ_PROXY_INBOUND_PORT: 5001,
25
+ ZERO_MQ_PROXY_OUTBOUND_PORT: 5000,
26
+ AERON_SERVICE_PORT: null,
27
+ };
7
28
 
8
29
  // Every SESSION_AUTH_TOKEN/REFRESH_AUTH_TOKEN issued by this server -> the
9
30
  // username it was issued to. Shared across the WS and HTTP transports so a
@@ -12,12 +33,35 @@ const DEFAULT_HEARTBEAT_INTERVAL_SECS = 30;
12
33
  // DETAILS.REFRESH_AUTH_TOKEN, no credentials) can succeed.
13
34
  export type TokenRegistry = Map<string, string>;
14
35
 
36
+ // A login session, as auth's USER_SESSION row holds it.
37
+ export interface AuthSession {
38
+ username: string;
39
+ sessionAuthToken: string;
40
+ refreshAuthToken: string;
41
+ sessionId: string;
42
+ }
43
+
44
+ // The auth state both transports share.
45
+ export interface AuthState {
46
+ tokens: TokenRegistry;
47
+ // Live sessions by SESSION_AUTH_TOKEN. event-login-details answers with the
48
+ // session's own tokens, and a cookie-authenticated socket needs one.
49
+ sessions: Map<string, AuthSession>;
50
+ // username -> epoch millis of their latest login (USER_LOGIN's
51
+ // LAST_LOGIN_DATETIME, the ack's DETAILS.LAST_LOGIN_DATE_TIME).
52
+ lastLogin: Map<string, number>;
53
+ }
54
+
55
+ export function createAuthState(): AuthState {
56
+ return { tokens: new Map(), sessions: new Map(), lastLogin: new Map() };
57
+ }
58
+
15
59
  // Both transports mint tokens on every login/silent-login, so a long-lived
16
60
  // dev/CI server would otherwise grow these maps one entry per page load.
17
61
  // Maps iterate in insertion order, so dropping from the front evicts the
18
62
  // oldest sessions/tokens first.
19
63
  const MAX_REGISTRY_ENTRIES = 1000;
20
- export function capRegistry(registry: Map<string, string>): void {
64
+ export function capRegistry(registry: Map<string, unknown>): void {
21
65
  while (registry.size > MAX_REGISTRY_ENTRIES) {
22
66
  const oldest = registry.keys().next().value;
23
67
  if (oldest === undefined) return;
@@ -25,26 +69,132 @@ export function capRegistry(registry: Map<string, string>): void {
25
69
  }
26
70
  }
27
71
 
28
- export function registerAckTokens(ack: Row, username: string, tokens: TokenRegistry): void {
29
- tokens.set(ack.SESSION_AUTH_TOKEN, username);
30
- tokens.set(ack.REFRESH_AUTH_TOKEN, username);
31
- capRegistry(tokens);
72
+ export function openSession(auth: AuthState, user: AuthUser): AuthSession {
73
+ const session: AuthSession = {
74
+ username: user.username,
75
+ sessionAuthToken: crypto.randomUUID(),
76
+ refreshAuthToken: crypto.randomUUID(),
77
+ sessionId: crypto.randomUUID(),
78
+ };
79
+ auth.sessions.set(session.sessionAuthToken, session);
80
+ capRegistry(auth.sessions);
81
+ auth.tokens.set(session.sessionAuthToken, user.username);
82
+ auth.tokens.set(session.refreshAuthToken, user.username);
83
+ capRegistry(auth.tokens);
84
+ auth.lastLogin.set(user.username, Date.now());
85
+ return session;
86
+ }
87
+
88
+ // Revokes the session's tokens, not just the session: every message
89
+ // re-adopts a stamped SESSION_AUTH_TOKEN (see router.ts), so a token left in
90
+ // the registry silently logs a connection straight back in.
91
+ export function closeSession(auth: AuthState, session: AuthSession): void {
92
+ auth.sessions.delete(session.sessionAuthToken);
93
+ auth.tokens.delete(session.sessionAuthToken);
94
+ auth.tokens.delete(session.refreshAuthToken);
95
+ }
96
+
97
+ export function sessionByRefreshToken(
98
+ auth: AuthState,
99
+ refreshAuthToken: unknown,
100
+ ): AuthSession | undefined {
101
+ if (typeof refreshAuthToken !== 'string') return undefined;
102
+ for (const session of auth.sessions.values()) {
103
+ if (session.refreshAuthToken === refreshAuthToken) return session;
104
+ }
105
+ return undefined;
106
+ }
107
+
108
+ export function sessionTimeoutMins(config: MockServerConfig): number {
109
+ return config.auth?.sessionTimeoutMins ?? DEFAULT_SESSION_TIMEOUT_MINS;
110
+ }
111
+
112
+ export function refreshTokenExpirationMins(config: MockServerConfig): number {
113
+ return config.auth?.refreshTokenExpirationMins ?? DEFAULT_REFRESH_TOKEN_EXPIRATION_MINS;
32
114
  }
33
115
 
34
- // Shared by the WS EVENT_LOGIN_AUTH handler and the HTTP login handlers
35
- // (handlers/http.ts) — EVENT_LOGIN_DETAILS_ACK is byte-for-byte the same shape
36
- // as EVENT_LOGIN_AUTH_ACK, just under a different MESSAGE_TYPE (see
37
- // foundation-auth's EVENT_LOGIN_DETAILS_ACK.ts, which literally extends it).
116
+ const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
117
+ const MONTH_NAMES = [
118
+ 'Jan',
119
+ 'Feb',
120
+ 'Mar',
121
+ 'Apr',
122
+ 'May',
123
+ 'Jun',
124
+ 'Jul',
125
+ 'Aug',
126
+ 'Sep',
127
+ 'Oct',
128
+ 'Nov',
129
+ 'Dec',
130
+ ];
131
+
132
+ // java.util.Date#toString in UTC ("Thu Oct 01 13:05:42 UTC 2026"), which is
133
+ // what auth sends as DETAILS.SYSTEM.DATE (LoginProcessor.kt:228).
134
+ export function javaDateString(date: Date): string {
135
+ const pad = (value: number) => String(value).padStart(2, '0');
136
+ const time = [date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()].map(pad).join(':');
137
+ return `${DAY_NAMES[date.getUTCDay()]} ${MONTH_NAMES[date.getUTCMonth()]} ${pad(date.getUTCDate())} ${time} UTC ${date.getUTCFullYear()}`;
138
+ }
139
+
140
+ // The login ack, GSF auth 8.15.5 (LoginProcessor.successfulLoginMessage,
141
+ // LoginProcessor.kt:163-245; field names from Events.kt:66-114). Recorded in
142
+ // http-login.json. EVENT_LOGIN_DETAILS_ACK is the same body under its own
143
+ // MESSAGE_TYPE (Events.kt:79-82), built afresh for the same session
144
+ // (auth-login-eventhandler.kts:84-116). Nothing here is a login count: a
145
+ // successful login resets FAILED_ and REJECTED_LOGIN_ATTEMPTS to 0
146
+ // (LoginAuditController.kt:63,187).
38
147
  export function buildLoginAckBody(
39
148
  user: AuthUser,
149
+ session: AuthSession,
40
150
  config: MockServerConfig,
151
+ auth: AuthState,
41
152
  messageType: string = MESSAGE_TYPE.EVENT_LOGIN_AUTH_ACK,
42
153
  ): Row {
154
+ if (isLegacyFidelity(config)) return buildLegacyLoginAckBody(user, session, config, messageType);
43
155
  return {
156
+ SESSION_AUTH_TOKEN: session.sessionAuthToken,
157
+ REFRESH_AUTH_TOKEN: session.refreshAuthToken,
158
+ SESSION_ID: session.sessionId,
159
+ USER_NAME: user.username,
160
+ DETAILS: {
161
+ HEARTBEAT_INTERVAL_SECONDS: config.auth?.heartbeatIntervalSecs ?? 0,
162
+ SESSION_TIMEOUT_MINS: sessionTimeoutMins(config),
163
+ REFRESH_TOKEN_EXPIRATION_MINS: refreshTokenExpirationMins(config),
164
+ FAILED_LOGIN_ATTEMPTS: 0,
165
+ REJECTED_LOGIN_ATTEMPTS: 0,
166
+ LAST_LOGIN_DATE_TIME: auth.lastLogin.get(user.username) ?? null,
167
+ DAYS_TO_PASSWORD_EXPIRY: DAYS_TO_PASSWORD_EXPIRY_NONE,
168
+ NOTIFY_EXPIRY: null,
169
+ MFA_CODE: null,
170
+ MFA_CODE_EXPIRY_MINS: null,
171
+ SYSTEM: { DATE: javaDateString(new Date()) },
172
+ PRODUCT: config.auth?.products ?? DEFAULT_PRODUCTS,
173
+ },
174
+ PERMISSION: user.permission ?? [],
175
+ PROFILE: user.profile ?? [],
176
+ UPDATE_QUEUE_DETAILS: UPDATE_QUEUE_DETAILS,
177
+ USER: user.loginAck ?? null,
178
+ USER_DETAILS: {
179
+ FIRST_NAME: user.user?.FIRST_NAME ?? null,
180
+ LAST_NAME: user.user?.LAST_NAME ?? null,
181
+ },
44
182
  MESSAGE_TYPE: messageType,
45
- SESSION_AUTH_TOKEN: crypto.randomUUID(),
46
- REFRESH_AUTH_TOKEN: crypto.randomUUID(),
47
- SESSION_ID: crypto.randomUUID(),
183
+ };
184
+ }
185
+
186
+ // fidelity: 'legacy': the ack this engine sent up to 15.47.
187
+ function buildLegacyLoginAckBody(
188
+ user: AuthUser,
189
+ session: AuthSession,
190
+ config: MockServerConfig,
191
+ messageType: string,
192
+ ): Row {
193
+ return {
194
+ MESSAGE_TYPE: messageType,
195
+ SESSION_AUTH_TOKEN: session.sessionAuthToken,
196
+ REFRESH_AUTH_TOKEN: session.refreshAuthToken,
197
+ SESSION_ID: session.sessionId,
48
198
  USER_NAME: user.username,
49
199
  UPDATE_QUEUE: 'MOCK',
50
200
  ZERO_MQ_PROXY_MODE_ENABLED: false,
@@ -53,8 +203,7 @@ export function buildLoginAckBody(
53
203
  USER: user.user ?? {},
54
204
  DETAILS: {
55
205
  SYSTEM: { DATE: new Date().toISOString() },
56
- HEARTBEAT_INTERVAL_SECS:
57
- config.auth?.heartbeatIntervalSecs ?? DEFAULT_HEARTBEAT_INTERVAL_SECS,
206
+ HEARTBEAT_INTERVAL_SECS: config.auth?.heartbeatIntervalSecs ?? LEGACY_HEARTBEAT_INTERVAL_SECS,
58
207
  FAILED_LOGIN_ATTEMPTS: 0,
59
208
  REJECTED_LOGIN_ATTEMPTS: 0,
60
209
  LAST_LOGIN_DATETIME: 0,
@@ -66,6 +215,54 @@ export function buildLoginAckBody(
66
215
  };
67
216
  }
68
217
 
218
+ // A failed login, GSF auth 8.15.5: one LoginError (Events.kt:91-98,133-140)
219
+ // with the "Problem logging in" text, for a wrong password and an unknown
220
+ // user alike (LoginProcessor.kt:160-161,330). Over HTTP it is a 200
221
+ // (http-login-failed.json).
222
+ export function buildLoginNackBody(config: MockServerConfig, transport: 'ws' | 'http'): Row {
223
+ if (isLegacyFidelity(config)) {
224
+ return {
225
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
226
+ ERROR: [
227
+ transport === 'ws'
228
+ ? {
229
+ CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
230
+ STATUS_CODE: '401',
231
+ TEXT: 'Incorrect username or password',
232
+ }
233
+ : {
234
+ CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
235
+ STATUS_CODE: '401 Unauthorized',
236
+ TEXT: 'Problem logging in',
237
+ },
238
+ ],
239
+ WARNING: [],
240
+ };
241
+ }
242
+ return {
243
+ ERROR: [
244
+ {
245
+ '@type': 'LoginError',
246
+ CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
247
+ TEXT: 'Problem logging in',
248
+ STATUS_CODE: '401 Unauthorized',
249
+ DETAILS: null,
250
+ },
251
+ ],
252
+ WARNING: [],
253
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
254
+ REFRESH_AUTH_TOKEN: null,
255
+ REFRESH_TOKEN_EXPIRATION_MINS: null,
256
+ };
257
+ }
258
+
259
+ // LOGOUT_ACK, GSF auth 8.15.5 (Events.kt:121-123): OIDC_LOGOUT_URL is null
260
+ // without an OIDC provider.
261
+ export function buildLogoutAckBody(config: MockServerConfig): Row {
262
+ if (isLegacyFidelity(config)) return { MESSAGE_TYPE: MESSAGE_TYPE.LOGOUT_ACK };
263
+ return { OIDC_LOGOUT_URL: null, MESSAGE_TYPE: MESSAGE_TYPE.LOGOUT_ACK };
264
+ }
265
+
69
266
  // Trusted lookup by username alone — for paths where identity is already
70
267
  // established (a token this server issued, an HTTP session cookie,
71
268
  // httpAutoLogin). NEVER use this for a credentials login.
@@ -92,7 +289,7 @@ export function handleLogin(
92
289
  message: GenesisMessage,
93
290
  connection: Connection,
94
291
  config: MockServerConfig,
95
- tokens: TokenRegistry,
292
+ auth: AuthState,
96
293
  ): void {
97
294
  const details = message.DETAILS ?? {};
98
295
  // Two login shapes share EVENT_LOGIN_AUTH: credentials ({USER_NAME,
@@ -101,9 +298,9 @@ export function handleLogin(
101
298
  // at the top level), no username at all.
102
299
  const tokenUsername =
103
300
  details.USER_NAME === undefined
104
- ? (tokens.get(details.REFRESH_AUTH_TOKEN) ??
105
- tokens.get(details.SESSION_AUTH_TOKEN) ??
106
- tokens.get(message.SESSION_AUTH_TOKEN))
301
+ ? (auth.tokens.get(details.REFRESH_AUTH_TOKEN) ??
302
+ auth.tokens.get(details.SESSION_AUTH_TOKEN) ??
303
+ auth.tokens.get(message.SESSION_AUTH_TOKEN))
107
304
  : undefined;
108
305
  const user =
109
306
  details.USER_NAME !== undefined
@@ -111,48 +308,39 @@ export function handleLogin(
111
308
  : findUser(config, tokenUsername);
112
309
 
113
310
  if (!user) {
114
- connection.reply(message, {
115
- MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
116
- ERROR: [
117
- {
118
- CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
119
- STATUS_CODE: '401',
120
- TEXT: 'Incorrect username or password',
121
- },
122
- ],
123
- WARNING: [],
124
- });
311
+ connection.reply(message, buildLoginNackBody(config, 'ws'));
125
312
  return;
126
313
  }
127
314
 
128
- const ack = buildLoginAckBody(user, config);
129
- registerAckTokens(ack, user.username, tokens);
315
+ const session = openSession(auth, user);
130
316
  connection.authenticated = true;
131
317
  connection.userName = user.username;
132
318
  connection.profile = user.profile ?? [];
133
319
  connection.permission = user.permission ?? [];
134
- connection.sessionAuthToken = ack.SESSION_AUTH_TOKEN;
135
- connection.refreshAuthToken = ack.REFRESH_AUTH_TOKEN;
136
- connection.sessionId = ack.SESSION_ID;
320
+ connection.sessionAuthToken = session.sessionAuthToken;
321
+ connection.refreshAuthToken = session.refreshAuthToken;
322
+ connection.sessionId = session.sessionId;
137
323
 
138
- connection.reply(message, ack);
324
+ connection.reply(message, buildLoginAckBody(user, session, config, auth));
139
325
  }
140
326
 
141
327
  export function handleLogout(
142
328
  message: GenesisMessage,
143
329
  connection: Connection,
144
- tokens: TokenRegistry,
330
+ config: MockServerConfig,
331
+ auth: AuthState,
145
332
  ): void {
146
- // Revoke this connection's tokens, not just its authenticated flag: every
147
- // message re-adopts a stamped SESSION_AUTH_TOKEN (see router.ts), so a
148
- // token left in the registry silently logs the connection straight back in
149
- // on its very next request.
333
+ const session =
334
+ connection.sessionAuthToken === undefined
335
+ ? undefined
336
+ : auth.sessions.get(connection.sessionAuthToken);
337
+ if (session) closeSession(auth, session);
150
338
  for (const token of [connection.sessionAuthToken, connection.refreshAuthToken]) {
151
- if (token !== undefined) tokens.delete(token);
339
+ if (token !== undefined) auth.tokens.delete(token);
152
340
  }
153
341
  connection.authenticated = false;
154
342
  connection.sessionAuthToken = undefined;
155
343
  connection.refreshAuthToken = undefined;
156
344
  connection.subscriptions.clear();
157
- connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.LOGOUT_ACK });
345
+ connection.reply(message, buildLogoutAckBody(config));
158
346
  }
@@ -1,11 +1,20 @@
1
1
  import type { Connection } from '../protocol/connection.ts';
2
+ import { isLegacyFidelity } from '../protocol/fidelity.ts';
2
3
  import { MESSAGE_TYPE } from '../protocol/messageTypes.ts';
3
4
  import type { GenesisMessage, MockServerConfig } from '../types.ts';
5
+ import type { AuthState } from './auth.ts';
4
6
 
7
+ // HEARTBEAT_PONG, as genesis-router answers it
8
+ // (RouterMessageDelegator.handleHeartbeat, RouterMessageDelegator.kt:158-195
9
+ // @v8.15.29): IS_AUTHENTICATED, plus with VERBOSE:true the connection's
10
+ // USER_NAME, CREATED_AT, LAST_RECEIVED, LAST_SENT and RESOURCES
11
+ // (heartbeat.json). The router writes it straight to the socket, so it
12
+ // doesn't count as LAST_SENT.
5
13
  export function handleHeartbeat(
6
14
  message: GenesisMessage,
7
15
  connection: Connection,
8
16
  config: MockServerConfig,
17
+ auth: AuthState,
9
18
  ): void {
10
19
  // With the auth gate off (the default), this server accepts every data
11
20
  // message — so the pong must report IS_AUTHENTICATED: true even though the
@@ -16,8 +25,33 @@ export function handleHeartbeat(
16
25
  // down, defeating httpAutoLogin entirely. Only when a project opts into
17
26
  // auth.requireAuth does the flag reflect real connection auth state.
18
27
  const requireAuth = config.auth?.requireAuth ?? false;
19
- connection.reply(message, {
20
- MESSAGE_TYPE: MESSAGE_TYPE.HEARTBEAT_PONG,
21
- IS_AUTHENTICATED: connection.authenticated || !requireAuth,
22
- });
28
+ const IS_AUTHENTICATED = connection.authenticated || !requireAuth;
29
+ if (isLegacyFidelity(config) || message.VERBOSE !== true) {
30
+ connection.reply(
31
+ message,
32
+ { MESSAGE_TYPE: MESSAGE_TYPE.HEARTBEAT_PONG, IS_AUTHENTICATED },
33
+ false,
34
+ );
35
+ return;
36
+ }
37
+ // A ping carrying a token names the session's user ('' for a dead one);
38
+ // otherwise the connection's own login.
39
+ const token = message.SESSION_AUTH_TOKEN;
40
+ const USER_NAME =
41
+ typeof token === 'string'
42
+ ? (auth.sessions.get(token)?.username ?? '')
43
+ : (connection.userName ?? null);
44
+ connection.reply(
45
+ message,
46
+ {
47
+ IS_AUTHENTICATED,
48
+ USER_NAME,
49
+ CREATED_AT: connection.createdAt,
50
+ LAST_RECEIVED: connection.lastReceived,
51
+ LAST_SENT: connection.lastSent,
52
+ RESOURCES: connection.dataserverResources(),
53
+ MESSAGE_TYPE: MESSAGE_TYPE.HEARTBEAT_PONG,
54
+ },
55
+ false,
56
+ );
23
57
  }