@genesislcap/mock-server 15.65.1-alpha-358eaead70.0 → 15.67.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.
Files changed (51) hide show
  1. package/README.md +120 -4
  2. package/dist/handlers/auth.d.ts +24 -5
  3. package/dist/handlers/auth.js +196 -43
  4. package/dist/handlers/heartbeat.d.ts +2 -1
  5. package/dist/handlers/heartbeat.js +26 -3
  6. package/dist/handlers/http.d.ts +6 -3
  7. package/dist/handlers/http.js +266 -91
  8. package/dist/handlers/resources.d.ts +2 -1
  9. package/dist/handlers/resources.js +18 -2
  10. package/dist/index.d.ts +1 -1
  11. package/dist/presets/csv.d.ts +2 -0
  12. package/dist/presets/csv.js +52 -0
  13. package/dist/presets/index.d.ts +3 -0
  14. package/dist/presets/index.js +3 -0
  15. package/dist/presets/merge.d.ts +15 -0
  16. package/dist/presets/merge.js +76 -0
  17. package/dist/presets/platform/default-user.json +30 -0
  18. package/dist/presets/platform/profile-rights.json +242 -0
  19. package/dist/presets/platform/profiles.json +62 -0
  20. package/dist/presets/platform/resources.json +710 -0
  21. package/dist/presets/platform/rights.json +238 -0
  22. package/dist/presets/platform.d.ts +27 -0
  23. package/dist/presets/platform.js +410 -0
  24. package/dist/protocol/connection.d.ts +10 -2
  25. package/dist/protocol/connection.js +69 -3
  26. package/dist/protocol/msgNack.d.ts +2 -0
  27. package/dist/protocol/msgNack.js +18 -0
  28. package/dist/protocol/router.d.ts +2 -2
  29. package/dist/protocol/router.js +24 -7
  30. package/dist/server.js +30 -12
  31. package/dist/types.d.ts +18 -0
  32. package/package.json +8 -2
  33. package/src/handlers/auth.ts +232 -44
  34. package/src/handlers/heartbeat.ts +38 -4
  35. package/src/handlers/http.ts +317 -103
  36. package/src/handlers/resources.ts +19 -2
  37. package/src/index.ts +2 -0
  38. package/src/presets/csv.ts +50 -0
  39. package/src/presets/index.ts +8 -0
  40. package/src/presets/merge.ts +79 -0
  41. package/src/presets/platform/default-user.json +30 -0
  42. package/src/presets/platform/profile-rights.json +242 -0
  43. package/src/presets/platform/profiles.json +62 -0
  44. package/src/presets/platform/resources.json +710 -0
  45. package/src/presets/platform/rights.json +238 -0
  46. package/src/presets/platform.ts +503 -0
  47. package/src/protocol/connection.ts +77 -3
  48. package/src/protocol/msgNack.ts +25 -0
  49. package/src/protocol/router.ts +31 -8
  50. package/src/server.ts +35 -12
  51. package/src/types.ts +69 -3
@@ -32,9 +32,17 @@ export declare class Connection {
32
32
  profile: string[];
33
33
  permission: string[];
34
34
  readonly subscriptions: Map<string, Subscription>;
35
+ cookieSessionAuthToken: string | undefined;
36
+ readonly createdAt: number;
37
+ lastReceived: number;
38
+ lastSent: number;
39
+ private readonly subscriptionStats;
35
40
  constructor(ws: SocketLike);
36
- send(payload: Row): void;
37
- reply(requestMessage: GenesisMessage, payload: Row): void;
41
+ send(payload: Row, track?: boolean): void;
42
+ reply(requestMessage: GenesisMessage, payload: Row, track?: boolean): void;
43
+ noteReceived(message: GenesisMessage): void;
44
+ noteLogon(message: GenesisMessage): void;
45
+ dataserverResources(): Record<string, Row[]>;
38
46
  subscribe(sourceRef: string, subscription: Subscription): void;
39
47
  unsubscribe(sourceRef: string): void;
40
48
  }
