@genesislcap/mock-server 15.73.0 → 15.75.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 (100) hide show
  1. package/README.md +296 -58
  2. package/dist/db/schema.d.ts +9 -1
  3. package/dist/db/schema.js +40 -11
  4. package/dist/db/store.d.ts +1 -0
  5. package/dist/db/store.js +4 -0
  6. package/dist/handlers/auth.d.ts +15 -6
  7. package/dist/handlers/auth.js +152 -33
  8. package/dist/handlers/commitEvent.js +43 -20
  9. package/dist/handlers/crudEvents.d.ts +3 -1
  10. package/dist/handlers/crudEvents.js +3 -2
  11. package/dist/handlers/eventValidation.js +6 -3
  12. package/dist/handlers/http.d.ts +2 -2
  13. package/dist/handlers/http.js +66 -43
  14. package/dist/handlers/jsonSchema.d.ts +1 -0
  15. package/dist/handlers/jsonSchema.js +72 -21
  16. package/dist/handlers/meta.d.ts +1 -1
  17. package/dist/handlers/meta.js +59 -10
  18. package/dist/handlers/requestReply.js +36 -9
  19. package/dist/index.d.ts +1 -1
  20. package/dist/presets/auth.d.ts +25 -0
  21. package/dist/presets/auth.js +855 -0
  22. package/dist/presets/cronExpression.d.ts +1 -0
  23. package/dist/presets/cronExpression.js +429 -0
  24. package/dist/presets/fileServer.d.ts +13 -0
  25. package/dist/presets/fileServer.js +399 -0
  26. package/dist/presets/gsf.d.ts +24 -0
  27. package/dist/presets/gsf.js +450 -0
  28. package/dist/presets/index.d.ts +1 -0
  29. package/dist/presets/index.js +1 -0
  30. package/dist/presets/javaTime.d.ts +7 -0
  31. package/dist/presets/javaTime.js +322 -0
  32. package/dist/presets/multipart.d.ts +14 -0
  33. package/dist/presets/multipart.js +91 -0
  34. package/dist/presets/notify.d.ts +27 -0
  35. package/dist/presets/notify.js +250 -0
  36. package/dist/presets/notifyDispatch.d.ts +28 -0
  37. package/dist/presets/notifyDispatch.js +570 -0
  38. package/dist/presets/notifyRules.d.ts +9 -0
  39. package/dist/presets/notifyRules.js +754 -0
  40. package/dist/presets/platform/backing.json +8058 -217
  41. package/dist/presets/platform/criteria-model.json +362 -0
  42. package/dist/presets/platform/time-zones.json +608 -0
  43. package/dist/presets/platform.d.ts +7 -0
  44. package/dist/presets/platform.js +145 -103
  45. package/dist/presets/products.d.ts +9 -7
  46. package/dist/presets/products.js +89 -21
  47. package/dist/presets/reconciliation.d.ts +18 -0
  48. package/dist/presets/reconciliation.js +721 -0
  49. package/dist/presets/reporting.d.ts +14 -0
  50. package/dist/presets/reporting.js +862 -0
  51. package/dist/protocol/connection.d.ts +2 -0
  52. package/dist/protocol/connection.js +4 -0
  53. package/dist/protocol/dtoTypes.d.ts +30 -0
  54. package/dist/protocol/dtoTypes.js +250 -0
  55. package/dist/protocol/errors.d.ts +3 -1
  56. package/dist/protocol/errors.js +2 -0
  57. package/dist/protocol/fieldTypes.js +5 -0
  58. package/dist/protocol/router.d.ts +1 -0
  59. package/dist/protocol/router.js +3 -3
  60. package/dist/protocol/schemaValidation.d.ts +1 -1
  61. package/dist/protocol/schemaValidation.js +53 -8
  62. package/dist/server.js +34 -2
  63. package/dist/types.d.ts +50 -2
  64. package/package.json +1 -1
  65. package/src/db/schema.ts +56 -13
  66. package/src/db/store.ts +5 -0
  67. package/src/handlers/auth.ts +211 -37
  68. package/src/handlers/commitEvent.ts +44 -19
  69. package/src/handlers/crudEvents.ts +9 -2
  70. package/src/handlers/eventValidation.ts +6 -3
  71. package/src/handlers/http.ts +83 -42
  72. package/src/handlers/jsonSchema.ts +86 -23
  73. package/src/handlers/meta.ts +77 -9
  74. package/src/handlers/requestReply.ts +42 -6
  75. package/src/index.ts +7 -0
  76. package/src/presets/auth.ts +961 -0
  77. package/src/presets/cronExpression.ts +445 -0
  78. package/src/presets/fileServer.ts +475 -0
  79. package/src/presets/gsf.ts +475 -0
  80. package/src/presets/index.ts +5 -0
  81. package/src/presets/javaTime.ts +354 -0
  82. package/src/presets/multipart.ts +110 -0
  83. package/src/presets/notify.ts +312 -0
  84. package/src/presets/notifyDispatch.ts +685 -0
  85. package/src/presets/notifyRules.ts +866 -0
  86. package/src/presets/platform/backing.json +8058 -217
  87. package/src/presets/platform/criteria-model.json +362 -0
  88. package/src/presets/platform/time-zones.json +608 -0
  89. package/src/presets/platform.ts +204 -115
  90. package/src/presets/products.ts +125 -19
  91. package/src/presets/reconciliation.ts +824 -0
  92. package/src/presets/reporting.ts +953 -0
  93. package/src/protocol/connection.ts +4 -0
  94. package/src/protocol/dtoTypes.ts +310 -0
  95. package/src/protocol/errors.ts +13 -1
  96. package/src/protocol/fieldTypes.ts +5 -0
  97. package/src/protocol/router.ts +3 -3
  98. package/src/protocol/schemaValidation.ts +61 -8
  99. package/src/server.ts +38 -2
  100. package/src/types.ts +147 -3
