@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,5 +1,11 @@
1
1
  import type { Store } from '../db/store.ts';
2
- import { handleLogin, handleLogout, type TokenRegistry } from '../handlers/auth.ts';
2
+ import {
3
+ createAuthState,
4
+ handleLogin,
5
+ handleLogout,
6
+ type AuthState,
7
+ type TokenRegistry,
8
+ } from '../handlers/auth.ts';
3
9
  import { handleCommitEvent, type CommitEventCtx } from '../handlers/commitEvent.ts';
4
10
  import { handleDataLogon, handleDataLogoff, handleMoreRows } from '../handlers/dataLogon.ts';
5
11
  import { handleHeartbeat } from '../handlers/heartbeat.ts';
@@ -11,6 +17,7 @@ import type { GenesisMessage, MockServerConfig } from '../types.ts';
11
17
  import type { Connection } from './connection.ts';
12
18
  import { isLegacyFidelity } from './fidelity.ts';
13
19
  import { MESSAGE_TYPE, ERROR_CODE, isCommitEvent, isRequestReply } from './messageTypes.ts';
20
+ import { websocketForbiddenNack } from './msgNack.ts';
14
21
 
15
22
  // Message types a connection may send before authenticating when the OPT-IN
16
23
  // auth gate (config.auth.requireAuth = true) is enabled. Everything else
@@ -84,17 +91,32 @@ function replyNotLoggedOn(message: GenesisMessage, connection: Connection): void
84
91
  }
85
92
 
