@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.
@@ -1,17 +1,37 @@
1
1
  import crypto from 'node:crypto';
2
2
  import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import { isLegacyFidelity } from '../protocol/fidelity.ts';
3
4
  import { MESSAGE_TYPE } from '../protocol/messageTypes.ts';
4
- import type { MockServerConfig } from '../types.ts';
5
+ import { notLoggedInNack } from '../protocol/msgNack.ts';
6
+ import type { AuthUser, CookieAuthenticationOptions, MockServerConfig, Row } from '../types.ts';
5
7
  import {
6
8
  buildLoginAckBody,
9
+ buildLoginNackBody,
10
+ buildLogoutAckBody,
7
11
  capRegistry,
12
+ closeSession,
13
+ createAuthState,
8
14
  findUser,
9
15
  findUserByCredentials,
10
- registerAckTokens,
11
- type TokenRegistry,
16
+ openSession,
17
+ refreshTokenExpirationMins,
18
+ sessionByRefreshToken,
19
+ sessionTimeoutMins,
20
+ type AuthSession,
21
+ type AuthState,
12
22
  } from './auth.ts';
13
23
 
14
- const SESSION_COOKIE = 'MOCK_SESSION_ID';
24
+ // fidelity: 'legacy' without cookieAuthentication: the mock's own session
25
+ // cookie, sessionId -> username.
26
+ const LEGACY_SESSION_COOKIE = 'MOCK_SESSION_ID';
27
+ // genesis-router CookieHandler.kt:195-202 @v8.15.29.
28
+ export const SESSION_AUTH_TOKEN_COOKIE = 'sessionAuthToken';
29
+ const REFRESH_AUTH_TOKEN_COOKIE = 'refreshAuthToken';
30
+ const SESSION_ID_COOKIE = 'sessionId';
31
+ const MFA_CODE_COOKIE = 'mfaCode';
32
+
33
+ const SECONDS_PER_MINUTE = 60;
34
+ const MILLIS_PER_SECOND = 1000;
15
35
 