@@ -1,5 +1,6 @@
1
+ import type { Store } from '../db/store.ts';
1
2
  import type { Connection } from '../protocol/connection.ts';
2
- import type { AuthUser, GenesisMessage, MockServerConfig, Row } from '../types.ts';
3
+ import type { AuthUser, BroadcastTableChangeFn, GenesisMessage, LoginCtx, LoginFailure, MockServerConfig, Row } from '../types.ts';
3
4
  export type TokenRegistry = Map<string, string>;
4
5
  export interface AuthSession {
5
6
  username: string;
@@ -21,9 +22,17 @@ export declare function sessionTimeoutMins(config: MockServerConfig): number;
21
22
  export declare function refreshTokenExpirationMins(config: MockServerConfig): number;
22
23
  export declare function javaDateString(date: Date): string;
23
24
  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 buildLoginNackBody(config: MockServerConfig, transport: 'ws' | 'http', failure?: LoginError): Row;
25
26
  export declare function buildLogoutAckBody(config: MockServerConfig): Row;
26
- export declare function findUser(config: MockServerConfig, username?: string): AuthUser | undefined;
27
- export declare function findUserByCredentials(config: MockServerConfig, username?: string, password?: string): AuthUser | undefined;
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;
27
+ export declare function findUser(config: MockServerConfig, store: Store, username?: string): AuthUser | undefined;
28
+ export type LoginKind = 'credentials' | 'refresh' | 'none';
29
+ export declare function loginKind(config: MockServerConfig, details: Row, refreshToken: unknown): LoginKind;
30
+ export declare function credentialsLogin(config: MockServerConfig, store: Store, details: Row, ctx: LoginCtx): AuthUser | LoginFailure;
31
+ export declare function unclaimedLogin(config: MockServerConfig, details: Row, ctx: LoginCtx): LoginFailure;
32
+ export declare function refreshLogin(config: MockServerConfig, store: Store, username: string | undefined, ctx: LoginCtx): AuthUser | LoginFailure;
33
+ export type LoginError = LoginFailure | 'INTERNAL_ERROR';
34
+ export declare function attemptLogin(run: () => AuthUser | LoginFailure): AuthUser | LoginError;
35
+ export declare function recordLogout(config: MockServerConfig, auth: AuthState, username: string, ctx: LoginCtx): void;
36
+ export declare function routerHostname(header: unknown, address: string | undefined): string;
37
+ export declare function handleLogin(message: GenesisMessage, connection: Connection, config: MockServerConfig, auth: AuthState, store: Store, broadcastTableChange: BroadcastTableChangeFn): void;
38
+ export declare function handleLogout(message: GenesisMessage, connection: Connection, config: MockServerConfig, auth: AuthState, store: Store, broadcastTableChange: BroadcastTableChangeFn): void;
@@ -164,11 +164,21 @@ function buildLegacyLoginAckBody(user, session, config, messageType) {
164
164
  PROFILE: user.profile ?? [],
165
165
  };
166
166
  }
167
+ // The status each login failure answers with (AuthFailure$WhenMappings).
168
+ const LOGIN_FAILURE_STATUS = {
169
+ INCORRECT_CREDENTIALS: '401 Unauthorized',
170
+ UNKNOWN_ACCOUNT: '401 Unauthorized',
171
+ PASSWORD_EXPIRED: '403 Forbidden',
172
+ LOCKED_ACCOUNT: '403 Forbidden',
173
+ MAX_TRIES_REACHED: '429 Too Many Requests',
174
+ NO_COMPATIBLE_PROVIDERS: '400 Bad Request',
175
+ INTERNAL_ERROR: '500 Internal Server Error',
176
+ };
167
177
  // 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) {