86
93
  export function routeMessage(
87
- message: GenesisMessage,
94
+ inbound: GenesisMessage,
88
95
  connection: Connection,
89
96
  config: MockServerConfig,
90
97
  store: Store,
91
98
  ctx: CommitEventCtx,
92
- tokens: TokenRegistry = new Map(),
99
+ auth: AuthState = createAuthState(),
93
100
  ): void {
101
+ let message = inbound;
102
+ // A socket opened with a sessionAuthToken cookie (auth.cookieAuthentication)
103
+ // is authenticated by it, so the router refuses to log it in or out, and
104
+ // stamps the cookie's token on everything else, over whatever the client
105
+ // sent (CookieHandler.kt:165-176 @v8.15.29).
106
+ const cookieToken = connection.cookieSessionAuthToken;
107
+ if (cookieToken !== undefined) {
108
+ const type = message.MESSAGE_TYPE;
109
+ if (type === MESSAGE_TYPE.EVENT_LOGIN_AUTH || type === MESSAGE_TYPE.EVENT_LOGOUT) {
110
+ return connection.reply(message, websocketForbiddenNack(type), false);
111
+ }
112
+ message = { ...message, SESSION_AUTH_TOKEN: cookieToken };
113
+ }
114
+
94
115
  // Adopt token auth on every message (not just gated ones) so e.g. a
95
116
  // HEARTBEAT_PONG's IS_AUTHENTICATED reflects an HTTP-issued token straight
96
117
  // away; the gate itself only applies to data traffic.
97
- ensureAuthenticated(message, connection, tokens);
118
+ ensureAuthenticated(message, connection, auth.tokens);
119
+ if (message.MESSAGE_TYPE !== MESSAGE_TYPE.HEARTBEAT_PING) connection.noteReceived(message);
98
120
  const requireAuth = config.auth?.requireAuth ?? false;
99
121
  if (requireAuth && !isPreAuth(message.MESSAGE_TYPE, config) && !connection.authenticated) {
100
122
  return replyNotLoggedOn(message, connection);
@@ -102,13 +124,14 @@ export function routeMessage(
102
124
 
103
125
  switch (message.MESSAGE_TYPE) {
104
126
  case MESSAGE_TYPE.EVENT_LOGIN_AUTH:
105
- return handleLogin(message, connection, config, tokens);
127
+ return handleLogin(message, connection, config, auth);
106
128
  case MESSAGE_TYPE.EVENT_LOGOUT:
107
- return handleLogout(message, connection, tokens);
129
+ return handleLogout(message, connection, config, auth);
108
130
  case MESSAGE_TYPE.HEARTBEAT_PING:
109
- return handleHeartbeat(message, connection, config);
131
+ return handleHeartbeat(message, connection, config, auth);
110
132
  case MESSAGE_TYPE.DATA_LOGON:
111
- return handleDataLogon(message, connection, config, store);
133
+ handleDataLogon(message, connection, config, store);
134
+ return connection.noteLogon(message);
112
135
  case MESSAGE_TYPE.DATA_LOGOFF:
113
136
  return handleDataLogoff(message, connection, config);
114
137
  case MESSAGE_TYPE.MORE_ROWS:
package/src/server.ts CHANGED
@@ -10,9 +10,15 @@ import {
10
10
  type PlannedJoin,
11
11
  type ViewEntry,
12
12
  } from './db/views.ts';
13
+ import { createAuthState } from './handlers/auth.ts';
13
14
  import { crudEventHandler } from './handlers/crudEvents.ts';
14
15
  import { pendingKey, viewRow, waitForPage } from './handlers/dataLogon.ts';
15
- import { createHttpRequestListener } from './handlers/http.ts';
16
+ import {
17
+ cookieAuthentication,
18
+ createHttpRequestListener,
19
+ parseCookies,
20
+ SESSION_AUTH_TOKEN_COOKIE,
21
+ } from './handlers/http.ts';
16
22
  import { permittedQueryRow, requestingUser } from './handlers/resourceAuth.ts';
17
23
  import { Connection, type Subscription, type ViewRow } from './protocol/connection.ts';
18
24
  import { isLegacyFidelity, liveModifyMode } from './protocol/fidelity.ts';
@@ -119,6 +125,9 @@ export interface MockServer {
119
125
  ): void;
120
126
  }
121
127
 
128
+ // The status a cookie-authenticated router refuses an upgrade with.
129
+ const HTTP_UNAUTHORIZED = 401;
130
+
122
131
  export function createMockServer(config: MockServerConfig): MockServer {
123
132
  // Declared columns are held by type (db/values.ts), except under
124
133
  // fidelity: 'legacy', which keeps rows as given.
@@ -561,13 +570,14 @@ export function createMockServer(config: MockServerConfig): MockServer {
561
570
  }
562
571
  };
563
572
 
564
- const httpSessions = new Map<string, string>(); // sessionId -> username, for the HTTP login transport (see handlers/http.ts)
565
- // Every SESSION_AUTH_TOKEN/REFRESH_AUTH_TOKEN this server has issued (over
566
- // either transport) -> username. Lets a WS connection authenticate with a
567
- // token from an earlier HTTP login (foundation-comms sends the stored
568
- // SESSION_AUTH_TOKEN on every message, and its token-refresh path sends
569
- // EVENT_LOGIN_AUTH with only DETAILS.REFRESH_AUTH_TOKEN — no credentials).
570
- const issuedTokens = new Map<string, string>();
573
+ // fidelity: 'legacy' HTTP sessions, MOCK_SESSION_ID -> username (handlers/http.ts).
574
+ const legacyHttpSessions = new Map<string, string>();
575
+ // Sessions and tokens issued over either transport (handlers/auth.ts), so a
576
+ // WS connection can authenticate with a token from an earlier HTTP login
577
+ // (foundation-comms sends the stored SESSION_AUTH_TOKEN on every message, and
578
+ // its token refresh sends EVENT_LOGIN_AUTH with only
579
+ // DETAILS.REFRESH_AUTH_TOKEN, no credentials).
580
+ const auth = createAuthState();
571
581
 
572
582
  // Runtime override/extend API. Every handler reads off this same `config`
573
583
  // object at call time (both the WS path in routeMessage below and the HTTP
@@ -650,11 +660,24 @@ export function createMockServer(config: MockServerConfig): MockServer {
650
660
  // node:http + the `ws` package rather than a runtime-specific API (e.g.
651
661
  // Bun.serve) so this runs unmodified under both Node (>=22.6, via
652
662
  // `node --experimental-strip-types`) and Bun.
653
- httpServer = http.createServer(createHttpRequestListener(config, httpSessions, issuedTokens));
654
- wss = new WebSocketServer({ server: httpServer });
663
+ httpServer = http.createServer(createHttpRequestListener(config, legacyHttpSessions, auth));
664
+ // A cookie-authenticated router answers an upgrade without a live
665
+ // sessionAuthToken cookie with HTTP 401 (PreHttpHandlerProvider.kt:61-95
666
+ // @v8.15.29). Read per upgrade, like every config field.
667
+ const cookieToken = (req: http.IncomingMessage) =>
668
+ parseCookies(req.headers.cookie)[SESSION_AUTH_TOKEN_COOKIE];
669
+ wss = new WebSocketServer({
670
+ server: httpServer,
671
+ verifyClient: ({ req }, done) => {
672
+ if (!cookieAuthentication(config)) return done(true);
673
+ const token = cookieToken(req);
674
+ done(token !== undefined && auth.sessions.has(token), HTTP_UNAUTHORIZED);
675
+ },
676
+ });
655
677
 
656
- wss.on('connection', (ws: WebSocket) => {
678
+ wss.on('connection', (ws: WebSocket, req: http.IncomingMessage) => {
657
679
  const connection = new Connection(ws);
680
+ if (cookieAuthentication(config)) connection.cookieSessionAuthToken = cookieToken(req);
658
681
  connections.add(connection);
659
682
 
660
683
  ws.on('message', (data) => {
@@ -685,7 +708,7 @@ export function createMockServer(config: MockServerConfig): MockServer {
685
708
  config,
686
709
  store,
687
710
  { broadcast, broadcastTableChange },
688
- issuedTokens,
711
+ auth,
689
712
  );
690
713
  } catch (error) {
691
714
  console.error(`[mock-server] Error handling ${message.MESSAGE_TYPE}:`, error);
package/src/types.ts CHANGED
@@ -378,7 +378,34 @@ export interface AuthUser {
378
378
  password?: string;
379
379
  profile?: string[];
380
380
  permission?: string[];
381
+ // The user's USER record. Its FIRST_NAME and LAST_NAME are the login ack's
382
+ // USER_DETAILS (null when unset). Under fidelity: 'legacy' the whole record
383
+ // is sent as the ack's USER instead.
381
384
  user?: Row;
385
+ // The login ack's USER: what an auth-preferences `loginAck { }` block adds
386
+ // per user. GSF sends USER: null without one, and so does the mock when
387
+ // this is unset. Not used under fidelity: 'legacy'.
388
+ loginAck?: Row;
389
+ }
390
+
391
+ // GSF's router `cookieAuthentication { }` block (genesis-router
392
+ // CookieAuthenticationDefinition). An unset field takes the value from the
393
+ // block GSF ships in genesis-router.kts: httpOnly true, secure false,
394
+ // sameSite 'Lax', path '/'.
395
+ export interface CookieAuthenticationOptions {
396
+ httpOnly?: boolean;
397
+ secure?: boolean;
398
+ sameSite?: 'Strict' | 'Lax' | 'None';
399
+ path?: string;
400
+ domain?: string;
401
+ // true: no Max-Age, so the browser drops the cookies when it closes.
402
+ sessionCookies?: boolean;
403
+ }
404
+
405
+ // A login ack DETAILS.PRODUCT entry: an installed product and its version.
406
+ export interface ProductDetails {
407
+ NAME: string;
408
+ VERSION: string;
382
409
  }
383
410
 
384
411
  // Entry served from GET gwf/sso/list, matching foundation-auth's
@@ -400,9 +427,40 @@ export interface AuthConfig {
400
427
  // to keep the login screen rendering. Clicking it navigates to the real
401
428
  // SSO login URL template, which the mock does not implement.
402
429
  ssoIdentityProviders?: SsoIdentityProvider[];
430
+ // auth-preferences heartbeatIntervalSecs: the login ack's
431
+ // DETAILS.HEARTBEAT_INTERVAL_SECONDS. Unset: 0, as GSF sends without one
432
+ // (30 under fidelity: 'legacy', which sends it as HEARTBEAT_INTERVAL_SECS).
403
433
  heartbeatIntervalSecs?: number;
434
+ // auth-preferences sessionTimeoutMins (GSF default 30): the ack's
435
+ // DETAILS.SESSION_TIMEOUT_MINS and the sessionAuthToken cookie's Max-Age.
436
+ sessionTimeoutMins?: number;
437
+ // auth-preferences refreshTokenExpirationMins (GSF default 7200): the ack's
438
+ // DETAILS.REFRESH_TOKEN_EXPIRATION_MINS and the refreshAuthToken and
439
+ // sessionId cookies' Max-Age.
440
+ refreshTokenExpirationMins?: number;
441
+ // The login ack's DETAILS.PRODUCT: the products the server runs. Unset:
442
+ // auth 8.15.5 and genesis 8.15.29, the versions this mock follows.
443
+ products?: ProductDetails[];
444
+ // The router's cookie authentication. ON by default, as GSF's
445
+ // genesis-router.kts ships it (`cookieAuthentication { enabled = true }`);
446
+ // `false` opts out, and fidelity: 'legacy' defaults it off. When on:
447
+ // - an HTTP login sets the sessionAuthToken, refreshAuthToken, sessionId
448
+ // and mfaCode cookies, a failed one clears refreshAuthToken, and logout
449
+ // clears all four;
450
+ // - the HTTP endpoints read the session from the sessionAuthToken cookie;
451
+ // - a WebSocket upgrade without a live sessionAuthToken cookie gets HTTP
452
+ // 401, and every message on the socket is authenticated by that cookie;
453
+ // - EVENT_LOGIN_AUTH and EVENT_LOGOUT over the socket get MSG_NACK 403.
454
+ // Off: no cookies at all, as on a GSF router without the block, so an HTTP
455
+ // request names its session in a SESSION_AUTH_TOKEN header (under
456
+ // fidelity: 'legacy', the mock's MOCK_SESSION_ID cookie), and the socket
457
+ // logs in with EVENT_LOGIN_AUTH. `true` (or unset) uses the shipped block's
458
+ // cookie attributes; an object overrides them.
459
+ cookieAuthentication?: boolean | CookieAuthenticationOptions;
404
460
  // A username to always ack gwf/event-login-details as (skips the login
405
- // screen entirely), or `true` to use the first configured user.
461
+ // screen entirely), or `true` to use the first configured user. A request
462
+ // without a live session gets a new one, as if that user had logged in
463
+ // (with cookieAuthentication on, the login cookies are set too).
406
464
  httpAutoLogin?: string | true;
407
465
  // OPT-IN (default false): when true, WS data traffic (DATA_LOGON, REQ_*,
408
466
  // META/JSON_SCHEMA, commit events) is rejected with a NOT_LOGGED_ON error
@@ -492,8 +550,9 @@ export type OnMessageHook = (
492
550
  // How closely the wire envelopes follow the real server. 'gsf' (the default)
493
551
  // matches GSF 8.15.x: LOGON_ACK before the snapshot, dataserver paging
494
552
  // (MAX_ROWS / MAX_VIEW / MORE_ROWS), LOGOFF_ACK, FEATURE_ACK /
495
- // JSON_SCHEMA_FEATURE_ACK, and the router's MSG_NACK for unknown resources and
496
- // missing/duplicate subscriptions. 'legacy' restores the envelopes this engine
553
+ // JSON_SCHEMA_FEATURE_ACK, the router's MSG_NACK for unknown resources and
554
+ // missing/duplicate subscriptions, and auth 8.15.5's login ack, login NACK
555
+ // (HTTP 200) and HEARTBEAT_PONG VERBOSE fields. 'legacy' restores the envelopes this engine
497
556
  // sent up to 15.47 (every row in one snapshot, no LOGON_ACK/LOGOFF_ACK, typed
498
557
  // UNKNOWN_RESOURCE replies that RESOLVE the client's pending promise where
499
558
  // MSG_NACK rejects it) — an escape hatch for consumers built against those,