@@ -14,18 +14,84 @@ export class Connection {
14
14
  profile = [];
15
15
  permission = [];
16
16
  subscriptions = new Map();
17
+ // The sessionAuthToken cookie the socket was opened with, under
18
+ // auth.cookieAuthentication; it authenticates every message (router.ts).
19
+ cookieSessionAuthToken;
20
+ // A verbose HEARTBEAT_PONG's CREATED_AT, LAST_RECEIVED and LAST_SENT, as
21
+ // genesis-router's ClientHandler keeps them (ClientHandler.kt:66-68,
22
+ // 100-113 @v8.15.29): 0 until a message other than a heartbeat goes either
23
+ // way, since pings and pongs bypass the client handler.
24
+ createdAt = Date.now();
25
+ lastReceived = 0;
26
+ lastSent = 0;
27
+ subscriptionStats = new WeakMap();
17
28
  constructor(ws) {
18
29
  this.ws = ws;
19
30
  }
20
31
  // Every response must echo the request's SOURCE_REF verbatim, or the client's
21
32
  // pending promise for that call never resolves (silent hang, no error).
22
- send(payload) {
33
+ // `track: false` for what the real router writes without its client
34
+ // handler (pongs, the cookie router's refusals): it leaves LAST_SENT alone.
35
+ send(payload, track = true) {
23
36
  if (this.ws.readyState !== WS_OPEN)
24
37
  return;
25
38
  this.ws.send(JSON.stringify(payload));
39
+ if (!track)
40
+ return;
41
+ const now = Date.now();
42
+ this.lastSent = now;
43
+ const subscription = typeof payload.SOURCE_REF === 'string'
44
+ ? this.subscriptions.get(payload.SOURCE_REF)
45
+ : undefined;
46
+ const stats = subscription && this.subscriptionStats.get(subscription);
47
+ if (stats)
48
+ stats.lastSent = now;
49
+ }
50
+ reply(requestMessage, payload, track = true) {
51
+ this.send({ ...payload, SOURCE_REF: requestMessage.SOURCE_REF }, track);
52
+ }
53
+ // Called for every routed message but heartbeats.
54
+ noteReceived(message) {
55
+ const now = Date.now();
56
+ this.lastReceived = now;
57
+ const subscription = this.subscriptions.get(message.SOURCE_REF ?? '');
58
+ const stats = subscription && this.subscriptionStats.get(subscription);
59
+ if (stats)
60
+ stats.lastReceived = now;
61
+ }
62
+ // Called after a DATA_LOGON was handled: starts the stats of the
63
+ // subscription it opened, if it opened one.
64
+ noteLogon(message) {
65
+ const subscription = this.subscriptions.get(message.SOURCE_REF ?? '');
66
+ if (!subscription || this.subscriptionStats.has(subscription))
67
+ return;
68
+ const now = Date.now();
69
+ this.subscriptionStats.set(subscription, {
70
+ createdAt: now,
71
+ lastReceived: now,
72
+ lastSent: now,
73
+ dataLogon: message.DETAILS ?? {},
74
+ });
26
75
  }
27
- reply(requestMessage, payload) {
28
- this.send({ ...payload, SOURCE_REF: requestMessage.SOURCE_REF });
76
+ // A verbose HEARTBEAT_PONG's RESOURCES: the live subscriptions by resource
77
+ // name (FullDuplexClientHandler.kt:60-66 @v8.15.29), each a serialized
78
+ // DataserverResource.
79
+ dataserverResources() {
80
+ const resources = {};
81
+ for (const [sourceRef, subscription] of this.subscriptions) {
82
+ const stats = this.subscriptionStats.get(subscription);
83
+ if (!stats)
84
+ continue;
85
+ (resources[subscription.resourceName] ??= []).push({
86
+ NAME: subscription.resourceName,
87
+ CREATED_AT: stats.createdAt,
88
+ LAST_RECEIVED: stats.lastReceived,
89
+ LAST_SENT: stats.lastSent,
90
+ SOURCE_REF: sourceRef,
91
+ DATA_LOGON: stats.dataLogon,
92
+ });
93
+ }
94
+ return resources;
29
95
  }
30
96
  subscribe(sourceRef, subscription) {
31
97
  this.subscriptions.set(sourceRef, subscription);
@@ -4,3 +4,5 @@ export declare function serviceMsgNack(errors: NackErrorEntry[], warnings?: Nack
4
4
  export declare function resourceNotMappedNack(resourceName: string | undefined): Row;
5
5
  export declare function nonExistentSubscriptionNack(): Row;
6
6
  export declare function subscriptionAlreadyExistsNack(): Row;
7
+ export declare function websocketForbiddenNack(messageType: string): Row;
8
+ export declare function notLoggedInNack(tokenSupplied: boolean): Row;
@@ -44,3 +44,21 @@ export function nonExistentSubscriptionNack() {
44
44
  export function subscriptionAlreadyExistsNack() {
45
45
  return routerNack(HTTP_CONFLICT, 'Conflict', 'Subscription exists for source ref. If using HTTP, try HTTP GET instead of HTTP POST');
46
46
  }
47
+ const HTTP_UNAUTHORIZED = 401;
48
+ const HTTP_FORBIDDEN = 403;
49
+ // A cookie-authenticated router refuses EVENT_LOGIN_AUTH and EVENT_LOGOUT on
50
+ // a socket, which the cookie already authenticates (genesis-router
51
+ // WebsocketHandler.kt:54-58 @v8.15.29). Recorded in ws-login.json and
52
+ // ws-logout.json.
53
+ export function websocketForbiddenNack(messageType) {
54
+ return routerNack(HTTP_FORBIDDEN, 'Forbidden', `Unable to call ${messageType} via websocket`);
55
+ }
56
+ // An HTTP request that needs a session but names none (AuthModel.kt:134-137
57
+ // @v8.15.29), or names one that is not live (genesis-commons ErrorMessage
58
+ // INVALID_AUTH_TOKEN_MSG). Sent with HTTP status 401; recorded in
59
+ // http-login-failed.json and http-login.json.
60
+ export function notLoggedInNack(tokenSupplied) {
61
+ return routerNack(HTTP_UNAUTHORIZED, 'Unauthorized', tokenSupplied
62
+ ? 'User is not logged in and supplied auth token is invalid.'
63
+ : 'This request needs the user to be logged in, but the current authentication status is logged out');
64
+ }
@@ -1,6 +1,6 @@
1
1
  import type { Store } from '../db/store.ts';
2
- import { type TokenRegistry } from '../handlers/auth.ts';
2
+ import { type AuthState } from '../handlers/auth.ts';
3
3
  import { type CommitEventCtx } from '../handlers/commitEvent.ts';
4
4
  import type { GenesisMessage, MockServerConfig } from '../types.ts';
5
5
  import type { Connection } from './connection.ts';
6
- export declare function routeMessage(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store, ctx: CommitEventCtx, tokens?: TokenRegistry): void;
6
+ export declare function routeMessage(inbound: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store, ctx: CommitEventCtx, auth?: AuthState): void;
@@ -1,4 +1,4 @@
1
- import { handleLogin, handleLogout } from "../handlers/auth.js";
1
+ import { createAuthState, handleLogin, handleLogout, } from "../handlers/auth.js";
2
2
  import { handleCommitEvent } from "../handlers/commitEvent.js";
3
3
  import { handleDataLogon, handleDataLogoff, handleMoreRows } from "../handlers/dataLogon.js";
4
4
  import { handleHeartbeat } from "../handlers/heartbeat.js";
@@ -8,6 +8,7 @@ import { handleRequestReply } from "../handlers/requestReply.js";
8
8
  import { handleResourcesRequest } from "../handlers/resources.js";
9
9
  import { isLegacyFidelity } from "./fidelity.js";
10
10
  import { MESSAGE_TYPE, ERROR_CODE, isCommitEvent, isRequestReply } from "./messageTypes.js";
11
+ import { websocketForbiddenNack } from "./msgNack.js";
11
12
  // Message types a connection may send before authenticating when the OPT-IN
12
13
  // auth gate (config.auth.requireAuth = true) is enabled. Everything else
13
14
  // (data subscriptions, request-replies, metadata, commit events) then
@@ -73,24 +74,40 @@ function replyNotLoggedOn(message, connection) {
73
74
  }
74
75
  connection.reply(message, { MESSAGE_TYPE: type, ERROR });
75
76
  }
76
- export function routeMessage(message, connection, config, store, ctx, tokens = new Map()) {
77
+ export function routeMessage(inbound, connection, config, store, ctx, auth = createAuthState()) {
78
+ let message = inbound;
79
+ // A socket opened with a sessionAuthToken cookie (auth.cookieAuthentication)
80
+ // is authenticated by it, so the router refuses to log it in or out, and
81
+ // stamps the cookie's token on everything else, over whatever the client
82
+ // sent (CookieHandler.kt:165-176 @v8.15.29).
83
+ const cookieToken = connection.cookieSessionAuthToken;
84
+ if (cookieToken !== undefined) {
85
+ const type = message.MESSAGE_TYPE;
86
+ if (type === MESSAGE_TYPE.EVENT_LOGIN_AUTH || type === MESSAGE_TYPE.EVENT_LOGOUT) {
87
+ return connection.reply(message, websocketForbiddenNack(type), false);
88
+ }
89
+ message = { ...message, SESSION_AUTH_TOKEN: cookieToken };
90
+ }
77
91
  // Adopt token auth on every message (not just gated ones) so e.g. a
78
92
  // HEARTBEAT_PONG's IS_AUTHENTICATED reflects an HTTP-issued token straight
79
93
  // away; the gate itself only applies to data traffic.
80
- ensureAuthenticated(message, connection, tokens);
94
+ ensureAuthenticated(message, connection, auth.tokens);
95
+ if (message.MESSAGE_TYPE !== MESSAGE_TYPE.HEARTBEAT_PING)
96
+ connection.noteReceived(message);
81
97
  const requireAuth = config.auth?.requireAuth ?? false;
82
98
  if (requireAuth && !isPreAuth(message.MESSAGE_TYPE, config) && !connection.authenticated) {
83
99
  return replyNotLoggedOn(message, connection);
84
100
  }
85
101
  switch (message.MESSAGE_TYPE) {
86
102
  case MESSAGE_TYPE.EVENT_LOGIN_AUTH:
87
- return handleLogin(message, connection, config, tokens);
103
+ return handleLogin(message, connection, config, auth);
88
104
  case MESSAGE_TYPE.EVENT_LOGOUT:
89
- return handleLogout(message, connection, tokens);
105
+ return handleLogout(message, connection, config, auth);
90
106
  case MESSAGE_TYPE.HEARTBEAT_PING:
91
- return handleHeartbeat(message, connection, config);
107
+ return handleHeartbeat(message, connection, config, auth);
92
108
  case MESSAGE_TYPE.DATA_LOGON:
93
- return handleDataLogon(message, connection, config, store);
109
+ handleDataLogon(message, connection, config, store);
110
+ return connection.noteLogon(message);
94
111
  case MESSAGE_TYPE.DATA_LOGOFF:
95
112
  return handleDataLogoff(message, connection, config);
96
113
  case MESSAGE_TYPE.MORE_ROWS:
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
  }
@@ -198,6 +215,7 @@ export interface MockServerConfig {
198
215
  eventSchemas?: Record<string, EventSchemaOverride>;
199
216
  auth?: AuthConfig;
200
217
  resources?: ResourceItem[];
218
+ additionalResources?: ResourceItem[];
201
219
  httpRoutes?: HttpRouteDef[];
202
220
  onMessage?: OnMessageHook;
203
221
  productName?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@genesislcap/mock-server",
3
- "version": "15.65.1-alpha-358eaead70.0",
3
+ "version": "15.67.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",
@@ -10,6 +10,11 @@
10
10
  "types": "./dist/index.d.ts",
11
11
  "bun": "./src/index.ts",
12
12
  "default": "./dist/index.js"
13
+ },
14
+ "./presets": {
15
+ "types": "./dist/presets/index.d.ts",
16
+ "bun": "./src/presets/index.ts",
17
+ "default": "./dist/presets/index.js"
13
18
  }
14
19
  },
15
20
  "files": [
@@ -24,7 +29,8 @@
24
29
  "typecheck": "tsc --noEmit",
25
30
  "test": "node --experimental-strip-types --test \"test/**/*.test.ts\"",
26
31
  "test:conformance": "node --experimental-strip-types --test \"test/conformance/**/*.test.ts\"",
27
- "conformance:record": "node --experimental-strip-types test/conformance/record.ts"
32
+ "conformance:record": "node --experimental-strip-types test/conformance/record.ts",
33
+ "preset:generate": "node --experimental-strip-types scripts/platform-preset/generate.ts"
28
34
  },
29
35
  "dependencies": {
30
36
  "ws": "^8.18.0"