178
+ // with the "Problem logging in" text whatever the failure, an unknown user
179
+ // and a wrong password alike (LoginProcessor.kt:160-161,330). Over HTTP it is
180
+ // a 200 (http-login-failed.json).
181
+ export function buildLoginNackBody(config, transport, failure = 'INCORRECT_CREDENTIALS') {
172
182
  if (isLegacyFidelity(config)) {
173
183
  return {
174
184
  MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
@@ -192,9 +202,9 @@ export function buildLoginNackBody(config, transport) {
192
202
  ERROR: [
193
203
  {
194
204
  '@type': 'LoginError',
195
- CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
205
+ CODE: failure,
196
206
  TEXT: 'Problem logging in',
197
- STATUS_CODE: '401 Unauthorized',
207
+ STATUS_CODE: LOGIN_FAILURE_STATUS[failure],
198
208
  DETAILS: null,
199
209
  },
200
210
  ],
@@ -213,39 +223,145 @@ export function buildLogoutAckBody(config) {
213
223
  }
214
224
  // Trusted lookup by username alone — for paths where identity is already
215
225
  // established (a token this server issued, an HTTP session cookie,
216
- // httpAutoLogin). NEVER use this for a credentials login.
217
- export function findUser(config, username) {
226
+ // httpAutoLogin): the directory's user when the config has one, else a
227
+ // configured one. NEVER use this for a credentials login.
228
+ export function findUser(config, store, username) {
218
229
  if (username === undefined)
219
230
  return undefined;
231
+ const directory = config.auth?.directory;
232
+ if (directory)
233
+ return directory.user(username, store);
220
234
  return (config.auth?.users ?? []).find((u) => u.username === username);
221
235
  }
222
- // Credentials login: the supplied password must match the configured one. A
223
- // missing PASSWORD is a failed login, never a username-only lookup — treating
224
- // it as one lets any client authenticate as any configured user just by
225
- // omitting the field, defeating auth.requireAuth and every rowFilter/
226
- // hideFields rule built on the logged-in identity.
227
- export function findUserByCredentials(config, username, password) {
228
- const user = findUser(config, username);
229
- return user && user.password === password ? user : undefined;
236
+ // A status auth asks a new password for (UserStatus).
237
+ const needsNewPassword = (status) => status === 'PASSWORD_EXPIRED' || status === 'PASSWORD_RESET';
238
+ const statusLetsIn = (status) => status === undefined || status === 'ENABLED';
239
+ export function loginKind(config, details, refreshToken) {
240
+ if (isLegacyFidelity(config))
241
+ return details.USER_NAME === undefined ? 'refresh' : 'credentials';
242
+ const given = (value) => value !== undefined && value !== null;
243
+ if (!given(details.PASSWORD) && given(refreshToken))
244
+ return 'refresh';
245
+ return given(details.USER_NAME) && given(details.PASSWORD) ? 'credentials' : 'none';
246
+ }
247
+ // A credentials login: the directory's when the config has one, else checked
248
+ // against the configured users in auth's order (GenesisDbAuthenticator, auth
249
+ // v8.15.5): an unknown or DISABLED user fails as a wrong password does, a
250
+ // status that asks for a new password answers PASSWORD_EXPIRED, both before
251
+ // the password is looked at, and a right password with any other status but
252
+ // ENABLED LOCKED_ACCOUNT. fidelity: 'legacy' compares the password as 15.47
253
+ // did, so a user configured without one logs in by sending none.
254
+ export function credentialsLogin(config, store, details, ctx) {
255
+ const username = String(details.USER_NAME);
256
+ const directory = config.auth?.directory;
257
+ if (directory) {
258
+ const password = details.PASSWORD === undefined || details.PASSWORD === null
259
+ ? undefined
260
+ : String(details.PASSWORD);
261
+ return directory.login(username, password, ctx);
262
+ }
263
+ const user = findUser(config, store, username);
264
+ if (!user || user.status === 'DISABLED')
265
+ return 'INCORRECT_CREDENTIALS';
266
+ if (needsNewPassword(user.status))
267
+ return 'PASSWORD_EXPIRED';
268
+ const password = isLegacyFidelity(config) ? details.PASSWORD : String(details.PASSWORD);
269
+ if (user.password !== password)
270
+ return 'INCORRECT_CREDENTIALS';
271
+ return statusLetsIn(user.status) ? user : 'LOCKED_ACCOUNT';
272
+ }
273
+ // A login no authenticator takes: the directory records it (it is asked with
274
+ // no password), and it fails whatever the directory answers.
275
+ export function unclaimedLogin(config, details, ctx) {
276
+ const directory = config.auth?.directory;
277
+ const username = typeof details.USER_NAME === 'string' ? details.USER_NAME : '';
278
+ const answer = directory?.login(username, undefined, ctx);
279
+ return typeof answer === 'string' ? answer : 'NO_COMPATIBLE_PROVIDERS';
280
+ }
281
+ // A refresh-token login (RefreshTokenAuthenticator) as the user the token's
282
+ // session belongs to (undefined: none has it), refused when their status no
283
+ // longer lets them in.
284
+ export function refreshLogin(config, store, username, ctx) {
285
+ const directory = config.auth?.directory;
286
+ if (directory)
287
+ return directory.refresh(username, ctx);
288
+ const user = findUser(config, store, username);
289
+ if (!user)
290
+ return isLegacyFidelity(config) ? 'INCORRECT_CREDENTIALS' : 'UNKNOWN_ACCOUNT';
291
+ if (needsNewPassword(user.status))
292
+ return 'PASSWORD_EXPIRED';
293
+ return statusLetsIn(user.status) ? user : 'LOCKED_ACCOUNT';
230
294
  }
231
- export function handleLogin(message, connection, config, auth) {
295
+ export function attemptLogin(run) {
296
+ try {
297
+ const answer = run();
298
+ if (typeof answer === 'string' && answer in LOGIN_FAILURE_STATUS)
299
+ return answer;
300
+ if (typeof answer === 'object' && answer !== null)
301
+ return answer;
302
+ console.error('[mock-server] A login answered with neither a user nor a reason:', answer);
303
+ }
304
+ catch (error) {
305
+ console.error('[mock-server] Error during a login:', error);
306
+ }
307
+ return 'INTERNAL_ERROR';
308
+ }
309
+ // Tells the directory a session of `username`'s has logged out.
310
+ export function recordLogout(config, auth, username, ctx) {
311
+ const online = [...auth.sessions.values()].some((session) => session.username === username);
312
+ config.auth?.directory?.logout(username, online, ctx);
313
+ }
314
+ // DETAILS.HOSTNAME as GSF's router sets it on a login or logout
315
+ // (MsgCreator.kt:59-66 @v8.15.29): the HOSTNAME header, else the socket's
316
+ // address as Java prints it, up to its first ':' ("/127.0.0.1"; an IPv6 one
317
+ // keeps "/[" and its first group).
318
+ export function routerHostname(header, address) {
319
+ if (typeof header === 'string' && header !== '')
320
+ return header;
321
+ const ip = (address ?? '').replace(/^::ffff:(?=\d+\.)/, '');
322
+ if (!ip.includes(':'))
323
+ return `/${ip}`;
324
+ return `/[${ip.startsWith(':') ? '0' : ip.split(':')[0]}`;
325
+ }
326
+ // What a login over the socket runs with.
327
+ function socketLoginCtx(message, connection, store, broadcastTableChange) {
328
+ return {
329
+ store,
330
+ broadcastTableChange,
331
+ hostname: routerHostname(connection.hostnameHeader ?? message.HOSTNAME, connection.remoteAddress),
332
+ messageUser: typeof message.USER_NAME === 'string' ? message.USER_NAME : null,
333
+ };
334
+ }
335
+ export function handleLogin(message, connection, config, auth, store, broadcastTableChange) {
232
336
  const details = message.DETAILS ?? {};
233
- // Two login shapes share EVENT_LOGIN_AUTH: credentials ({USER_NAME,
234
- // PASSWORD}) and token refresh — foundation-comms' createRefreshTokenMessage
235
- // sends only DETAILS.REFRESH_AUTH_TOKEN (plus the stored SESSION_AUTH_TOKEN
236
- // at the top level), no username at all.
237
- const tokenUsername = details.USER_NAME === undefined
238
- ? (auth.tokens.get(details.REFRESH_AUTH_TOKEN) ??
239
- auth.tokens.get(details.SESSION_AUTH_TOKEN) ??
240
- auth.tokens.get(message.SESSION_AUTH_TOKEN))
241
- : undefined;
242
- const user = details.USER_NAME !== undefined
243
- ? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
244
- : findUser(config, tokenUsername);
245
- if (!user) {
246
- connection.reply(message, buildLoginNackBody(config, 'ws'));
337
+ const ctx = socketLoginCtx(message, connection, store, broadcastTableChange);
338
+ // The session a refresh logs out: RefreshTokenAuthenticator deletes the
339
+ // USER_SESSION whose token it used. Under fidelity: 'legacy' the old
340
+ // session stays, as up to 15.47.
341
+ let replaced;
342
+ const user = attemptLogin(() => {
343
+ const kind = loginKind(config, details, details.REFRESH_AUTH_TOKEN);
344
+ if (kind === 'credentials')
345
+ return credentialsLogin(config, store, details, ctx);
346
+ if (kind === 'none')
347
+ return unclaimedLogin(config, details, ctx);
348
+ if (isLegacyFidelity(config)) {
349
+ // foundation-comms' createRefreshTokenMessage sends the refresh token
350
+ // in DETAILS and the stored SESSION_AUTH_TOKEN at the top level.
351
+ const username = auth.tokens.get(details.REFRESH_AUTH_TOKEN) ??
352
+ auth.tokens.get(details.SESSION_AUTH_TOKEN) ??
353
+ auth.tokens.get(message.SESSION_AUTH_TOKEN);
354
+ return refreshLogin(config, store, username, ctx);
355
+ }
356
+ replaced = sessionByRefreshToken(auth, details.REFRESH_AUTH_TOKEN);
357
+ return refreshLogin(config, store, replaced?.username, ctx);
358
+ });
359
+ if (typeof user === 'string') {
360
+ connection.reply(message, buildLoginNackBody(config, 'ws', user));
247
361
  return;
248
362
  }
363
+ if (replaced)
364
+ closeSession(auth, replaced);
249
365
  const session = openSession(auth, user);
250
366
  connection.authenticated = true;
251
367
  connection.userName = user.username;
@@ -256,12 +372,15 @@ export function handleLogin(message, connection, config, auth) {
256
372
  connection.sessionId = session.sessionId;
257
373
  connection.reply(message, buildLoginAckBody(user, session, config, auth));
258
374
  }
259
- export function handleLogout(message, connection, config, auth) {
375
+ export function handleLogout(message, connection, config, auth, store, broadcastTableChange) {
260
376
  const session = connection.sessionAuthToken === undefined
261
377
  ? undefined
262
378
  : auth.sessions.get(connection.sessionAuthToken);
263
- if (session)
379
+ if (session) {
264
380
  closeSession(auth, session);
381
+ const ctx = socketLoginCtx(message, connection, store, broadcastTableChange);
382
+ recordLogout(config, auth, session.username, ctx);
383
+ }
265
384
  for (const token of [connection.sessionAuthToken, connection.refreshAuthToken]) {
266
385
  if (token !== undefined)
267
386
  auth.tokens.delete(token);
@@ -12,42 +12,62 @@ function resolveEventHandler(eventName, config) {
12
12
  crudEventHandler(eventName, config) ??
13
13
  config.defaultEventHandler);
14
14
  }
15
+ // Runs each callback; one that fails is logged, and the rest still run.
16
+ function runAll(callbacks, what) {
17
+ for (const callback of callbacks.splice(0)) {
18
+ try {
19
+ callback();
20
+ }
21
+ catch (error) {
22
+ console.error(`[mock-server] Error ${what}:`, error);
23
+ }
24
+ }
25
+ }
15
26
  function openTransaction(store, ctx, audit) {
16
27
  const pending = [];
17
- let open = true;
28
+ const committed = [];
29
+ // open: the handler runs; committed: its writes kept, its pushes waiting
30
+ // for flush(); over: flushed or rolled back.
31
+ let state = 'open';
32
+ let rolledBack = false;
18
33
  store.begin(audit);
19
34
  const hold = (push) => {
20
- if (open)
21
- pending.push(push);
22
- else
35
+ if (state === 'over')
23
36
  push();
37
+ else
38
+ pending.push(push);
24
39
  };
25
40
  return {
26
41
  broadcast: (resourceName, operation, row) => hold(() => ctx.broadcast(resourceName, operation, row)),
27
42
  broadcastTableChange: (tableName, operation, pk) => hold(() => ctx.broadcastTableChange(tableName, operation, pk)),
43
+ // Asked for once the handler is done (from a callback, or kept for
44
+ // later): at once when the event committed, never when it rolled back.
45
+ afterCommit: (callback) => {
46
+ if (state === 'open')
47
+ committed.push(callback);
48
+ else if (!rolledBack)
49
+ runAll([callback], 'after a commit');
50
+ },
28
51
  commit() {
29
52
  // The audit rows the writes added go live with them.
30
53
  for (const { tableName, key } of store.takeAuditWrites()) {
31
54
  pending.push(() => ctx.broadcastTableChange(tableName, 'INSERT', key));
32
55
  }
33
- open = false;
34
56
  store.commit();
57
+ state = 'committed';
58
+ runAll(committed, 'after a commit');
35
59
  },
36
60
  flush() {
37
- for (const push of pending.splice(0)) {
38
- try {
39
- push();
40
- }
41
- catch (error) {
42
- console.error('[mock-server] Error pushing a committed change:', error);
43
- }
44
- }
61
+ state = 'over';
62
+ runAll(pending, 'pushing a committed change');
45
63
  },
46
64
  rollback() {
47
- if (!open)
65
+ if (state !== 'open')
48
66
  return;
49
- open = false;
67
+ state = 'over';
68
+ rolledBack = true;
50
69
  pending.length = 0;
70
+ committed.length = 0;
51
71
  store.rollback();
52
72
  },
53
73
  };
@@ -141,10 +161,12 @@ export function handleCommitEvent(message, connection, config, store, ctx) {
141
161
  connection,
142
162
  store,
143
163
  message,
164
+ config,
144
165
  broadcast: transaction?.broadcast ?? ctx.broadcast,
145
166
  broadcastTableChange: transaction?.broadcastTableChange ?? ctx.broadcastTableChange,
146
167
  validate,
147
168
  ignoreWarnings,
169
+ afterCommit: transaction?.afterCommit ?? ((callback) => callback()),
148
170
  }) ?? {};
149
171
  if (result.warnings?.length && (validate || !ignoreWarnings)) {
150
172
  transaction?.rollback();
@@ -155,15 +177,16 @@ export function handleCommitEvent(message, connection, config, store, ctx) {
155
177
  return;
156
178
  }
157
179
  const generated = validate && !legacy ? [] : (result.generated ?? []);
158
- // A GENERATED that can't go on the wire (a BigInt, a cycle) fails the
159
- // event here, before anything is committed.
160
- JSON.stringify(generated);
180
+ const reply = result.reply ?? { MESSAGE_TYPE: MESSAGE_TYPE.EVENT_ACK, GENERATED: generated };
181
+ // A reply that can't go on the wire (a BigInt, a cycle) fails the event
182
+ // here, before anything is committed.
183
+ JSON.stringify(reply);
161
184
  if (validate)
162
185
  transaction?.rollback();
163
186
  else
164
187
  transaction?.commit();
165
188
  try {
166
- connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.EVENT_ACK, GENERATED: generated });
189
+ connection.reply(message, reply);
167
190
  }
168
191
  finally {
169
192
  transaction?.flush();
@@ -172,7 +195,7 @@ export function handleCommitEvent(message, connection, config, store, ctx) {
172
195
  catch (error) {
173
196
  transaction?.rollback();
174
197
  connection.reply(message, {
175
- MESSAGE_TYPE: MESSAGE_TYPE.EVENT_NACK,
198
+ MESSAGE_TYPE: (error instanceof NackError && error.messageType) || MESSAGE_TYPE.EVENT_NACK,
176
199
  ...nackPayload(error, legacy),
177
200
  });
178
201
  }
@@ -1,2 +1,4 @@
1
- import type { EventHandler, MockServerConfig } from '../types.ts';
1
+ import type { Store } from '../db/store.ts';
2
+ import type { EventHandler, MockServerConfig, Row, TableDef } from '../types.ts';
3
+ export declare function checkUnique(table: string, def: TableDef, row: Row, store: Store, self?: string): void;
2
4
  export declare function crudEventHandler(eventName: string, config: MockServerConfig): EventHandler | undefined;
@@ -24,8 +24,9 @@ function indexValueText(fields, row) {
24
24
  }
25
25
  // The database's unique constraints: the primary key (unless `self` is the
26
26
  // record being modified, whose key can't change) and every other unique
27
- // index. A null in an index's fields never clashes, as in SQL.
28
- function checkUnique(table, def, row, store, self) {
27
+ // index. A null in an index's fields never clashes, as in SQL. A clash is
28
+ // entityDb's DUPLICATE_KEY.
29
+ export function checkUnique(table, def, row, store, self) {
29
30
  const pkFields = pkFieldsOf(def);
30
31
  if (self === undefined && pkFields.every((field) => !isMissing(row[field]))) {
31
32
  if (store.getRow(table, store.rowKey(table, row))) {
@@ -1,5 +1,6 @@
1
1
  import { eventFields, isDeclared, resolveEventTarget } from "../db/schema.js";
2
2
  import { eventValue } from "../db/values.js";
3
+ import { decodedValue } from "../protocol/dtoTypes.js";
3
4
  import { schemaFieldErrors, validateSchema } from "../protocol/schemaValidation.js";
4
5
  import { eventInboundSchema } from "./jsonSchema.js";
5
6
  // The schema check every event goes through on the real server before its
@@ -35,8 +36,10 @@ function declaredEvent(name, config, store) {
35
36
  }
36
37
  // DETAILS as the handler gets them, after the schema check: a declared
37
38
  // BigDecimal field's string is a number, as GSF hands its handler a
38
- // deserialized BigDecimal (db/values.ts eventValue). Anything else, and any
39
- // undeclared event's DETAILS, as sent.
39
+ // deserialized BigDecimal (db/values.ts eventValue), and a nested class
40
+ // loses the keys it doesn't declare, which its schema lets through
41
+ // (protocol/dtoTypes.ts decodedValue). Anything else, and any undeclared
42
+ // event's DETAILS, as sent.
40
43
  export function eventDetails(message, config, store) {
41
44
  const details = message.DETAILS ?? {};
42
45
  const declared = declaredEvent(message.MESSAGE_TYPE, config, store);
@@ -46,7 +49,7 @@ export function eventDetails(message, config, store) {
46
49
  for (const field of declared.fields) {
47
50
  if (!Object.hasOwn(details, field.name))
48
51
  continue;
49
- const value = eventValue(field, details[field.name]);
52
+ const value = eventValue(field, decodedValue(field, details[field.name]));
50
53
  if (value === details[field.name])
51
54
  continue;
52
55
  converted ??= { ...details };
@@ -1,7 +1,7 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
- import type { CookieAuthenticationOptions, MockServerConfig } from '../types.ts';
2
+ import type { CookieAuthenticationOptions, HttpRouteCtx, MockServerConfig } from '../types.ts';
3
3
  import { type AuthState } from './auth.ts';
4
4
  export declare const SESSION_AUTH_TOKEN_COOKIE = "sessionAuthToken";
5
5
  export declare function cookieAuthentication(config: MockServerConfig): CookieAuthenticationOptions | undefined;
6
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>;
7
+ export declare function createHttpRequestListener(config: MockServerConfig, legacySessions: Map<string, string>, auth: AuthState, routeCtx: Omit<HttpRouteCtx, 'userName'>): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
@@ -2,7 +2,7 @@ import crypto from 'node:crypto';
2
2
  import { isLegacyFidelity } from "../protocol/fidelity.js";
3
3
  import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
4
4
  import { notLoggedInNack } from "../protocol/msgNack.js";
5
- import { buildLoginAckBody, buildLoginNackBody, buildLogoutAckBody, capRegistry, closeSession, createAuthState, findUser, findUserByCredentials, openSession, refreshTokenExpirationMins, sessionByRefreshToken, sessionTimeoutMins, } from "./auth.js";
5
+ import { attemptLogin, buildLoginAckBody, buildLoginNackBody, buildLogoutAckBody, capRegistry, closeSession, credentialsLogin, findUser, loginKind, openSession, recordLogout, refreshLogin, refreshTokenExpirationMins, routerHostname, sessionByRefreshToken, sessionTimeoutMins, unclaimedLogin, } from "./auth.js";
6
6
  // fidelity: 'legacy' without cookieAuthentication: the mock's own session
7
7
  // cookie, sessionId -> username.
8
8
  const LEGACY_SESSION_COOKIE = 'MOCK_SESSION_ID';
@@ -136,11 +136,11 @@ function headerValue(req, name) {
136
136
  const value = req.headers[name.toLowerCase()] ?? req.headers[name.toLowerCase().replaceAll('_', '-')];
137
137
  return typeof value === 'string' ? value : undefined;
138
138
  }
139
- function autoLoginUser(config) {
139
+ function autoLoginUser(config, store) {
140
140
  const autoLogin = config.auth?.httpAutoLogin;
141
141
  if (!autoLogin)
142
142
  return undefined;
143
- return findUser(config, autoLogin === true ? config.auth?.users?.[0]?.username : autoLogin);
143
+ return findUser(config, store, autoLogin === true ? config.auth?.users?.[0]?.username : autoLogin);
144
144
  }
145
145
  // Drops every token this server minted for `username` (fidelity: 'legacy',
146
146
  // whose logout ends all of the user's sessions).
@@ -168,19 +168,27 @@ function ensureLegacySession(legacySessions, cookieSessionId, username) {
168
168
  function legacySessionCookie(sessionId) {
169
169
  return `${LEGACY_SESSION_COOKIE}=${sessionId}; Path=/; SameSite=Lax`;
170
170
  }
171
- export function createHttpRequestListener(config, legacySessions, auth = createAuthState()) {
171
+ export function createHttpRequestListener(config, legacySessions, auth, routeCtx) {
172
+ const { store } = routeCtx;
173
+ // What a login or logout over HTTP runs with.
174
+ const loginCtx = (req, body) => ({
175
+ store,
176
+ broadcastTableChange: routeCtx.broadcastTableChange,
177
+ hostname: routerHostname(req.headers.hostname, req.socket.remoteAddress),
178
+ messageUser: typeof body.USER_NAME === 'string' ? body.USER_NAME : null,
179
+ });
172
180
  // Every HTTP reply carries a SOURCE_REF: the request's, or AUTO_<uuid> as
173
181
  // the router mints one (http-login.json). Not under fidelity: 'legacy'.
174
182
  const withSourceRef = (body, request = {}) => isLegacyFidelity(config)
175
183
  ? body
176
184
  : { ...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.
185
+ // The session a request names: the SESSION_AUTH_TOKEN header, which under
186
+ // cookieAuthentication the sessionAuthToken cookie overwrites when there is
187
+ // one (CookieHandler.kt:52-59 @v8.15.29). '' when the cookie is there but
188
+ // empty, as after a logout cleared it.
180
189
  function requestToken(req, cookies) {
181
- if (cookieAuthentication(config))
182
- return cookies[SESSION_AUTH_TOKEN_COOKIE];
183
- return headerValue(req, 'SESSION_AUTH_TOKEN');
190
+ const cookie = cookieAuthentication(config) ? cookies[SESSION_AUTH_TOKEN_COOKIE] : undefined;
191
+ return cookie ?? headerValue(req, 'SESSION_AUTH_TOKEN');
184
192
  }
185
193
  // The legacy-mode session cookie, or none.
186
194
  function legacyCookies(cookies, username) {
@@ -200,11 +208,11 @@ export function createHttpRequestListener(config, legacySessions, auth = createA
200
208
  function handleLoginDetails(req, res, request) {
201
209
  const cookies = parseCookies(req.headers.cookie);
202
210
  const legacyWithoutCookies = isLegacyFidelity(config) && !cookieAuthentication(config);
203
- const autoLogin = autoLoginUser(config);
211
+ const autoLogin = autoLoginUser(config, store);
204
212
  // fidelity: 'legacy' without cookieAuthentication: as up to 15.47, a new
205
213
  // session per call, found by the MOCK_SESSION_ID cookie.
206
214
  if (legacyWithoutCookies) {
207
- const user = autoLogin ?? findUser(config, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
215
+ const user = autoLogin ?? findUser(config, store, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
208
216
  if (!user) {
209
217
  sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
210
218
  MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
@@ -221,7 +229,7 @@ export function createHttpRequestListener(config, legacySessions, auth = createA
221
229
  }
222
230
  const token = requestToken(req, cookies);
223
231
  const session = token === undefined ? undefined : auth.sessions.get(token);
224
- const sessionUser = session && findUser(config, session.username);
232
+ const sessionUser = session && findUser(config, store, session.username);
225
233
  if (session && sessionUser) {
226
234
  const body = buildLoginAckBody(sessionUser, session, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
227
235
  sendJson(res, HTTP_STATUS.OK, withSourceRef(body, request));
@@ -241,30 +249,42 @@ export function createHttpRequestListener(config, legacySessions, auth = createA
241
249
  const details = body.DETAILS ?? {};
242
250
  const cookies = parseCookies(req.headers.cookie);
243
251
  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) {
252
+ // A refresh (foundation-comms' sessionRefresh performRefresh) names its
253
+ // token in the refreshAuthToken cookie under cookieAuthentication
254
+ // (CookieHandler.kt:62-67), else in DETAILS; under fidelity: 'legacy'
255
+ // without cookies, the MOCK_SESSION_ID session is the one refreshed.
256
+ const refreshToken = cookieOptions
257
+ ? cookies[REFRESH_AUTH_TOKEN_COOKIE]
258
+ : (details.REFRESH_AUTH_TOKEN ?? headerValue(req, 'REFRESH_AUTH_TOKEN'));
259
+ const ctx = loginCtx(req, body);
260
+ // The session a refresh logs out (RefreshTokenAuthenticator deletes the
261
+ // USER_SESSION whose token it used); fidelity: 'legacy' keeps it.
262
+ let replaced;
263
+ const user = attemptLogin(() => {
264
+ const kind = loginKind(config, details, refreshToken);
265
+ if (kind === 'credentials')
266
+ return credentialsLogin(config, store, details, ctx);
267
+ if (kind === 'none')
268
+ return unclaimedLogin(config, details, ctx);
269
+ if (isLegacyFidelity(config) && !cookieOptions) {
270
+ const username = legacySessions.get(cookies[LEGACY_SESSION_COOKIE]);
271
+ return findUser(config, store, username) ?? 'INCORRECT_CREDENTIALS';
272
+ }
273
+ const session = sessionByRefreshToken(auth, refreshToken);
274
+ if (!isLegacyFidelity(config))
275
+ replaced = session;
276
+ return refreshLogin(config, store, session?.username, ctx);
277
+ });
278
+ if (typeof user === 'string') {
262
279
  // GSF answers a failed login with HTTP 200; fidelity: 'legacy' with 401.
263
280
  const status = isLegacyFidelity(config) ? HTTP_STATUS.UNAUTHORIZED : HTTP_STATUS.OK;
264
281
  const nackCookies = cookieOptions ? loginNackCookies(cookieOptions) : [];
265
- sendJson(res, status, withSourceRef(buildLoginNackBody(config, 'http'), body), nackCookies);
282
+ const nack = buildLoginNackBody(config, 'http', user);
283
+ sendJson(res, status, withSourceRef(nack, body), nackCookies);
266
284
  return;
267
285
  }
286
+ if (replaced)
287
+ closeSession(auth, replaced);
268
288
  const session = openSession(auth, user);
269
289
  const ack = buildLoginAckBody(user, session, config, auth);
270
290
  sendJson(res, HTTP_STATUS.OK, withSourceRef(ack, body), sessionCookies(cookies, session));
@@ -283,16 +303,17 @@ export function createHttpRequestListener(config, legacySessions, auth = createA
283
303
  return;
284
304
  }
285
305
  // 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
- }
306
+ // under cookieAuthentication, CookieHandler.kt:76-81, else the request's
307
+ // own), else the token's.
308
+ const sessionId = (cookieOptions ? cookies[SESSION_ID_COOKIE] : undefined) ??
309
+ body.SESSION_ID ??
310
+ headerValue(req, 'SESSION_ID');
311
+ const token = requestToken(req, cookies);
312
+ const ended = [...auth.sessions.values()].filter((session) => session.sessionId === sessionId || session.sessionAuthToken === token);
313
+ for (const session of ended)
314
+ closeSession(auth, session);
315
+ for (const session of ended)
316
+ recordLogout(config, auth, session.username, loginCtx(req, body));
296
317
  if (isLegacyFidelity(config)) {
297
318
  sendJson(res, HTTP_STATUS.OK, buildLogoutAckBody(config), logoutCookies(cookieOptions));
298
319
  return;
@@ -310,7 +331,9 @@ export function createHttpRequestListener(config, legacySessions, auth = createA
310
331
  ? pathname.endsWith(candidate.path)
311
332
  : candidate.path.test(pathname)));
312
333
  if (route) {
313
- await route.handler(req, res);
334
+ const token = requestToken(req, parseCookies(req.headers.cookie));
335
+ const userName = token === undefined ? undefined : auth.sessions.get(token)?.username;
336
+ await route.handler(req, res, { ...routeCtx, ...(userName ? { userName } : {}) });
314
337
  return;
315
338
  }
316
339
  // foundation-auth's login screen fetches this whenever SSO is toggled
@@ -4,4 +4,5 @@ import type { Connection } from '../protocol/connection.ts';
4
4
  import type { GenesisMessage, MockServerConfig, Row } from '../types.ts';
5
5
  export { inferEventTable };
6
6
  export declare function eventInboundSchema(eventName: string, target: EventTarget, fields: ResolvedField[], appName: string | undefined): Row;
7
+ export declare function requestServerReplyProperties(name: string, config: MockServerConfig, store: Store): Row | undefined;
7
8
  export declare function handleJsonSchemaRequest(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store): void;