@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,23 +1,50 @@
1
1
  import crypto from 'node:crypto';
2
+ import { isLegacyFidelity } from "../protocol/fidelity.js";
2
3
  import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
3
- import { buildLoginAckBody, capRegistry, findUser, findUserByCredentials, registerAckTokens, } from "./auth.js";
4
- const SESSION_COOKIE = 'MOCK_SESSION_ID';
4
+ import { notLoggedInNack } from "../protocol/msgNack.js";
5
+ import { buildLoginAckBody, buildLoginNackBody, buildLogoutAckBody, capRegistry, closeSession, createAuthState, findUser, findUserByCredentials, openSession, refreshTokenExpirationMins, sessionByRefreshToken, sessionTimeoutMins, } from "./auth.js";
6
+ // fidelity: 'legacy' without cookieAuthentication: the mock's own session
7
+ // cookie, sessionId -> username.
8
+ const LEGACY_SESSION_COOKIE = 'MOCK_SESSION_ID';
9
+ // genesis-router CookieHandler.kt:195-202 @v8.15.29.
10
+ export const SESSION_AUTH_TOKEN_COOKIE = 'sessionAuthToken';
11
+ const REFRESH_AUTH_TOKEN_COOKIE = 'refreshAuthToken';
12
+ const SESSION_ID_COOKIE = 'sessionId';
13
+ const MFA_CODE_COOKIE = 'mfaCode';
14
+ const SECONDS_PER_MINUTE = 60;
15
+ const MILLIS_PER_SECOND = 1000;
5
16
  const HTTP_STATUS = {
6
17
  OK: 200,
7
18
  UNAUTHORIZED: 401,
8
19
  NOT_FOUND: 404,
9
20
  INTERNAL_SERVER_ERROR: 500,
10
21
  };
22
+ // The `cookieAuthentication { }` block GSF ships in genesis-router.kts.
23
+ const SHIPPED_COOKIE_OPTIONS = {
24
+ httpOnly: true,
25
+ secure: false,
26
+ sameSite: 'Lax',
27
+ path: '/',
28
+ sessionCookies: false,
29
+ };
30
+ export function cookieAuthentication(config) {
31
+ // On unless the config opts out, as GSF ships it; off under fidelity: 'legacy'.
32
+ const option = config.auth?.cookieAuthentication ?? !isLegacyFidelity(config);
33
+ if (!option)
34
+ return undefined;
35
+ return option === true ? SHIPPED_COOKIE_OPTIONS : { ...SHIPPED_COOKIE_OPTIONS, ...option };
36
+ }
11
37
  // foundation-auth's login UI (client-app-login) doesn't use the WebSocket
12
38
  // EVENT_LOGIN_AUTH flow at all — it POSTs credentials over plain HTTP to