16
36
  const HTTP_STATUS = {
17
37
  OK: 200,
@@ -20,16 +40,35 @@ const HTTP_STATUS = {
20
40
  INTERNAL_SERVER_ERROR: 500,
21
41
  };
22
42
 
43
+ // The `cookieAuthentication { }` block GSF ships in genesis-router.kts.
44
+ const SHIPPED_COOKIE_OPTIONS: Required<Omit<CookieAuthenticationOptions, 'domain'>> = {
45
+ httpOnly: true,
46
+ secure: false,
47
+ sameSite: 'Lax',
48
+ path: '/',
49
+ sessionCookies: false,
50
+ };
51
+
52
+ export function cookieAuthentication(
53
+ config: MockServerConfig,
54
+ ): CookieAuthenticationOptions | undefined {
55
+ // On unless the config opts out, as GSF ships it; off under fidelity: 'legacy'.
56
+ const option = config.auth?.cookieAuthentication ?? !isLegacyFidelity(config);
57
+ if (!option) return undefined;
58
+ return option === true ? SHIPPED_COOKIE_OPTIONS : { ...SHIPPED_COOKIE_OPTIONS, ...option };
59
+ }
60
+
23
61
  // foundation-auth's login UI (client-app-login) doesn't use the WebSocket
24
62
  // EVENT_LOGIN_AUTH flow at all — it POSTs credentials over plain HTTP to
25
- // gwf/event-login-auth, and separately GETs gwf/event-login-details on every
26
- // app load (cookie-based silent login: foundation-comms/src/connect/
27
- // sessionRefresh.ts's isAuthenticated()). Both expect the exact same ACK body
28
- // shape as the WS login (EVENT_LOGIN_DETAILS_ACK literally extends
29
- // EVENT_LOGIN_AUTH_ACK), just reached over HTTP with a session cookie instead
30
- // of SOURCE_REF correlation. This is a *separate* transport from the WS
31
- // protocol in server.ts — a client-app can use either, or (as here) both.
32
- function parseCookies(header: string | undefined): Record<string, string> {
63
+ // gwf/event-login-auth, and separately POSTs gwf/event-login-details on every
64
+ // app load (silent login; foundation-comms/src/connect/sessionRefresh.ts's
65
+ // isAuthenticated() GETs it later). Both expect the same ACK body as the WS
66
+ // login (EVENT_LOGIN_DETAILS_ACK literally extends EVENT_LOGIN_AUTH_ACK), with
67
+ // the session named by a cookie (cookieAuthentication) or a SESSION_AUTH_TOKEN
68
+ // header instead of SOURCE_REF correlation. This is a *separate* transport
69
+ // from the WS protocol in server.ts — a client-app can use either, or (as
70
+ // here) both.
71
+ export function parseCookies(header: string | undefined): Record<string, string> {
33
72
  const cookies: Record<string, string> = {};
34
73
  for (const part of (header ?? '').split(';')) {
35
74
  const [key, ...rest] = part.trim().split('=');
@@ -38,11 +77,76 @@ function parseCookies(header: string | undefined): Record<string, string> {
38
77
  return cookies;
39
78
  }
40
79
 
41
- function setSessionCookie(res: ServerResponse, sessionId: string): void {
42
- res.setHeader('Set-Cookie', `${SESSION_COOKIE}=${sessionId}; Path=/; SameSite=Lax`);
80
+ // As Netty's ServerCookieEncoder.STRICT writes it (CookieHandler.kt:178-192
81
+ // @v8.15.29): Max-Age and Expires unless it is a session cookie, then Path,
82
+ // Domain, Secure, HTTPOnly, SameSite.
83
+ function encodeCookie(
84
+ options: CookieAuthenticationOptions,
85
+ name: string,
86
+ value: string,
87
+ maxAgeSecs: number | undefined,
88
+ ): string {
89
+ const parts = [`${name}=${value}`];
90
+ if (maxAgeSecs !== undefined) {
91
+ const expires = new Date(Date.now() + maxAgeSecs * MILLIS_PER_SECOND);
92
+ parts.push(`Max-Age=${maxAgeSecs}`, `Expires=${expires.toUTCString()}`);
93
+ }
94
+ if (options.path) parts.push(`Path=${options.path}`);
95
+ if (options.domain) parts.push(`Domain=${options.domain}`);
96
+ if (options.secure) parts.push('Secure');
97
+ if (options.httpOnly) parts.push('HTTPOnly');
98
+ if (options.sameSite) parts.push(`SameSite=${options.sameSite}`);
99
+ return parts.join('; ');
100
+ }
101
+
102
+ // The cookies GSF's router sets on an EVENT_LOGIN_AUTH_ACK
103
+ // (CookieHandler.kt:91-130): the session token lives as long as the session,
104
+ // the refresh token and session id as long as the refresh token, and the
105
+ // unused MFA code expires at once.
106
+ function loginCookies(
107
+ options: CookieAuthenticationOptions,
108
+ config: MockServerConfig,
109
+ session: AuthSession,
110
+ ): string[] {
111
+ const sessionMaxAge = options.sessionCookies
112
+ ? undefined
113
+ : sessionTimeoutMins(config) * SECONDS_PER_MINUTE;
114
+ const refreshMaxAge = options.sessionCookies
115
+ ? undefined
116
+ : refreshTokenExpirationMins(config) * SECONDS_PER_MINUTE;
117
+ return [
118
+ encodeCookie(options, SESSION_AUTH_TOKEN_COOKIE, session.sessionAuthToken, sessionMaxAge),
119
+ encodeCookie(options, REFRESH_AUTH_TOKEN_COOKIE, session.refreshAuthToken, refreshMaxAge),
120
+ encodeCookie(options, SESSION_ID_COOKIE, session.sessionId, refreshMaxAge),
121
+ encodeCookie(options, MFA_CODE_COOKIE, '', 0),
122
+ ];
43
123
  }
44
124
 
45
- function sendJson(res: ServerResponse, status: number, body: unknown): void {
125
+ // On EVENT_LOGIN_AUTH_NACK the router sets the NACK's REFRESH_AUTH_TOKEN
126
+ // (null) for its REFRESH_TOKEN_EXPIRATION_MINS (null): an empty cookie that
127
+ // expires at once (CookieHandler.kt:132-139); recorded in
128
+ // http-login-failed.json.
129
+ function loginNackCookies(options: CookieAuthenticationOptions): string[] {
130
+ return [encodeCookie(options, REFRESH_AUTH_TOKEN_COOKIE, '', 0)];
131
+ }
132
+
133
+ // LOGOUT_ACK expires all four (CookieHandler.kt:141-147).
134
+ function logoutCookies(options: CookieAuthenticationOptions): string[] {
135
+ return [
136
+ SESSION_AUTH_TOKEN_COOKIE,
137
+ REFRESH_AUTH_TOKEN_COOKIE,
138
+ SESSION_ID_COOKIE,
139
+ MFA_CODE_COOKIE,
140
+ ].map((name) => encodeCookie(options, name, '', 0));
141
+ }
142
+
143
+ function sendJson(
144
+ res: ServerResponse,
145
+ status: number,
146
+ body: unknown,
147
+ cookies: string[] = [],
148
+ ): void {
149
+ if (cookies.length > 0) res.setHeader('Set-Cookie', cookies);
46
150
  res.writeHead(status, { 'Content-Type': 'application/json' });
47
151
  res.end(JSON.stringify(body));
48
152
  }
@@ -65,36 +169,207 @@ async function readJsonBody(req: IncomingMessage): Promise<Record<string, any>>
65
169
  return raw ? JSON.parse(raw) : {};
66
170
  }
67
171
 
68
- // Drops every token this server minted for `username`. Logout has to do this,
69
- // not just forget the session: router.ts re-adopts any known SESSION_AUTH_TOKEN
70
- // on every message, so a token left in the registry logs a WS connection
71
- // straight back in on its next request.
72
- function revokeTokensFor(tokens: TokenRegistry, username: string): void {
73
- for (const [token, owner] of tokens) {
74
- if (owner === username) tokens.delete(token);
172
+ // A header the client may send as SESSION_AUTH_TOKEN or, as foundation-comms'
173
+ // createHTTPHeadersFromMessage does, SESSION-AUTH-TOKEN.
174
+ function headerValue(req: IncomingMessage, name: string): string | undefined {
175
+ const value =
176
+ req.headers[name.toLowerCase()] ?? req.headers[name.toLowerCase().replaceAll('_', '-')];
177
+ return typeof value === 'string' ? value : undefined;
178
+ }
179
+
180
+ function autoLoginUser(config: MockServerConfig): AuthUser | undefined {
181
+ const autoLogin = config.auth?.httpAutoLogin;
182
+ if (!autoLogin) return undefined;
183
+ return findUser(config, autoLogin === true ? config.auth?.users?.[0]?.username : autoLogin);
184
+ }
185
+
186
+ // Drops every token this server minted for `username` (fidelity: 'legacy',
187
+ // whose logout ends all of the user's sessions).
188
+ function revokeSessionsOf(auth: AuthState, username: string): void {
189
+ for (const session of auth.sessions.values()) {
190
+ if (session.username === username) closeSession(auth, session);
191
+ }
192
+ for (const [token, owner] of auth.tokens) {
193
+ if (owner === username) auth.tokens.delete(token);
75
194
  }
76
195
  }
77
196
 
78
- // Reuse the request's own session when its cookie already maps to this user —
79
- // otherwise every page load would mint (and leak) a fresh session entry on a
80
- // long-lived dev/CI server.
81
- function ensureSession(
82
- sessions: Map<string, string>,
197
+ // fidelity: 'legacy': reuse the request's MOCK_SESSION_ID when it already maps
198
+ // to this user — otherwise every page load would mint (and leak) a fresh
199
+ // session entry on a long-lived dev/CI server.
200
+ function ensureLegacySession(
201
+ legacySessions: Map<string, string>,
83
202
  cookieSessionId: string | undefined,
84
203
  username: string,
85
204
  ): string {
86
- if (cookieSessionId && sessions.get(cookieSessionId) === username) return cookieSessionId;
205
+ if (cookieSessionId && legacySessions.get(cookieSessionId) === username) return cookieSessionId;
87
206
  const sessionId = crypto.randomUUID();
88
- sessions.set(sessionId, username);
89
- capRegistry(sessions);
207
+ legacySessions.set(sessionId, username);
208
+ capRegistry(legacySessions);
90
209
  return sessionId;
91
210
  }
92
211
 
212
+ function legacySessionCookie(sessionId: string): string {
213
+ return `${LEGACY_SESSION_COOKIE}=${sessionId}; Path=/; SameSite=Lax`;
214
+ }
215
+
93
216
  export function createHttpRequestListener(
94
217
  config: MockServerConfig,
95
- sessions: Map<string, string>,
96
- tokens: TokenRegistry = new Map(),
218
+ legacySessions: Map<string, string>,
219
+ auth: AuthState = createAuthState(),
97
220
  ) {
221
+ // Every HTTP reply carries a SOURCE_REF: the request's, or AUTO_<uuid> as
222
+ // the router mints one (http-login.json). Not under fidelity: 'legacy'.
223
+ const withSourceRef = (body: Row, request: Row = {}): Row =>
224
+ isLegacyFidelity(config)
225
+ ? body
226
+ : { ...body, SOURCE_REF: request.SOURCE_REF ?? `AUTO_${crypto.randomUUID()}` };
227
+
228
+ // The session a request names: the sessionAuthToken cookie under
229
+ // cookieAuthentication, else (GSF) the SESSION_AUTH_TOKEN header. '' when
230
+ // the cookie is there but empty, as after a logout cleared it.
231
+ function requestToken(req: IncomingMessage, cookies: Record<string, string>): string | undefined {
232
+ if (cookieAuthentication(config)) return cookies[SESSION_AUTH_TOKEN_COOKIE];
233
+ return headerValue(req, 'SESSION_AUTH_TOKEN');
234
+ }
235
+
236
+ // The legacy-mode session cookie, or none.
237
+ function legacyCookies(cookies: Record<string, string>, username: string): string[] {
238
+ if (!isLegacyFidelity(config) || cookieAuthentication(config)) return [];
239
+ return [
240
+ legacySessionCookie(
241
+ ensureLegacySession(legacySessions, cookies[LEGACY_SESSION_COOKIE], username),
242
+ ),
243
+ ];
244
+ }
245
+
246
+ // A session opened by a login (or an httpAutoLogin): the login cookies.
247
+ function sessionCookies(cookies: Record<string, string>, session: AuthSession): string[] {
248
+ const options = cookieAuthentication(config);
249
+ return options
250
+ ? loginCookies(options, config, session)
251
+ : legacyCookies(cookies, session.username);
252
+ }
253
+
254
+ function handleLoginDetails(req: IncomingMessage, res: ServerResponse, request: Row): void {
255
+ const cookies = parseCookies(req.headers.cookie);
256
+ const legacyWithoutCookies = isLegacyFidelity(config) && !cookieAuthentication(config);
257
+ const autoLogin = autoLoginUser(config);
258
+
259
+ // fidelity: 'legacy' without cookieAuthentication: as up to 15.47, a new
260
+ // session per call, found by the MOCK_SESSION_ID cookie.
261
+ if (legacyWithoutCookies) {
262
+ const user =
263
+ autoLogin ?? findUser(config, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
264
+ if (!user) {
265
+ sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
266
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
267
+ ERROR: [
268
+ { CODE: 'NOT_LOGGED_ON', STATUS_CODE: '401 Unauthorized', TEXT: 'No active session' },
269
+ ],
270
+ });
271
+ return;
272
+ }
273
+ const session = openSession(auth, user);
274
+ const body = buildLoginAckBody(user, session, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
275
+ sendJson(res, HTTP_STATUS.OK, body, legacyCookies(cookies, user.username));
276
+ return;
277
+ }
278
+
279
+ const token = requestToken(req, cookies);
280
+ const session = token === undefined ? undefined : auth.sessions.get(token);
281
+ const sessionUser = session && findUser(config, session.username);
282
+ if (session && sessionUser) {
283
+ const body = buildLoginAckBody(sessionUser, session, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
284
+ sendJson(res, HTTP_STATUS.OK, withSourceRef(body, request));
285
+ return;
286
+ }
287
+ // httpAutoLogin: a request without a live session logs the user in.
288
+ if (autoLogin) {
289
+ const opened = openSession(auth, autoLogin);
290
+ const body = buildLoginAckBody(autoLogin, opened, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
291
+ sendJson(res, HTTP_STATUS.OK, withSourceRef(body, request), sessionCookies(cookies, opened));
292
+ return;
293
+ }
294
+ sendJson(
295
+ res,
296
+ HTTP_STATUS.UNAUTHORIZED,
297
+ withSourceRef(notLoggedInNack(token !== undefined), request),
298
+ );
299
+ }
300
+
301
+ async function handleLoginAuth(req: IncomingMessage, res: ServerResponse): Promise<void> {
302
+ const body = await readJsonBody(req);
303
+ const details = body.DETAILS ?? {};
304
+ const cookies = parseCookies(req.headers.cookie);
305
+ const cookieOptions = cookieAuthentication(config);
306
+
307
+ // No USER_NAME: a token refresh (foundation-comms' sessionRefresh
308
+ // performRefresh). Its refresh token is the refreshAuthToken cookie under
309
+ // cookieAuthentication (CookieHandler.kt:62-67), else DETAILS'; under
310
+ // fidelity: 'legacy' without cookies, the MOCK_SESSION_ID session.
311
+ let user: AuthUser | undefined;
312
+ if (details.USER_NAME !== undefined) {
313
+ user = findUserByCredentials(config, details.USER_NAME, details.PASSWORD);
314
+ } else if (isLegacyFidelity(config) && !cookieOptions) {
315
+ user = findUser(config, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
316
+ } else {
317
+ const refreshToken = cookieOptions
318
+ ? cookies[REFRESH_AUTH_TOKEN_COOKIE]
319
+ : (details.REFRESH_AUTH_TOKEN ?? headerValue(req, 'REFRESH_AUTH_TOKEN'));
320
+ user = findUser(config, sessionByRefreshToken(auth, refreshToken)?.username);
321
+ }
322
+
323
+ if (!user) {
324
+ // GSF answers a failed login with HTTP 200; fidelity: 'legacy' with 401.
325
+ const status = isLegacyFidelity(config) ? HTTP_STATUS.UNAUTHORIZED : HTTP_STATUS.OK;
326
+ const nackCookies = cookieOptions ? loginNackCookies(cookieOptions) : [];
327
+ sendJson(res, status, withSourceRef(buildLoginNackBody(config, 'http'), body), nackCookies);
328
+ return;
329
+ }
330
+
331
+ const session = openSession(auth, user);
332
+ const ack = buildLoginAckBody(user, session, config, auth);
333
+ sendJson(res, HTTP_STATUS.OK, withSourceRef(ack, body), sessionCookies(cookies, session));
334
+ }
335
+
336
+ async function handleLogout(req: IncomingMessage, res: ServerResponse): Promise<void> {
337
+ const body = await readJsonBody(req).catch(() => ({}) as Record<string, any>);
338
+ const cookies = parseCookies(req.headers.cookie);
339
+ const cookieOptions = cookieAuthentication(config);
340
+
341
+ if (isLegacyFidelity(config) && !cookieOptions) {
342
+ const sessionId = cookies[LEGACY_SESSION_COOKIE];
343
+ const username = legacySessions.get(sessionId);
344
+ legacySessions.delete(sessionId);
345
+ if (username !== undefined) revokeSessionsOf(auth, username);
346
+ sendJson(res, HTTP_STATUS.OK, buildLogoutAckBody(config));
347
+ return;
348
+ }
349
+
350
+ // auth's LOGOUT ends the session SESSION_ID names (the sessionId cookie
351
+ // under cookieAuthentication, CookieHandler.kt:76-81), else the token's.
352
+ const sessionId = cookieOptions
353
+ ? cookies[SESSION_ID_COOKIE]
354
+ : (body.SESSION_ID ?? headerValue(req, 'SESSION_ID'));
355
+ const token = cookieOptions ? cookies[SESSION_AUTH_TOKEN_COOKIE] : requestToken(req, cookies);
356
+ for (const session of auth.sessions.values()) {
357
+ if (session.sessionId === sessionId || session.sessionAuthToken === token) {
358
+ closeSession(auth, session);
359
+ }
360
+ }
361
+ if (isLegacyFidelity(config)) {
362
+ sendJson(res, HTTP_STATUS.OK, buildLogoutAckBody(config), logoutCookies(cookieOptions!));
363
+ return;
364
+ }
365
+ sendJson(
366
+ res,
367
+ HTTP_STATUS.OK,
368
+ withSourceRef(buildLogoutAckBody(config), body),
369
+ cookieOptions ? logoutCookies(cookieOptions) : [],
370
+ );
371
+ }
372
+
98
373
  return async function requestListener(req: IncomingMessage, res: ServerResponse): Promise<void> {
99
374
  const pathname = (req.url ?? '').split('?')[0];
100
375
 
@@ -126,89 +401,28 @@ export function createHttpRequestListener(
126
401
  return;
127
402
  }
128
403
 
129
- // Cookie-based silent login on app load — auto-authenticates as the
130
- // configured user when config.auth.httpAutoLogin is set, so the login
131
- // screen never appears (matches how a real session cookie would behave
132
- // once already logged in, but skips the manual login step entirely).
133
- // Two different call sites hit this path with different methods:
134
- // foundation-auth's fetch machine always POSTs (createFetchMachineEvent
135
- // hardcodes method: 'POST') on initial silent-login; foundation-comms'
136
- // sessionRefresh.ts's isAuthenticated() does a plain GET later, when
137
- // checking whether an expired session can be silently renewed.
404
+ // Silent login on app load. Two call sites hit this path with
405
+ // different methods: foundation-auth's fetch machine always POSTs
406
+ // (createFetchMachineEvent hardcodes method: 'POST') on initial
407
+ // silent-login; foundation-comms' sessionRefresh.ts's isAuthenticated()
408
+ // does a plain GET later, when checking whether an expired session can
409
+ // be silently renewed.
138
410
  if (
139
411
  (req.method === 'GET' || req.method === 'POST') &&
140
412
  pathname.endsWith('event-login-details')
141
413
  ) {
142
- const autoLoginUsername = config.auth?.httpAutoLogin;
143
- const cookies = parseCookies(req.headers.cookie);
144
- const user = autoLoginUsername
145
- ? findUser(
146
- config,
147
- autoLoginUsername === true ? config.auth?.users?.[0]?.username : autoLoginUsername,
148
- )
149
- : findUser(config, sessions.get(cookies[SESSION_COOKIE]));
150
-
151
- if (!user) {
152
- sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
153
- MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
154
- ERROR: [
155
- { CODE: 'NOT_LOGGED_ON', STATUS_CODE: '401 Unauthorized', TEXT: 'No active session' },
156
- ],
157
- });
158
- return;
159
- }
160
-
161
- const sessionId = ensureSession(sessions, cookies[SESSION_COOKIE], user.username);
162
- setSessionCookie(res, sessionId);
163
- const ack = buildLoginAckBody(user, config, 'EVENT_LOGIN_DETAILS_ACK');
164
- registerAckTokens(ack, user.username, tokens);
165
- sendJson(res, HTTP_STATUS.OK, ack);
414
+ const request = req.method === 'POST' ? await readJsonBody(req) : {};
415
+ handleLoginDetails(req, res, request);
166
416
  return;
167
417
  }
168
418
 
169
419
  if (req.method === 'POST' && pathname.endsWith('event-login-auth')) {
170
- const body = await readJsonBody(req);
171
- const details = body.DETAILS ?? {};
172
- const cookies = parseCookies(req.headers.cookie);
173
-
174
- // Empty DETAILS means a session-refresh ping (foundation-comms'
175
- // sessionRefresh.performRefresh), not a fresh credentials login —
176
- // honor it only if the request already carries a known session.
177
- const user =
178
- details.USER_NAME !== undefined
179
- ? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
180
- : findUser(config, sessions.get(cookies[SESSION_COOKIE]));
181
-
182
- if (!user) {
183
- sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
184
- MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
185
- ERROR: [
186
- {
187
- CODE: 'INCORRECT_CREDENTIALS',
188
- STATUS_CODE: '401 Unauthorized',
189
- TEXT: 'Problem logging in',
190
- },
191
- ],
192
- WARNING: [],
193
- });
194
- return;
195
- }
196
-
197
- const sessionId = ensureSession(sessions, cookies[SESSION_COOKIE], user.username);
198
- setSessionCookie(res, sessionId);
199
- const ack = buildLoginAckBody(user, config);
200
- registerAckTokens(ack, user.username, tokens);
201
- sendJson(res, HTTP_STATUS.OK, ack);
420
+ await handleLoginAuth(req, res);
202
421
  return;
203
422
  }
204
423
 
205
424
  if (req.method === 'POST' && pathname.endsWith('event-logout')) {
206
- const cookies = parseCookies(req.headers.cookie);
207
- const sessionId = cookies[SESSION_COOKIE];
208
- const username = sessions.get(sessionId);
209
- sessions.delete(sessionId);
210
- if (username !== undefined) revokeTokensFor(tokens, username);
211
- sendJson(res, HTTP_STATUS.OK, { MESSAGE_TYPE: 'LOGOUT_ACK' });
425
+ await handleLogout(req, res);
212
426
  return;
213
427
  }
214
428
 
package/src/index.ts CHANGED
@@ -24,6 +24,7 @@ export type {
24
24
  AuthUser,
25
25
  BroadcastFn,
26
26
  BroadcastTableChangeFn,
27
+ CookieAuthenticationOptions,
27
28
  CrudEventVerb,
28
29
  EventHandler,
29
30
  EventHandlerCtx,
@@ -46,6 +47,7 @@ export type {
46
47
  MockServerConfig,
47
48
  OnMessageCtx,
48
49
  OnMessageHook,
50
+ ProductDetails,
49
51
  QueryDef,
50
52
  RequestingUser,
51
53
  RequestReplyDef,
@@ -62,6 +62,15 @@ export interface Subscription {
62
62
  encode?: (row: Row) => Row;
63
63
  }
64
64
 
65
+ // What a verbose HEARTBEAT_PONG reports per subscription (genesis-router
66
+ // QuerySubscription.kt / DataserverResource.kt @v8.15.29), all epoch millis.
67
+ interface SubscriptionStats {
68
+ createdAt: number;
69
+ lastReceived: number;
70
+ lastSent: number;
71
+ dataLogon: Row;
72
+ }
73
+
65
74
  // Wraps one WebSocket client connection: auth state and its live DATA_LOGON
66
75
  // subscriptions (keyed by SOURCE_REF, since that's the client's sole correlation
67
76
  // key — see README pitfall #1).
@@ -76,6 +85,17 @@ export class Connection {
76
85
  profile: string[] = [];
77
86
  permission: string[] = [];
78
87
  readonly subscriptions = new Map<string, Subscription>();
88
+ // The sessionAuthToken cookie the socket was opened with, under
89
+ // auth.cookieAuthentication; it authenticates every message (router.ts).
90
+ cookieSessionAuthToken: string | undefined;
91
+ // A verbose HEARTBEAT_PONG's CREATED_AT, LAST_RECEIVED and LAST_SENT, as
92
+ // genesis-router's ClientHandler keeps them (ClientHandler.kt:66-68,
93
+ // 100-113 @v8.15.29): 0 until a message other than a heartbeat goes either
94
+ // way, since pings and pongs bypass the client handler.
95
+ readonly createdAt = Date.now();
96
+ lastReceived = 0;
97
+ lastSent = 0;
98
+ private readonly subscriptionStats = new WeakMap<Subscription, SubscriptionStats>();
79
99
 
80
100
  constructor(ws: SocketLike) {
81
101
  this.ws = ws;
@@ -83,13 +103,67 @@ export class Connection {
83
103
 
84
104
  // Every response must echo the request's SOURCE_REF verbatim, or the client's
85
105
  // pending promise for that call never resolves (silent hang, no error).
86
- send(payload: Row): void {
106
+ // `track: false` for what the real router writes without its client
107
+ // handler (pongs, the cookie router's refusals): it leaves LAST_SENT alone.
108
+ send(payload: Row, track = true): void {
87
109
  if (this.ws.readyState !== WS_OPEN) return;
88
110
  this.ws.send(JSON.stringify(payload));
111
+ if (!track) return;
112
+ const now = Date.now();
113
+ this.lastSent = now;
114
+ const subscription =
115
+ typeof payload.SOURCE_REF === 'string'
116
+ ? this.subscriptions.get(payload.SOURCE_REF)
117
+ : undefined;
118
+ const stats = subscription && this.subscriptionStats.get(subscription);
119
+ if (stats) stats.lastSent = now;
120
+ }
121
+
122
+ reply(requestMessage: GenesisMessage, payload: Row, track = true): void {
123
+ this.send({ ...payload, SOURCE_REF: requestMessage.SOURCE_REF }, track);
124
+ }
125
+
126
+ // Called for every routed message but heartbeats.
127
+ noteReceived(message: GenesisMessage): void {
128
+ const now = Date.now();
129
+ this.lastReceived = now;
130
+ const subscription = this.subscriptions.get(message.SOURCE_REF ?? '');
131
+ const stats = subscription && this.subscriptionStats.get(subscription);
132
+ if (stats) stats.lastReceived = now;
133
+ }
134
+
135
+ // Called after a DATA_LOGON was handled: starts the stats of the
136
+ // subscription it opened, if it opened one.
137
+ noteLogon(message: GenesisMessage): void {
138
+ const subscription = this.subscriptions.get(message.SOURCE_REF ?? '');
139
+ if (!subscription || this.subscriptionStats.has(subscription)) return;
140
+ const now = Date.now();
141
+ this.subscriptionStats.set(subscription, {
142
+ createdAt: now,
143
+ lastReceived: now,
144
+ lastSent: now,
145
+ dataLogon: message.DETAILS ?? {},
146
+ });
89
147
  }
90
148
 
91
- reply(requestMessage: GenesisMessage, payload: Row): void {
92
- this.send({ ...payload, SOURCE_REF: requestMessage.SOURCE_REF });
149
+ // A verbose HEARTBEAT_PONG's RESOURCES: the live subscriptions by resource
150
+ // name (FullDuplexClientHandler.kt:60-66 @v8.15.29), each a serialized
151
+ // DataserverResource.
152
+ dataserverResources(): Record<string, Row[]> {
153
+ const resources: Record<string, Row[]> = {};
154
+ for (const [sourceRef, subscription] of this.subscriptions) {
155
+ const stats = this.subscriptionStats.get(subscription);
156
+ if (!stats) continue;
157
+ (resources[subscription.resourceName] ??= []).push({
158
+ NAME: subscription.resourceName,
159
+ CREATED_AT: stats.createdAt,
160
+ LAST_RECEIVED: stats.lastReceived,
161
+ LAST_SENT: stats.lastSent,
162
+ SOURCE_REF: sourceRef,
163
+ DATA_LOGON: stats.dataLogon,
164
+ });
165
+ }
166
+ return resources;
93
167
  }
94
168
 
95
169
  subscribe(sourceRef: string, subscription: Subscription): void {
@@ -60,3 +60,28 @@ export function subscriptionAlreadyExistsNack(): Row {
60
60
  'Subscription exists for source ref. If using HTTP, try HTTP GET instead of HTTP POST',
61
61
  );
62
62
  }
63
+
64
+ const HTTP_UNAUTHORIZED = 401;
65
+ const HTTP_FORBIDDEN = 403;
66
+
67
+ // A cookie-authenticated router refuses EVENT_LOGIN_AUTH and EVENT_LOGOUT on
68
+ // a socket, which the cookie already authenticates (genesis-router
69
+ // WebsocketHandler.kt:54-58 @v8.15.29). Recorded in ws-login.json and
70
+ // ws-logout.json.
71
+ export function websocketForbiddenNack(messageType: string): Row {
72
+ return routerNack(HTTP_FORBIDDEN, 'Forbidden', `Unable to call ${messageType} via websocket`);
73
+ }
74
+
75
+ // An HTTP request that needs a session but names none (AuthModel.kt:134-137
76
+ // @v8.15.29), or names one that is not live (genesis-commons ErrorMessage
77
+ // INVALID_AUTH_TOKEN_MSG). Sent with HTTP status 401; recorded in
78
+ // http-login-failed.json and http-login.json.
79
+ export function notLoggedInNack(tokenSupplied: boolean): Row {
80
+ return routerNack(
81
+ HTTP_UNAUTHORIZED,
82
+ 'Unauthorized',
83
+ tokenSupplied
84
+ ? 'User is not logged in and supplied auth token is invalid.'
85
+ : 'This request needs the user to be logged in, but the current authentication status is logged out',
86
+ );
87
+ }