@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/README.md CHANGED
@@ -678,12 +678,53 @@ package) that both the WebSocket upgrade and the HTTP login handler
678
678
  (`handlers/http.ts`, built on Node's `IncomingMessage`/`ServerResponse`)
679
679
  share, so both transports work against the same port under either runtime.
680
680
 
681
+ Both transports answer as auth 8.15.5 does (recorded in
682
+ `test/conformance/recordings/showcase-real/`):
683
+
684
+ - **Login ack** (`EVENT_LOGIN_AUTH_ACK`, and `EVENT_LOGIN_DETAILS_ACK` for the same
685
+ session): `DETAILS` holds `HEARTBEAT_INTERVAL_SECONDS` (`auth.heartbeatIntervalSecs`,
686
+ default 0), `SESSION_TIMEOUT_MINS` (`auth.sessionTimeoutMins`, default 30),
687
+ `REFRESH_TOKEN_EXPIRATION_MINS` (`auth.refreshTokenExpirationMins`, default 7200),
688
+ `LAST_LOGIN_DATE_TIME`, `DAYS_TO_PASSWORD_EXPIRY: 730`, null `NOTIFY_EXPIRY` and `MFA_*`,
689
+ `SYSTEM.DATE` as Java prints a date, and `PRODUCT` (`auth.products`, default auth 8.15.5
690
+ and genesis 8.15.29). Top level: `UPDATE_QUEUE_DETAILS` (a stock ZeroMQ install's),
691
+ `USER` (`AuthUser.loginAck`, else null) and `USER_DETAILS` (`FIRST_NAME`/`LAST_NAME` of
692
+ `AuthUser.user`). HTTP replies carry a `SOURCE_REF` (the request's, or `AUTO_<uuid>`).
693
+ - **Failed login:** `EVENT_LOGIN_AUTH_NACK` with one `LoginError`
694
+ (`INCORRECT_CREDENTIALS`, "Problem logging in") and null `REFRESH_AUTH_TOKEN` /
695
+ `REFRESH_TOKEN_EXPIRATION_MINS`; over HTTP it is a **200**, as on GSF, so foundation-auth
696
+ takes its NACK path rather than its fetch-error path.
697
+ - **Logout:** `LOGOUT_ACK {OIDC_LOGOUT_URL: null}`, ending that session.
698
+ - **`HEARTBEAT_PING` with `VERBOSE: true`:** the pong adds `USER_NAME`, `CREATED_AT`,
699
+ `LAST_RECEIVED` and `LAST_SENT` (heartbeats don't count) and `RESOURCES`, the live
700
+ subscriptions by resource name.
701
+ - **`event-login-details` without a live session:** HTTP 401 with the router's `MSG_NACK`.
702
+
703
+ **Cookie authentication (on by default).** The router runs as GSF's shipped
704
+ `genesis-router.kts` does (`cookieAuthentication { enabled = true }`, which Create's blank
705
+ project and the showcase keep). An HTTP login sets the `sessionAuthToken`, `refreshAuthToken`,
706
+ `sessionId` and `mfaCode` cookies (a failed one clears `refreshAuthToken`, logout clears all
707
+ four); the HTTP endpoints read the session from the cookie; a WebSocket upgrade without a live
708
+ `sessionAuthToken` cookie gets HTTP 401; and on the socket the cookie authenticates every
709
+ message, so `EVENT_LOGIN_AUTH` and `EVENT_LOGOUT` there get `MSG_NACK` 403. So a client (or a
710
+ test) logs in over HTTP and opens the socket with the cookies. Pass an object
711
+ (`{ httpOnly, secure, sameSite, path, domain, sessionCookies }`) to change the cookie
712
+ attributes. `config.auth.cookieAuthentication: false` runs a GSF router without the block: no
713
+ cookies, an HTTP request names its session in a `SESSION_AUTH_TOKEN` header, and the socket
714
+ logs in with `EVENT_LOGIN_AUTH`. `fidelity: 'legacy'` defaults it off.
715
+
716
+ > **Behaviour change:** up to this release a socket opened without logging in, and a WS
717
+ > `EVENT_LOGIN_AUTH` was answered. Clients that log in over WS need
718
+ > `cookieAuthentication: false`; clients on foundation-auth's HTTP login work unchanged.
719
+
681
720
  Set `config.auth.httpAutoLogin: '<username>'` to make `event-login-details`
682
721
  always ack as that user — the client's silent-login check succeeds on first
683
722
  load and the login screen never appears, which is usually what you want for
684
- CI/local dev. Leave it unset to require an explicit `EVENT_LOGIN_AUTH` POST
685
- (validated against `config.auth.users`, same as the WS flow) before
686
- `event-login-details` will succeed on a later reload.
723
+ CI/local dev. A request without a live session gets a new one, and with
724
+ `cookieAuthentication` its login cookies too, so the socket can open. Leave it
725
+ unset to require an explicit `EVENT_LOGIN_AUTH` POST (validated against
726
+ `config.auth.users`, same as the WS flow) before `event-login-details` will
727
+ succeed on a later reload.
687
728
 
688
729
  An **opt-in** auth gate (`config.auth.requireAuth: true`) rejects WS data
689
730
  traffic (`DATA_LOGON`, `REQ_*`, `META_REQUEST`, `JSON_SCHEMA_REQUEST`, commit
@@ -801,6 +842,11 @@ createMockServer({ ...config, fidelity: 'legacy' });
801
842
  | The criteria functions | GSF's, typed by the declared fields ([Criteria functions](#criteria-functions)) | The same, a date compared with also read as ISO-8601 |
802
843
  | `REQ_` | As in [Request servers](#request-servers-req_): `PARAMETRIC_TYPE`, criteria-only paging and ordering, `REQUEST` wildcards, ranges and arrays, a reply block, `MSG_NACK` failures | Every matching row in insertion order; `REQUEST` from the top level or `DETAILS`, `'*'`/`null`/`''` match anything, an array value any of its values; `CRITERIA_MATCH` fails open; no `RECORD_ID`/`TIMESTAMP`; errors as a `REP_` with `ERROR` |
803
844
  | Unknown resource | `MSG_NACK` 404 (the client's promise rejects) | A typed reply with `ERROR: [{CODE: 'UNKNOWN_RESOURCE'}]` (the promise resolves) |
845
+ | Login ack | auth 8.15.5's ([Two auth transports](#two-auth-transports)): `HEARTBEAT_INTERVAL_SECONDS`, `UPDATE_QUEUE_DETAILS`, `USER_DETAILS`, `USER: null`, a `SOURCE_REF` on HTTP replies; `event-login-details` answers with the session's own tokens | `HEARTBEAT_INTERVAL_SECS` (default 30), top-level `UPDATE_QUEUE`/`ZERO_MQ_*`, `USER` = `AuthUser.user`, one `PRODUCT` named by `productName`; new tokens on every `event-login-details` |
846
+ | Failed login | `EVENT_LOGIN_AUTH_NACK` with a `LoginError`; HTTP 200 | HTTP 401; over WS `STATUS_CODE: '401'`, "Incorrect username or password" |
847
+ | `HEARTBEAT_PING` `VERBOSE: true`, `EVENT_LOGOUT` | The pong's verbose fields; `LOGOUT_ACK {OIDC_LOGOUT_URL: null}` | `IS_AUTHENTICATED` only; `LOGOUT_ACK` alone |
848
+ | `cookieAuthentication` unset | On: login cookies, 401 upgrade without one, WS login/logout `MSG_NACK` 403 | Off |
849
+ | HTTP session, without `cookieAuthentication` | A `SESSION_AUTH_TOKEN` header; no cookies; 401 `MSG_NACK` without a session | The `MOCK_SESSION_ID` cookie; 401 `EVENT_LOGIN_AUTH_NACK NOT_LOGGED_ON` |
804
850
 
805
851
  `test/legacyParity.test.ts` pins `'legacy'` to replies recorded from the 15.47.0 engine
806
852
  itself, for a config with no declarations and for the showcase config.
@@ -1,10 +1,29 @@
1
1
  import type { Connection } from '../protocol/connection.ts';
2
2
  import type { AuthUser, GenesisMessage, MockServerConfig, Row } from '../types.ts';
3
3
  export type TokenRegistry = Map<string, string>;
4
- export declare function capRegistry(registry: Map<string, string>): void;
5
- export declare function registerAckTokens(ack: Row, username: string, tokens: TokenRegistry): void;
6
- export declare function buildLoginAckBody(user: AuthUser, config: MockServerConfig, messageType?: string): Row;
4
+ export interface AuthSession {
5
+ username: string;
6
+ sessionAuthToken: string;
7
+ refreshAuthToken: string;
8
+ sessionId: string;
9
+ }
10
+ export interface AuthState {
11
+ tokens: TokenRegistry;
12
+ sessions: Map<string, AuthSession>;
13
+ lastLogin: Map<string, number>;
14
+ }
15
+ export declare function createAuthState(): AuthState;
16
+ export declare function capRegistry(registry: Map<string, unknown>): void;
17
+ export declare function openSession(auth: AuthState, user: AuthUser): AuthSession;
18
+ export declare function closeSession(auth: AuthState, session: AuthSession): void;
19
+ export declare function sessionByRefreshToken(auth: AuthState, refreshAuthToken: unknown): AuthSession | undefined;
20
+ export declare function sessionTimeoutMins(config: MockServerConfig): number;
21
+ export declare function refreshTokenExpirationMins(config: MockServerConfig): number;
22
+ export declare function javaDateString(date: Date): string;
23
+ export declare function buildLoginAckBody(user: AuthUser, session: AuthSession, config: MockServerConfig, auth: AuthState, messageType?: string): Row;
24
+ export declare function buildLoginNackBody(config: MockServerConfig, transport: 'ws' | 'http'): Row;
25
+ export declare function buildLogoutAckBody(config: MockServerConfig): Row;
7
26
  export declare function findUser(config: MockServerConfig, username?: string): AuthUser | undefined;
8
27
  export declare function findUserByCredentials(config: MockServerConfig, username?: string, password?: string): AuthUser | undefined;
9
- export declare function handleLogin(message: GenesisMessage, connection: Connection, config: MockServerConfig, tokens: TokenRegistry): void;
10
- export declare function handleLogout(message: GenesisMessage, connection: Connection, tokens: TokenRegistry): void;
28
+ export declare function handleLogin(message: GenesisMessage, connection: Connection, config: MockServerConfig, auth: AuthState): void;
29
+ export declare function handleLogout(message: GenesisMessage, connection: Connection, config: MockServerConfig, auth: AuthState): void;
@@ -1,6 +1,30 @@
1
1
  import crypto from 'node:crypto';
2
+ import { isLegacyFidelity } from "../protocol/fidelity.js";
2
3
  import { MESSAGE_TYPE, ERROR_CODE } from "../protocol/messageTypes.js";
3
- const DEFAULT_HEARTBEAT_INTERVAL_SECS = 30;
4
+ const LEGACY_HEARTBEAT_INTERVAL_SECS = 30;
5
+ // auth 8.15.5 AuthPreferencesDefinition.kt:17,19 defaults.
6
+ const DEFAULT_SESSION_TIMEOUT_MINS = 30;
7
+ const DEFAULT_REFRESH_TOKEN_EXPIRATION_MINS = 7200;
8
+ // LoginProcessor.kt:176-177 @auth v8.15.5: a user with no password expiry date.
9
+ const DAYS_TO_PASSWORD_EXPIRY_NONE = 730; // 2 * 365
10
+ // The versions this mock follows (test/conformance/README.md).
11
+ const DEFAULT_PRODUCTS = [
12
+ { NAME: 'auth', VERSION: '8.15.5' },
13
+ { NAME: 'genesis', VERSION: '8.15.29' },
14
+ ];
15
+ // What a stock ZeroMQ install reports (LoginProcessor.kt:247-256 @auth
16
+ // v8.15.5; the values recorded in http-login.json). The mock has no update
17
+ // queue, and no client reads this.
18
+ const UPDATE_QUEUE_DETAILS = {
19
+ UPDATE_QUEUE: 'ZeroMq',
20
+ ZERO_MQ_PROXY_MODE_ENABLED: false,
21
+ ZERO_MQ_PROXY_INBOUND_PORT: 5001,
22
+ ZERO_MQ_PROXY_OUTBOUND_PORT: 5000,
23
+ AERON_SERVICE_PORT: null,
24
+ };
25
+ export function createAuthState() {
26
+ return { tokens: new Map(), sessions: new Map(), lastLogin: new Map() };
27
+ }
4
28
  // Both transports mint tokens on every login/silent-login, so a long-lived
5
29
  // dev/CI server would otherwise grow these maps one entry per page load.
6
30
  // Maps iterate in insertion order, so dropping from the front evicts the
@@ -14,21 +38,113 @@ export function capRegistry(registry) {
14
38
  registry.delete(oldest);
15
39
  }
16
40
  }
17
- export function registerAckTokens(ack, username, tokens) {
18
- tokens.set(ack.SESSION_AUTH_TOKEN, username);
19
- tokens.set(ack.REFRESH_AUTH_TOKEN, username);
20
- capRegistry(tokens);
41
+ export function openSession(auth, user) {
42
+ const session = {
43
+ username: user.username,
44
+ sessionAuthToken: crypto.randomUUID(),
45
+ refreshAuthToken: crypto.randomUUID(),
46
+ sessionId: crypto.randomUUID(),
47
+ };
48
+ auth.sessions.set(session.sessionAuthToken, session);
49
+ capRegistry(auth.sessions);
50
+ auth.tokens.set(session.sessionAuthToken, user.username);
51
+ auth.tokens.set(session.refreshAuthToken, user.username);
52
+ capRegistry(auth.tokens);
53
+ auth.lastLogin.set(user.username, Date.now());
54
+ return session;
55
+ }
56
+ // Revokes the session's tokens, not just the session: every message
57
+ // re-adopts a stamped SESSION_AUTH_TOKEN (see router.ts), so a token left in
58
+ // the registry silently logs a connection straight back in.
59
+ export function closeSession(auth, session) {
60
+ auth.sessions.delete(session.sessionAuthToken);
61
+ auth.tokens.delete(session.sessionAuthToken);
62
+ auth.tokens.delete(session.refreshAuthToken);
63
+ }
64
+ export function sessionByRefreshToken(auth, refreshAuthToken) {
65
+ if (typeof refreshAuthToken !== 'string')
66
+ return undefined;
67
+ for (const session of auth.sessions.values()) {
68
+ if (session.refreshAuthToken === refreshAuthToken)
69
+ return session;
70
+ }
71
+ return undefined;
72
+ }
73
+ export function sessionTimeoutMins(config) {
74
+ return config.auth?.sessionTimeoutMins ?? DEFAULT_SESSION_TIMEOUT_MINS;
75
+ }
76
+ export function refreshTokenExpirationMins(config) {
77
+ return config.auth?.refreshTokenExpirationMins ?? DEFAULT_REFRESH_TOKEN_EXPIRATION_MINS;
78
+ }
79
+ const DAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
80
+ const MONTH_NAMES = [
81
+ 'Jan',
82
+ 'Feb',
83
+ 'Mar',
84
+ 'Apr',
85
+ 'May',
86
+ 'Jun',
87
+ 'Jul',
88
+ 'Aug',
89
+ 'Sep',
90
+ 'Oct',
91
+ 'Nov',
92
+ 'Dec',
93
+ ];
94
+ // java.util.Date#toString in UTC ("Thu Oct 01 13:05:42 UTC 2026"), which is
95
+ // what auth sends as DETAILS.SYSTEM.DATE (LoginProcessor.kt:228).
96
+ export function javaDateString(date) {
97
+ const pad = (value) => String(value).padStart(2, '0');
98
+ const time = [date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()].map(pad).join(':');
99
+ return `${DAY_NAMES[date.getUTCDay()]} ${MONTH_NAMES[date.getUTCMonth()]} ${pad(date.getUTCDate())} ${time} UTC ${date.getUTCFullYear()}`;
21
100
  }
22
- // Shared by the WS EVENT_LOGIN_AUTH handler and the HTTP login handlers
23
- // (handlers/http.ts) — EVENT_LOGIN_DETAILS_ACK is byte-for-byte the same shape
24
- // as EVENT_LOGIN_AUTH_ACK, just under a different MESSAGE_TYPE (see
25
- // foundation-auth's EVENT_LOGIN_DETAILS_ACK.ts, which literally extends it).
26
- export function buildLoginAckBody(user, config, messageType = MESSAGE_TYPE.EVENT_LOGIN_AUTH_ACK) {
101
+ // The login ack, GSF auth 8.15.5 (LoginProcessor.successfulLoginMessage,
102
+ // LoginProcessor.kt:163-245; field names from Events.kt:66-114). Recorded in
103
+ // http-login.json. EVENT_LOGIN_DETAILS_ACK is the same body under its own
104
+ // MESSAGE_TYPE (Events.kt:79-82), built afresh for the same session
105
+ // (auth-login-eventhandler.kts:84-116). Nothing here is a login count: a
106
+ // successful login resets FAILED_ and REJECTED_LOGIN_ATTEMPTS to 0
107
+ // (LoginAuditController.kt:63,187).
108
+ export function buildLoginAckBody(user, session, config, auth, messageType = MESSAGE_TYPE.EVENT_LOGIN_AUTH_ACK) {
109
+ if (isLegacyFidelity(config))
110
+ return buildLegacyLoginAckBody(user, session, config, messageType);
27
111
  return {
112
+ SESSION_AUTH_TOKEN: session.sessionAuthToken,
113
+ REFRESH_AUTH_TOKEN: session.refreshAuthToken,
114
+ SESSION_ID: session.sessionId,
115
+ USER_NAME: user.username,
116
+ DETAILS: {
117
+ HEARTBEAT_INTERVAL_SECONDS: config.auth?.heartbeatIntervalSecs ?? 0,
118
+ SESSION_TIMEOUT_MINS: sessionTimeoutMins(config),
119
+ REFRESH_TOKEN_EXPIRATION_MINS: refreshTokenExpirationMins(config),
120
+ FAILED_LOGIN_ATTEMPTS: 0,
121
+ REJECTED_LOGIN_ATTEMPTS: 0,
122
+ LAST_LOGIN_DATE_TIME: auth.lastLogin.get(user.username) ?? null,
123
+ DAYS_TO_PASSWORD_EXPIRY: DAYS_TO_PASSWORD_EXPIRY_NONE,
124
+ NOTIFY_EXPIRY: null,
125
+ MFA_CODE: null,
126
+ MFA_CODE_EXPIRY_MINS: null,
127
+ SYSTEM: { DATE: javaDateString(new Date()) },
128
+ PRODUCT: config.auth?.products ?? DEFAULT_PRODUCTS,
129
+ },
130
+ PERMISSION: user.permission ?? [],
131
+ PROFILE: user.profile ?? [],
132
+ UPDATE_QUEUE_DETAILS: UPDATE_QUEUE_DETAILS,
133
+ USER: user.loginAck ?? null,
134
+ USER_DETAILS: {
135
+ FIRST_NAME: user.user?.FIRST_NAME ?? null,
136
+ LAST_NAME: user.user?.LAST_NAME ?? null,
137
+ },
28
138
  MESSAGE_TYPE: messageType,
29
- SESSION_AUTH_TOKEN: crypto.randomUUID(),
30
- REFRESH_AUTH_TOKEN: crypto.randomUUID(),
31
- SESSION_ID: crypto.randomUUID(),
139
+ };
140
+ }
141
+ // fidelity: 'legacy': the ack this engine sent up to 15.47.
142
+ function buildLegacyLoginAckBody(user, session, config, messageType) {
143
+ return {
144
+ MESSAGE_TYPE: messageType,
145
+ SESSION_AUTH_TOKEN: session.sessionAuthToken,
146
+ REFRESH_AUTH_TOKEN: session.refreshAuthToken,
147
+ SESSION_ID: session.sessionId,
32
148
  USER_NAME: user.username,
33
149
  UPDATE_QUEUE: 'MOCK',
34
150
  ZERO_MQ_PROXY_MODE_ENABLED: false,
@@ -37,7 +153,7 @@ export function buildLoginAckBody(user, config, messageType = MESSAGE_TYPE.EVENT
37
153
  USER: user.user ?? {},
38
154
  DETAILS: {
39
155
  SYSTEM: { DATE: new Date().toISOString() },
40
- HEARTBEAT_INTERVAL_SECS: config.auth?.heartbeatIntervalSecs ?? DEFAULT_HEARTBEAT_INTERVAL_SECS,
156
+ HEARTBEAT_INTERVAL_SECS: config.auth?.heartbeatIntervalSecs ?? LEGACY_HEARTBEAT_INTERVAL_SECS,
41
157
  FAILED_LOGIN_ATTEMPTS: 0,
42
158
  REJECTED_LOGIN_ATTEMPTS: 0,
43
159
  LAST_LOGIN_DATETIME: 0,
@@ -48,6 +164,53 @@ export function buildLoginAckBody(user, config, messageType = MESSAGE_TYPE.EVENT
48
164
  PROFILE: user.profile ?? [],
49
165
  };
50
166
  }
167
+ // A failed login, GSF auth 8.15.5: one LoginError (Events.kt:91-98,133-140)
168
+ // with the "Problem logging in" text, for a wrong password and an unknown
169
+ // user alike (LoginProcessor.kt:160-161,330). Over HTTP it is a 200
170
+ // (http-login-failed.json).
171
+ export function buildLoginNackBody(config, transport) {
172
+ if (isLegacyFidelity(config)) {
173
+ return {
174
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
175
+ ERROR: [
176
+ transport === 'ws'
177
+ ? {
178
+ CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
179
+ STATUS_CODE: '401',
180
+ TEXT: 'Incorrect username or password',
181
+ }
182
+ : {
183
+ CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
184
+ STATUS_CODE: '401 Unauthorized',
185
+ TEXT: 'Problem logging in',
186
+ },
187
+ ],
188
+ WARNING: [],
189
+ };
190
+ }
191
+ return {
192
+ ERROR: [
193
+ {
194
+ '@type': 'LoginError',
195
+ CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
196
+ TEXT: 'Problem logging in',
197
+ STATUS_CODE: '401 Unauthorized',
198
+ DETAILS: null,
199
+ },
200
+ ],
201
+ WARNING: [],
202
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
203
+ REFRESH_AUTH_TOKEN: null,
204
+ REFRESH_TOKEN_EXPIRATION_MINS: null,
205
+ };
206
+ }
207
+ // LOGOUT_ACK, GSF auth 8.15.5 (Events.kt:121-123): OIDC_LOGOUT_URL is null
208
+ // without an OIDC provider.
209
+ export function buildLogoutAckBody(config) {
210
+ if (isLegacyFidelity(config))
211
+ return { MESSAGE_TYPE: MESSAGE_TYPE.LOGOUT_ACK };
212
+ return { OIDC_LOGOUT_URL: null, MESSAGE_TYPE: MESSAGE_TYPE.LOGOUT_ACK };
213
+ }
51
214
  // Trusted lookup by username alone — for paths where identity is already
52
215
  // established (a token this server issued, an HTTP session cookie,
53
216
  // httpAutoLogin). NEVER use this for a credentials login.
@@ -65,57 +228,47 @@ export function findUserByCredentials(config, username, password) {
65
228
  const user = findUser(config, username);
66
229
  return user && user.password === password ? user : undefined;
67
230
  }
68
- export function handleLogin(message, connection, config, tokens) {
231
+ export function handleLogin(message, connection, config, auth) {
69
232
  const details = message.DETAILS ?? {};
70
233
  // Two login shapes share EVENT_LOGIN_AUTH: credentials ({USER_NAME,
71
234
  // PASSWORD}) and token refresh — foundation-comms' createRefreshTokenMessage
72
235
  // sends only DETAILS.REFRESH_AUTH_TOKEN (plus the stored SESSION_AUTH_TOKEN
73
236
  // at the top level), no username at all.
74
237
  const tokenUsername = details.USER_NAME === undefined
75
- ? (tokens.get(details.REFRESH_AUTH_TOKEN) ??
76
- tokens.get(details.SESSION_AUTH_TOKEN) ??
77
- tokens.get(message.SESSION_AUTH_TOKEN))
238
+ ? (auth.tokens.get(details.REFRESH_AUTH_TOKEN) ??
239
+ auth.tokens.get(details.SESSION_AUTH_TOKEN) ??
240
+ auth.tokens.get(message.SESSION_AUTH_TOKEN))
78
241
  : undefined;
79
242
  const user = details.USER_NAME !== undefined
80
243
  ? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
81
244
  : findUser(config, tokenUsername);
82
245
  if (!user) {
83
- connection.reply(message, {
84
- MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
85
- ERROR: [
86
- {
87
- CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
88
- STATUS_CODE: '401',
89
- TEXT: 'Incorrect username or password',
90
- },
91
- ],
92
- WARNING: [],
93
- });
246
+ connection.reply(message, buildLoginNackBody(config, 'ws'));
94
247
  return;
95
248
  }
96
- const ack = buildLoginAckBody(user, config);
97
- registerAckTokens(ack, user.username, tokens);
249
+ const session = openSession(auth, user);
98
250
  connection.authenticated = true;
99
251
  connection.userName = user.username;
100
252
  connection.profile = user.profile ?? [];
101
253
  connection.permission = user.permission ?? [];
102
- connection.sessionAuthToken = ack.SESSION_AUTH_TOKEN;
103
- connection.refreshAuthToken = ack.REFRESH_AUTH_TOKEN;
104
- connection.sessionId = ack.SESSION_ID;
105
- connection.reply(message, ack);
106
- }
107
- export function handleLogout(message, connection, tokens) {
108
- // Revoke this connection's tokens, not just its authenticated flag: every
109
- // message re-adopts a stamped SESSION_AUTH_TOKEN (see router.ts), so a
110
- // token left in the registry silently logs the connection straight back in
111
- // on its very next request.
254
+ connection.sessionAuthToken = session.sessionAuthToken;
255
+ connection.refreshAuthToken = session.refreshAuthToken;
256
+ connection.sessionId = session.sessionId;
257
+ connection.reply(message, buildLoginAckBody(user, session, config, auth));
258
+ }
259
+ export function handleLogout(message, connection, config, auth) {
260
+ const session = connection.sessionAuthToken === undefined
261
+ ? undefined
262
+ : auth.sessions.get(connection.sessionAuthToken);
263
+ if (session)
264
+ closeSession(auth, session);
112
265
  for (const token of [connection.sessionAuthToken, connection.refreshAuthToken]) {
113
266
  if (token !== undefined)
114
- tokens.delete(token);
267
+ auth.tokens.delete(token);
115
268
  }
116
269
  connection.authenticated = false;
117
270
  connection.sessionAuthToken = undefined;
118
271
  connection.refreshAuthToken = undefined;
119
272
  connection.subscriptions.clear();
120
- connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.LOGOUT_ACK });
273
+ connection.reply(message, buildLogoutAckBody(config));
121
274
  }
@@ -1,3 +1,4 @@
1
1
  import type { Connection } from '../protocol/connection.ts';
2
2
  import type { GenesisMessage, MockServerConfig } from '../types.ts';
3
- export declare function handleHeartbeat(message: GenesisMessage, connection: Connection, config: MockServerConfig): void;
3
+ import type { AuthState } from './auth.ts';
4
+ export declare function handleHeartbeat(message: GenesisMessage, connection: Connection, config: MockServerConfig, auth: AuthState): void;
@@ -1,5 +1,12 @@
1
+ import { isLegacyFidelity } from "../protocol/fidelity.js";
1
2
  import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
2
- export function handleHeartbeat(message, connection, config) {
3
+ // HEARTBEAT_PONG, as genesis-router answers it
4
+ // (RouterMessageDelegator.handleHeartbeat, RouterMessageDelegator.kt:158-195
5
+ // @v8.15.29): IS_AUTHENTICATED, plus with VERBOSE:true the connection's
6
+ // USER_NAME, CREATED_AT, LAST_RECEIVED, LAST_SENT and RESOURCES
7
+ // (heartbeat.json). The router writes it straight to the socket, so it
8
+ // doesn't count as LAST_SENT.
9
+ export function handleHeartbeat(message, connection, config, auth) {
3
10
  // With the auth gate off (the default), this server accepts every data
4
11
  // message — so the pong must report IS_AUTHENTICATED: true even though the
5
12
  // WS connection itself never "logged in". HTTP-login clients (httpAutoLogin
@@ -9,8 +16,24 @@ export function handleHeartbeat(message, connection, config) {
9
16
  // down, defeating httpAutoLogin entirely. Only when a project opts into
10
17
  // auth.requireAuth does the flag reflect real connection auth state.
11
18
  const requireAuth = config.auth?.requireAuth ?? false;
19
+ const IS_AUTHENTICATED = connection.authenticated || !requireAuth;
20
+ if (isLegacyFidelity(config) || message.VERBOSE !== true) {
21
+ connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.HEARTBEAT_PONG, IS_AUTHENTICATED }, false);
22
+ return;
23
+ }
24
+ // A ping carrying a token names the session's user ('' for a dead one);
25
+ // otherwise the connection's own login.
26
+ const token = message.SESSION_AUTH_TOKEN;
27
+ const USER_NAME = typeof token === 'string'
28
+ ? (auth.sessions.get(token)?.username ?? '')
29
+ : (connection.userName ?? null);
12
30
  connection.reply(message, {
31
+ IS_AUTHENTICATED,
32
+ USER_NAME,
33
+ CREATED_AT: connection.createdAt,
34
+ LAST_RECEIVED: connection.lastReceived,
35
+ LAST_SENT: connection.lastSent,
36
+ RESOURCES: connection.dataserverResources(),
13
37
  MESSAGE_TYPE: MESSAGE_TYPE.HEARTBEAT_PONG,
14
- IS_AUTHENTICATED: connection.authenticated || !requireAuth,
15
- });
38
+ }, false);
16
39
  }
@@ -1,4 +1,7 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
- import type { MockServerConfig } from '../types.ts';
3
- import { type TokenRegistry } from './auth.ts';
4
- export declare function createHttpRequestListener(config: MockServerConfig, sessions: Map<string, string>, tokens?: TokenRegistry): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
2
+ import type { CookieAuthenticationOptions, MockServerConfig } from '../types.ts';
3
+ import { type AuthState } from './auth.ts';
4
+ export declare const SESSION_AUTH_TOKEN_COOKIE = "sessionAuthToken";
5
+ export declare function cookieAuthentication(config: MockServerConfig): CookieAuthenticationOptions | undefined;
6
+ export declare function parseCookies(header: string | undefined): Record<string, string>;
7
+ export declare function createHttpRequestListener(config: MockServerConfig, legacySessions: Map<string, string>, auth?: AuthState): (req: IncomingMessage, res: ServerResponse) => Promise<void>;