13
- // gwf/event-login-auth, and separately GETs gwf/event-login-details on every
14
- // app load (cookie-based silent login: foundation-comms/src/connect/
15
- // sessionRefresh.ts's isAuthenticated()). Both expect the exact same ACK body
16
- // shape as the WS login (EVENT_LOGIN_DETAILS_ACK literally extends
17
- // EVENT_LOGIN_AUTH_ACK), just reached over HTTP with a session cookie instead
18
- // of SOURCE_REF correlation. This is a *separate* transport from the WS
19
- // protocol in server.ts — a client-app can use either, or (as here) both.
20
- function parseCookies(header) {
39
+ // gwf/event-login-auth, and separately POSTs gwf/event-login-details on every
40
+ // app load (silent login; foundation-comms/src/connect/sessionRefresh.ts's
41
+ // isAuthenticated() GETs it later). Both expect the same ACK body as the WS
42
+ // login (EVENT_LOGIN_DETAILS_ACK literally extends EVENT_LOGIN_AUTH_ACK), with
43
+ // the session named by a cookie (cookieAuthentication) or a SESSION_AUTH_TOKEN
44
+ // header instead of SOURCE_REF correlation. This is a *separate* transport
45
+ // from the WS protocol in server.ts — a client-app can use either, or (as
46
+ // here) both.
47
+ export function parseCookies(header) {
21
48
  const cookies = {};
22
49
  for (const part of (header ?? '').split(';')) {
23
50
  const [key, ...rest] = part.trim().split('=');
@@ -26,10 +53,64 @@ function parseCookies(header) {
26
53
  }
27
54
  return cookies;
28
55
  }
29
- function setSessionCookie(res, sessionId) {
30
- res.setHeader('Set-Cookie', `${SESSION_COOKIE}=${sessionId}; Path=/; SameSite=Lax`);
56
+ // As Netty's ServerCookieEncoder.STRICT writes it (CookieHandler.kt:178-192
57
+ // @v8.15.29): Max-Age and Expires unless it is a session cookie, then Path,
58
+ // Domain, Secure, HTTPOnly, SameSite.
59
+ function encodeCookie(options, name, value, maxAgeSecs) {
60
+ const parts = [`${name}=${value}`];
61
+ if (maxAgeSecs !== undefined) {
62
+ const expires = new Date(Date.now() + maxAgeSecs * MILLIS_PER_SECOND);
63
+ parts.push(`Max-Age=${maxAgeSecs}`, `Expires=${expires.toUTCString()}`);
64
+ }
65
+ if (options.path)
66
+ parts.push(`Path=${options.path}`);
67
+ if (options.domain)
68
+ parts.push(`Domain=${options.domain}`);
69
+ if (options.secure)
70
+ parts.push('Secure');
71
+ if (options.httpOnly)
72
+ parts.push('HTTPOnly');
73
+ if (options.sameSite)
74
+ parts.push(`SameSite=${options.sameSite}`);
75
+ return parts.join('; ');
76
+ }
77
+ // The cookies GSF's router sets on an EVENT_LOGIN_AUTH_ACK
78
+ // (CookieHandler.kt:91-130): the session token lives as long as the session,
79
+ // the refresh token and session id as long as the refresh token, and the
80
+ // unused MFA code expires at once.
81
+ function loginCookies(options, config, session) {
82
+ const sessionMaxAge = options.sessionCookies
83
+ ? undefined
84
+ : sessionTimeoutMins(config) * SECONDS_PER_MINUTE;
85
+ const refreshMaxAge = options.sessionCookies
86
+ ? undefined
87
+ : refreshTokenExpirationMins(config) * SECONDS_PER_MINUTE;
88
+ return [
89
+ encodeCookie(options, SESSION_AUTH_TOKEN_COOKIE, session.sessionAuthToken, sessionMaxAge),
90
+ encodeCookie(options, REFRESH_AUTH_TOKEN_COOKIE, session.refreshAuthToken, refreshMaxAge),
91
+ encodeCookie(options, SESSION_ID_COOKIE, session.sessionId, refreshMaxAge),
92
+ encodeCookie(options, MFA_CODE_COOKIE, '', 0),
93
+ ];
31
94
  }
32
- function sendJson(res, status, body) {
95
+ // On EVENT_LOGIN_AUTH_NACK the router sets the NACK's REFRESH_AUTH_TOKEN
96
+ // (null) for its REFRESH_TOKEN_EXPIRATION_MINS (null): an empty cookie that
97
+ // expires at once (CookieHandler.kt:132-139); recorded in
98
+ // http-login-failed.json.
99
+ function loginNackCookies(options) {
100
+ return [encodeCookie(options, REFRESH_AUTH_TOKEN_COOKIE, '', 0)];
101
+ }
102
+ // LOGOUT_ACK expires all four (CookieHandler.kt:141-147).
103
+ function logoutCookies(options) {
104
+ return [
105
+ SESSION_AUTH_TOKEN_COOKIE,
106
+ REFRESH_AUTH_TOKEN_COOKIE,
107
+ SESSION_ID_COOKIE,
108
+ MFA_CODE_COOKIE,
109
+ ].map((name) => encodeCookie(options, name, '', 0));
110
+ }
111
+ function sendJson(res, status, body, cookies = []) {
112
+ if (cookies.length > 0)
113
+ res.setHeader('Set-Cookie', cookies);
33
114
  res.writeHead(status, { 'Content-Type': 'application/json' });
34
115
  res.end(JSON.stringify(body));
35
116
  }
@@ -49,28 +130,175 @@ async function readJsonBody(req) {
49
130
  const raw = Buffer.concat(chunks).toString('utf8');
50
131
  return raw ? JSON.parse(raw) : {};
51
132
  }
52
- // Drops every token this server minted for `username`. Logout has to do this,
53
- // not just forget the session: router.ts re-adopts any known SESSION_AUTH_TOKEN
54
- // on every message, so a token left in the registry logs a WS connection
55
- // straight back in on its next request.
56
- function revokeTokensFor(tokens, username) {
57
- for (const [token, owner] of tokens) {
133
+ // A header the client may send as SESSION_AUTH_TOKEN or, as foundation-comms'
134
+ // createHTTPHeadersFromMessage does, SESSION-AUTH-TOKEN.
135
+ function headerValue(req, name) {
136
+ const value = req.headers[name.toLowerCase()] ?? req.headers[name.toLowerCase().replaceAll('_', '-')];
137
+ return typeof value === 'string' ? value : undefined;
138
+ }
139
+ function autoLoginUser(config) {
140
+ const autoLogin = config.auth?.httpAutoLogin;
141
+ if (!autoLogin)
142
+ return undefined;
143
+ return findUser(config, autoLogin === true ? config.auth?.users?.[0]?.username : autoLogin);
144
+ }
145
+ // Drops every token this server minted for `username` (fidelity: 'legacy',
146
+ // whose logout ends all of the user's sessions).
147
+ function revokeSessionsOf(auth, username) {
148
+ for (const session of auth.sessions.values()) {
149
+ if (session.username === username)
150
+ closeSession(auth, session);
151
+ }
152
+ for (const [token, owner] of auth.tokens) {
58
153
  if (owner === username)
59
- tokens.delete(token);
154
+ auth.tokens.delete(token);
60
155
  }
61
156
  }
62
- // Reuse the request's own session when its cookie already maps to this user —
63
- // otherwise every page load would mint (and leak) a fresh session entry on a
64
- // long-lived dev/CI server.
65
- function ensureSession(sessions, cookieSessionId, username) {
66
- if (cookieSessionId && sessions.get(cookieSessionId) === username)
157
+ // fidelity: 'legacy': reuse the request's MOCK_SESSION_ID when it already maps
158
+ // to this user — otherwise every page load would mint (and leak) a fresh
159
+ // session entry on a long-lived dev/CI server.
160
+ function ensureLegacySession(legacySessions, cookieSessionId, username) {
161
+ if (cookieSessionId && legacySessions.get(cookieSessionId) === username)
67
162
  return cookieSessionId;
68
163
  const sessionId = crypto.randomUUID();
69
- sessions.set(sessionId, username);
70
- capRegistry(sessions);
164
+ legacySessions.set(sessionId, username);
165
+ capRegistry(legacySessions);
71
166
  return sessionId;
72
167
  }
73
- export function createHttpRequestListener(config, sessions, tokens = new Map()) {
168
+ function legacySessionCookie(sessionId) {
169
+ return `${LEGACY_SESSION_COOKIE}=${sessionId}; Path=/; SameSite=Lax`;
170
+ }
171
+ export function createHttpRequestListener(config, legacySessions, auth = createAuthState()) {
172
+ // Every HTTP reply carries a SOURCE_REF: the request's, or AUTO_<uuid> as
173
+ // the router mints one (http-login.json). Not under fidelity: 'legacy'.
174
+ const withSourceRef = (body, request = {}) => isLegacyFidelity(config)
175
+ ? body
176
+ : { ...body, SOURCE_REF: request.SOURCE_REF ?? `AUTO_${crypto.randomUUID()}` };
177
+ // The session a request names: the sessionAuthToken cookie under
178
+ // cookieAuthentication, else (GSF) the SESSION_AUTH_TOKEN header. '' when
179
+ // the cookie is there but empty, as after a logout cleared it.
180
+ function requestToken(req, cookies) {
181
+ if (cookieAuthentication(config))
182
+ return cookies[SESSION_AUTH_TOKEN_COOKIE];
183
+ return headerValue(req, 'SESSION_AUTH_TOKEN');
184
+ }
185
+ // The legacy-mode session cookie, or none.
186
+ function legacyCookies(cookies, username) {
187
+ if (!isLegacyFidelity(config) || cookieAuthentication(config))
188
+ return [];
189
+ return [
190
+ legacySessionCookie(ensureLegacySession(legacySessions, cookies[LEGACY_SESSION_COOKIE], username)),
191
+ ];
192
+ }
193
+ // A session opened by a login (or an httpAutoLogin): the login cookies.
194
+ function sessionCookies(cookies, session) {
195
+ const options = cookieAuthentication(config);
196
+ return options
197
+ ? loginCookies(options, config, session)
198
+ : legacyCookies(cookies, session.username);
199
+ }
200
+ function handleLoginDetails(req, res, request) {
201
+ const cookies = parseCookies(req.headers.cookie);
202
+ const legacyWithoutCookies = isLegacyFidelity(config) && !cookieAuthentication(config);
203
+ const autoLogin = autoLoginUser(config);
204
+ // fidelity: 'legacy' without cookieAuthentication: as up to 15.47, a new
205
+ // session per call, found by the MOCK_SESSION_ID cookie.
206
+ if (legacyWithoutCookies) {
207
+ const user = autoLogin ?? findUser(config, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
208
+ if (!user) {
209
+ sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
210
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
211
+ ERROR: [
212
+ { CODE: 'NOT_LOGGED_ON', STATUS_CODE: '401 Unauthorized', TEXT: 'No active session' },
213
+ ],
214
+ });
215
+ return;
216
+ }
217
+ const session = openSession(auth, user);
218
+ const body = buildLoginAckBody(user, session, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
219
+ sendJson(res, HTTP_STATUS.OK, body, legacyCookies(cookies, user.username));
220
+ return;
221
+ }
222
+ const token = requestToken(req, cookies);
223
+ const session = token === undefined ? undefined : auth.sessions.get(token);
224
+ const sessionUser = session && findUser(config, session.username);
225
+ if (session && sessionUser) {
226
+ const body = buildLoginAckBody(sessionUser, session, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
227
+ sendJson(res, HTTP_STATUS.OK, withSourceRef(body, request));
228
+ return;
229
+ }
230
+ // httpAutoLogin: a request without a live session logs the user in.
231
+ if (autoLogin) {
232
+ const opened = openSession(auth, autoLogin);
233
+ const body = buildLoginAckBody(autoLogin, opened, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
234
+ sendJson(res, HTTP_STATUS.OK, withSourceRef(body, request), sessionCookies(cookies, opened));
235
+ return;
236
+ }
237
+ sendJson(res, HTTP_STATUS.UNAUTHORIZED, withSourceRef(notLoggedInNack(token !== undefined), request));
238
+ }
239
+ async function handleLoginAuth(req, res) {
240
+ const body = await readJsonBody(req);
241
+ const details = body.DETAILS ?? {};
242
+ const cookies = parseCookies(req.headers.cookie);
243
+ const cookieOptions = cookieAuthentication(config);
244
+ // No USER_NAME: a token refresh (foundation-comms' sessionRefresh
245
+ // performRefresh). Its refresh token is the refreshAuthToken cookie under
246
+ // cookieAuthentication (CookieHandler.kt:62-67), else DETAILS'; under
247
+ // fidelity: 'legacy' without cookies, the MOCK_SESSION_ID session.
248
+ let user;
249
+ if (details.USER_NAME !== undefined) {
250
+ user = findUserByCredentials(config, details.USER_NAME, details.PASSWORD);
251
+ }
252
+ else if (isLegacyFidelity(config) && !cookieOptions) {
253
+ user = findUser(config, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
254
+ }
255
+ else {
256
+ const refreshToken = cookieOptions
257
+ ? cookies[REFRESH_AUTH_TOKEN_COOKIE]
258
+ : (details.REFRESH_AUTH_TOKEN ?? headerValue(req, 'REFRESH_AUTH_TOKEN'));
259
+ user = findUser(config, sessionByRefreshToken(auth, refreshToken)?.username);
260
+ }
261
+ if (!user) {
262
+ // GSF answers a failed login with HTTP 200; fidelity: 'legacy' with 401.
263
+ const status = isLegacyFidelity(config) ? HTTP_STATUS.UNAUTHORIZED : HTTP_STATUS.OK;
264
+ const nackCookies = cookieOptions ? loginNackCookies(cookieOptions) : [];
265
+ sendJson(res, status, withSourceRef(buildLoginNackBody(config, 'http'), body), nackCookies);
266
+ return;
267
+ }
268
+ const session = openSession(auth, user);
269
+ const ack = buildLoginAckBody(user, session, config, auth);
270
+ sendJson(res, HTTP_STATUS.OK, withSourceRef(ack, body), sessionCookies(cookies, session));
271
+ }
272
+ async function handleLogout(req, res) {
273
+ const body = await readJsonBody(req).catch(() => ({}));
274
+ const cookies = parseCookies(req.headers.cookie);
275
+ const cookieOptions = cookieAuthentication(config);
276
+ if (isLegacyFidelity(config) && !cookieOptions) {
277
+ const sessionId = cookies[LEGACY_SESSION_COOKIE];
278
+ const username = legacySessions.get(sessionId);
279
+ legacySessions.delete(sessionId);
280
+ if (username !== undefined)
281
+ revokeSessionsOf(auth, username);
282
+ sendJson(res, HTTP_STATUS.OK, buildLogoutAckBody(config));
283
+ return;
284
+ }
285
+ // auth's LOGOUT ends the session SESSION_ID names (the sessionId cookie
286
+ // under cookieAuthentication, CookieHandler.kt:76-81), else the token's.
287
+ const sessionId = cookieOptions
288
+ ? cookies[SESSION_ID_COOKIE]
289
+ : (body.SESSION_ID ?? headerValue(req, 'SESSION_ID'));
290
+ const token = cookieOptions ? cookies[SESSION_AUTH_TOKEN_COOKIE] : requestToken(req, cookies);
291
+ for (const session of auth.sessions.values()) {
292
+ if (session.sessionId === sessionId || session.sessionAuthToken === token) {
293
+ closeSession(auth, session);
294
+ }
295
+ }
296
+ if (isLegacyFidelity(config)) {
297
+ sendJson(res, HTTP_STATUS.OK, buildLogoutAckBody(config), logoutCookies(cookieOptions));
298
+ return;
299
+ }
300
+ sendJson(res, HTTP_STATUS.OK, withSourceRef(buildLogoutAckBody(config), body), cookieOptions ? logoutCookies(cookieOptions) : []);
301
+ }
74
302
  return async function requestListener(req, res) {
75
303
  const pathname = (req.url ?? '').split('?')[0];
76
304
  try {
@@ -96,77 +324,24 @@ export function createHttpRequestListener(config, sessions, tokens = new Map())
96
324
  sendJson(res, HTTP_STATUS.OK, { IDPS: idps });
97
325
  return;
98
326
  }
99
- // Cookie-based silent login on app load — auto-authenticates as the
100
- // configured user when config.auth.httpAutoLogin is set, so the login
101
- // screen never appears (matches how a real session cookie would behave
102
- // once already logged in, but skips the manual login step entirely).
103
- // Two different call sites hit this path with different methods:
104
- // foundation-auth's fetch machine always POSTs (createFetchMachineEvent
105
- // hardcodes method: 'POST') on initial silent-login; foundation-comms'
106
- // sessionRefresh.ts's isAuthenticated() does a plain GET later, when
107
- // checking whether an expired session can be silently renewed.
327
+ // Silent login on app load. Two call sites hit this path with
328
+ // different methods: foundation-auth's fetch machine always POSTs
329
+ // (createFetchMachineEvent hardcodes method: 'POST') on initial
330
+ // silent-login; foundation-comms' sessionRefresh.ts's isAuthenticated()
331
+ // does a plain GET later, when checking whether an expired session can
332
+ // be silently renewed.
108
333
  if ((req.method === 'GET' || req.method === 'POST') &&
109
334
  pathname.endsWith('event-login-details')) {
110
- const autoLoginUsername = config.auth?.httpAutoLogin;
111
- const cookies = parseCookies(req.headers.cookie);
112
- const user = autoLoginUsername
113
- ? findUser(config, autoLoginUsername === true ? config.auth?.users?.[0]?.username : autoLoginUsername)
114
- : findUser(config, sessions.get(cookies[SESSION_COOKIE]));
115
- if (!user) {
116
- sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
117
- MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
118
- ERROR: [
119
- { CODE: 'NOT_LOGGED_ON', STATUS_CODE: '401 Unauthorized', TEXT: 'No active session' },
120
- ],
121
- });
122
- return;
123
- }
124
- const sessionId = ensureSession(sessions, cookies[SESSION_COOKIE], user.username);
125
- setSessionCookie(res, sessionId);
126
- const ack = buildLoginAckBody(user, config, 'EVENT_LOGIN_DETAILS_ACK');
127
- registerAckTokens(ack, user.username, tokens);
128
- sendJson(res, HTTP_STATUS.OK, ack);
335
+ const request = req.method === 'POST' ? await readJsonBody(req) : {};
336
+ handleLoginDetails(req, res, request);
129
337
  return;
130
338
  }
131
339
  if (req.method === 'POST' && pathname.endsWith('event-login-auth')) {
132
- const body = await readJsonBody(req);
133
- const details = body.DETAILS ?? {};
134
- const cookies = parseCookies(req.headers.cookie);
135
- // Empty DETAILS means a session-refresh ping (foundation-comms'
136
- // sessionRefresh.performRefresh), not a fresh credentials login —
137
- // honor it only if the request already carries a known session.
138
- const user = details.USER_NAME !== undefined
139
- ? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
140
- : findUser(config, sessions.get(cookies[SESSION_COOKIE]));
141
- if (!user) {
142
- sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
143
- MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
144
- ERROR: [
145
- {
146
- CODE: 'INCORRECT_CREDENTIALS',
147
- STATUS_CODE: '401 Unauthorized',
148
- TEXT: 'Problem logging in',
149
- },
150
- ],
151
- WARNING: [],
152
- });
153
- return;
154
- }
155
- const sessionId = ensureSession(sessions, cookies[SESSION_COOKIE], user.username);
156
- setSessionCookie(res, sessionId);
157
- const ack = buildLoginAckBody(user, config);
158
- registerAckTokens(ack, user.username, tokens);
159
- sendJson(res, HTTP_STATUS.OK, ack);
340
+ await handleLoginAuth(req, res);
160
341
  return;
161
342
  }
162
343
  if (req.method === 'POST' && pathname.endsWith('event-logout')) {
163
- const cookies = parseCookies(req.headers.cookie);
164
- const sessionId = cookies[SESSION_COOKIE];
165
- const username = sessions.get(sessionId);
166
- sessions.delete(sessionId);
167
- if (username !== undefined)
168
- revokeTokensFor(tokens, username);
169
- sendJson(res, HTTP_STATUS.OK, { MESSAGE_TYPE: 'LOGOUT_ACK' });
344
+ await handleLogout(req, res);
170
345
  return;
171
346
  }
172
347
  res.writeHead(HTTP_STATUS.NOT_FOUND).end();
package/dist/index.d.ts CHANGED
@@ -4,4 +4,4 @@ export { Store } from './db/store.ts';
4
4
  export { RECORD_FIELDS, RECORD_ID, TIMESTAMP } from './db/identity.ts';
5
5
  export { ErrorCode, NackError, statusCodeFor, type ErrorCodeName, type GenesisErrorType, type NackErrorEntry, type NackErrorInput, type NackErrorOptions, } from './protocol/errors.ts';
6
6
  export { compileCriteria, type CriteriaOptions, filterByCriteria, type Predicate, } from './db/criteria.ts';
7
- export type { AntiJoinDef, AuthConfig, AuthUser, BroadcastFn, BroadcastTableChangeFn, CrudEventVerb, EventHandler, EventHandlerCtx, EventHandlerResult, EventSchemaOverride, FidelityMode, FieldDef, FieldMetadata, GeneratedFieldDef, GenesisFieldType, GenesisMessage, HttpRouteDef, IndexDef, JoinDef, JoinFieldLink, JoinLink, JoinType, JoinValueLink, LiveModifyMode, MockServerConfig, OnMessageCtx, OnMessageHook, QueryDef, RequestingUser, RequestReplyDef, RequestReplyResolverCtx, ResourceAuthDef, ResourceItem, Row, SequenceFormat, SocketLike, SsoIdentityProvider, TableDef, ViewDef, ViewRowSources, } from './types.ts';
7
+ export type { AntiJoinDef, AuthConfig, AuthUser, BroadcastFn, BroadcastTableChangeFn, CookieAuthenticationOptions, CrudEventVerb, EventHandler, EventHandlerCtx, EventHandlerResult, EventSchemaOverride, FidelityMode, FieldDef, FieldMetadata, GeneratedFieldDef, GenesisFieldType, GenesisMessage, HttpRouteDef, IndexDef, JoinDef, JoinFieldLink, JoinLink, JoinType, JoinValueLink, LiveModifyMode, MockServerConfig, OnMessageCtx, OnMessageHook, ProductDetails, QueryDef, RequestingUser, RequestReplyDef, RequestReplyResolverCtx, ResourceAuthDef, ResourceItem, Row, SequenceFormat, SocketLike, SsoIdentityProvider, TableDef, ViewDef, ViewRowSources, } from './types.ts';
@@ -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: