@genesislcap/mock-server 15.74.0 → 15.76.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
package/dist/types.d.ts CHANGED
@@ -11,7 +11,7 @@ export interface GenesisMessage {
11
11
  export type GenesisFieldType = 'STRING' | 'ENUM' | 'INT' | 'SHORT' | 'LONG' | 'DOUBLE' | 'BIGDECIMAL' | 'BOOLEAN' | 'DATE' | 'DATETIME' | 'NANO_TIMESTAMP' | 'RAW';
12
12
  export interface FieldDef {
13
13
  name: string;
14
- type: GenesisFieldType;
14
+ type: GenesisFieldType | NestedFieldType;
15
15
  nullable?: boolean;
16
16
  values?: string[];
17
17
  default?: unknown;
@@ -23,7 +23,15 @@ export interface FieldDef {
23
23
  description?: string;
24
24
  title?: string;
25
25
  optional?: boolean;
26
+ items?: FieldTypeDef;
27
+ unique?: boolean;
28
+ className?: string;
29
+ fields?: FieldDef[];
30
+ enumClass?: string;
31
+ dao?: boolean;
26
32
  }
33
+ export type NestedFieldType = 'ARRAY' | 'MAP' | 'OBJECT' | 'ANY';
34
+ export type FieldTypeDef = Omit<FieldDef, 'name'>;
27
35
  export interface GeneratedFieldDef {
28
36
  field: string;
29
37
  kind: 'SEQUENCE' | 'AUTO_INCREMENT';
@@ -106,6 +114,7 @@ export interface QueryDef {
106
114
  fieldTypes?: Record<string, string>;
107
115
  fields?: string[];
108
116
  indexes?: IndexDef[];
117
+ legacyEngine?: boolean;
109
118
  filter?: (row: Row) => boolean;
110
119
  auth?: ResourceAuthDef;
111
120
  }
@@ -114,6 +123,7 @@ export interface RequestReplyResolverCtx {
114
123
  message: GenesisMessage;
115
124
  user: RequestingUser;
116
125
  store: Store;
126
+ config: MockServerConfig;
117
127
  }
118
128
  export interface RequestReplyDef {
119
129
  source?: string;
@@ -126,6 +136,19 @@ export interface RequestReplyDef {
126
136
  requestFields?: string[];
127
137
  fields?: string[];
128
138
  rowLimit?: number;
139
+ order?: (a: Row, b: Row) => number;
140
+ typed?: TypedRequestReply;
141
+ }
142
+ export interface TypedRequestReply {
143
+ request: {
144
+ className: string;
145
+ fields: FieldDef[];
146
+ };
147
+ reply: {
148
+ className: string;
149
+ fields: FieldDef[];
150
+ };
151
+ meta?: Row;
129
152
  }
130
153
  export interface EventSchemaOverride {
131
154
  table?: string;
@@ -145,6 +168,20 @@ export interface AuthUser {
145
168
  permission?: string[];
146
169
  user?: Row;
147
170
  loginAck?: Row;
171
+ status?: string;
172
+ }
173
+ export interface AuthDirectory {
174
+ user(username: string, store: Store): AuthUser | undefined;
175
+ login(username: string, password: string | undefined, ctx: LoginCtx): AuthUser | LoginFailure;
176
+ refresh(username: string | undefined, ctx: LoginCtx): AuthUser | LoginFailure;
177
+ logout(username: string, online: boolean, ctx: LoginCtx): void;
178
+ }
179
+ export type LoginFailure = 'INCORRECT_CREDENTIALS' | 'PASSWORD_EXPIRED' | 'LOCKED_ACCOUNT' | 'MAX_TRIES_REACHED' | 'UNKNOWN_ACCOUNT' | 'NO_COMPATIBLE_PROVIDERS';
180
+ export interface LoginCtx {
181
+ store: Store;
182
+ broadcastTableChange: BroadcastTableChangeFn;
183
+ hostname: string;
184
+ messageUser: string | null;
148
185
  }
149
186
  export interface CookieAuthenticationOptions {
150
187
  httpOnly?: boolean;
@@ -166,6 +203,7 @@ export interface SsoIdentityProvider {
166
203
  }
167
204
  export interface AuthConfig {
168
205
  users?: AuthUser[];
206
+ directory?: AuthDirectory;
169
207
  ssoIdentityProviders?: SsoIdentityProvider[];
170
208
  heartbeatIntervalSecs?: number;
171
209
  sessionTimeoutMins?: number;
@@ -185,20 +223,30 @@ export interface EventHandlerCtx {
185
223
  connection: import('./protocol/connection.ts').Connection;
186
224
  store: Store;
187
225
  message: GenesisMessage;
226
+ config: MockServerConfig;
188
227
  broadcast: BroadcastFn;
189
228
  broadcastTableChange: BroadcastTableChangeFn;
190
229
  validate: boolean;
191
230
  ignoreWarnings: boolean;
231
+ afterCommit(callback: () => void): void;
192
232
  }
193
233
  export type EventHandlerResult = {
194
234
  generated?: Row[];
195
235
  warnings?: NackErrorInput[];
236
+ reply?: Row;
196
237
  } | void;
197
238
  export type EventHandler = (details: Row, ctx: EventHandlerCtx) => EventHandlerResult;
198
239
  export interface HttpRouteDef {
199
240
  method?: string;
200
241
  path: string | RegExp;
201
- handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
242
+ handler: (req: IncomingMessage, res: ServerResponse, ctx: HttpRouteCtx) => void | Promise<void>;
243
+ }
244
+ export interface HttpRouteCtx {
245
+ store: Store;
246
+ broadcast: BroadcastFn;
247
+ broadcastTableChange: BroadcastTableChangeFn;
248
+ userName?: string;
249
+ commitEvent(message: GenesisMessage, userName: string | undefined): Row;
202
250
  }
203
251
  export interface OnMessageCtx {
204
252
  connection: import('./protocol/connection.ts').Connection;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@genesislcap/mock-server",
3
- "version": "15.74.0",
3
+ "version": "15.76.0",
4
4
  "description": "Reusable in-memory Genesis WebSocket protocol mock server for client automation/CI, without a JVM or database.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
package/src/db/schema.ts CHANGED
@@ -9,6 +9,7 @@ import { daoClassOf, titleCase } from '../protocol/fieldTypes.ts';
9
9
  import type {
10
10
  CrudEventVerb,
11
11
  FieldDef,
12
+ FieldTypeDef,
12
13
  GenesisFieldType,
13
14
  IndexDef,
14
15
  MockServerConfig,
@@ -48,6 +49,15 @@ export interface ResolvedField {
48
49
  // The table the column comes from (for a view, the joined table for a
49
50
  // join's column), for generated enum class names.
50
51
  table?: string;
52
+ // A DTO field's nested parts (FieldDef.items, unique, className, fields,
53
+ // enumClass).
54
+ items?: FieldTypeDef;
55
+ unique?: boolean;
56
+ className?: string;
57
+ fields?: FieldDef[];
58
+ enumClass?: string;
59
+ // From a DAO a DTO unwraps (FieldDef.dao).
60
+ dao?: boolean;
51
61
  }
52
62
 
53
63
  export interface ResolvedSchema {
@@ -103,6 +113,12 @@ function fromFieldDef(
103
113
  ...(field.title !== undefined ? { title: field.title } : {}),
104
114
  ...(field.optional !== undefined ? { optional: field.optional } : {}),
105
115
  ...(table ? { table } : {}),
116
+ ...(field.items !== undefined ? { items: field.items } : {}),
117
+ ...(field.unique !== undefined ? { unique: field.unique } : {}),
118
+ ...(field.className !== undefined ? { className: field.className } : {}),
119
+ ...(field.fields !== undefined ? { fields: field.fields } : {}),
120
+ ...(field.enumClass !== undefined ? { enumClass: field.enumClass } : {}),
121
+ ...(field.dao ? { dao: true } : {}),
106
122
  };
107
123
  }
108
124
 
@@ -351,13 +367,24 @@ export function requestReplySchema(
351
367
  ): ResolvedSchema {
352
368
  const schema = requestReply.source
353
369
  ? resolveSourceSchema(requestReply.source, config, store)
354
- : {
355
- fields: inferredFields(requestReply.metadataRows ?? [], [], new Set(), undefined),
356
- declared: false,
357
- };
370
+ : { fields: resolverFields(requestReply, isLegacyFidelity(config)), declared: false };
358
371
  return withTypeOverrides(schema, requestReply.fieldTypes);
359
372
  }
360
373
 
374
+ // A resolver's fields: its metadataRows', then any fieldTypes name they
375
+ // don't have (typed by withTypeOverrides). fidelity: 'legacy' lists the
376
+ // metadataRows' alone, as 15.47 did.
377
+ function resolverFields(requestReply: RequestReplyDef, legacy: boolean): ResolvedField[] {
378
+ const fields = inferredFields(requestReply.metadataRows ?? [], [], new Set(), undefined);
379
+ if (legacy) return fields;
380
+ const named = new Set(fields.map((field) => field.name));
381
+ const declared = Object.keys(requestReply.fieldTypes ?? {}).filter((name) => !named.has(name));
382
+ return [
383
+ ...fields,
384
+ ...declared.map((name) => ({ name, type: 'STRING', nullable: true, generated: false })),
385
+ ];
386
+ }
387
+
361
388
  // The record identity every table entity carries after its own columns: what
362
389
  // a request server with no reply block sends in each row and lists in
363
390
  // REPLY_FIELD, and what a criteria-only one can sort and filter by.
@@ -675,6 +702,30 @@ const byName = (a: ResolvedField, b: ResolvedField) => {
675
702
  return left < right ? -1 : left > right ? 1 : 0;
676
703
  };
677
704
 
705
+ // A custom class's fields, as a DTO event's DETAILS or a class nested in one:
706
+ // sorted by name, each optional only when it declares a default or
707
+ // `optional: true` (a DTO's Kotlin defaults are invisible).
708
+ // A typed request server's class fields (TypedRequestReply), in the order
709
+ // they're listed rather than by name.
710
+ export function typedFields(fields: FieldDef[]): ResolvedField[] {
711
+ const resolved = new Map(dtoFields(fields).map((field) => [field.name, field]));
712
+ return fields.map(({ name }) => resolved.get(name)!);
713
+ }
714
+
715
+ export function dtoFields(
716
+ fields: FieldDef[],
717
+ table?: string,
718
+ fieldTypes?: Record<string, string>,
719
+ ): ResolvedField[] {
720
+ const resolved = fields.map((field) => fromFieldDef(field, table, false, false));
721
+ return withTypeOverrides({ fields: resolved, declared: true }, fieldTypes)
722
+ .fields.map((field) => ({
723
+ ...field,
724
+ optional: field.optional ?? field.default !== undefined,
725
+ }))
726
+ .sort(byName);
727
+ }
728
+
678
729
  // The fields an event's DETAILS take, sorted by name as the real server
679
730
  // lists a class's properties — except a delete's, which are the key fields
680
731
  // in key order, all mandatory. A key field the schema doesn't know (an
@@ -690,15 +741,7 @@ export function eventFields(
690
741
  store: Store,
691
742
  ): ResolvedField[] {
692
743
  if (target.kind === 'dto') {
693
- const resolved = (target.fields ?? []).map((field) =>
694
- fromFieldDef(field, target.table, false, false),
695
- );
696
- return withTypeOverrides({ fields: resolved, declared: true }, target.fieldTypes)
697
- .fields.map((field) => ({
698
- ...field,
699
- optional: field.optional ?? field.default !== undefined,
700
- }))
701
- .sort(byName);
744
+ return dtoFields(target.fields ?? [], target.table, target.fieldTypes);
702
745
  }
703
746
  const table = target.table!;
704
747
  const { fields } = withTypeOverrides(
package/src/db/store.ts CHANGED
@@ -744,6 +744,11 @@ export class Store {
744
744
  return seed.map(withoutRecordFields);
745
745
  }
746
746
 
747
+ // Whether tableName is a table (not a view).
748
+ hasTable(tableName: string): boolean {
749
+ return this.tableConfig.has(tableName);
750
+ }
751
+
747
752
  // Row-identity fields for a table or view; empty when unknown.
748
753
  getPkFields(resourceName: string): string[] {
749
754
  const view = this.views.get(resourceName);
@@ -1,8 +1,18 @@
1
1
  import crypto from 'node:crypto';
2
+ import type { Store } from '../db/store.ts';
2
3
  import type { Connection } from '../protocol/connection.ts';
3
4
  import { isLegacyFidelity } from '../protocol/fidelity.ts';
4
5
  import { MESSAGE_TYPE, ERROR_CODE } from '../protocol/messageTypes.ts';
5
- import type { AuthUser, GenesisMessage, MockServerConfig, ProductDetails, Row } from '../types.ts';
6
+ import type {
7
+ AuthUser,
8
+ BroadcastTableChangeFn,
9
+ GenesisMessage,
10
+ LoginCtx,
11
+ LoginFailure,
12
+ MockServerConfig,
13
+ ProductDetails,
14
+ Row,
15
+ } from '../types.ts';
6
16
 
7
17
  const LEGACY_HEARTBEAT_INTERVAL_SECS = 30;
8
18
  // auth 8.15.5 AuthPreferencesDefinition.kt:17,19 defaults.
@@ -215,11 +225,26 @@ function buildLegacyLoginAckBody(
215
225
  };
216
226
  }
217
227
 
228
+ // The status each login failure answers with (AuthFailure$WhenMappings).
229
+ const LOGIN_FAILURE_STATUS: Record<LoginError, string> = {
230
+ INCORRECT_CREDENTIALS: '401 Unauthorized',
231
+ UNKNOWN_ACCOUNT: '401 Unauthorized',
232
+ PASSWORD_EXPIRED: '403 Forbidden',
233
+ LOCKED_ACCOUNT: '403 Forbidden',
234
+ MAX_TRIES_REACHED: '429 Too Many Requests',
235
+ NO_COMPATIBLE_PROVIDERS: '400 Bad Request',
236
+ INTERNAL_ERROR: '500 Internal Server Error',
237
+ };
238
+
218
239
  // A failed login, GSF auth 8.15.5: one LoginError (Events.kt:91-98,133-140)
219
- // with the "Problem logging in" text, for a wrong password and an unknown
220
- // user alike (LoginProcessor.kt:160-161,330). Over HTTP it is a 200
221
- // (http-login-failed.json).
222
- export function buildLoginNackBody(config: MockServerConfig, transport: 'ws' | 'http'): Row {
240
+ // with the "Problem logging in" text whatever the failure, an unknown user
241
+ // and a wrong password alike (LoginProcessor.kt:160-161,330). Over HTTP it is
242
+ // a 200 (http-login-failed.json).
243
+ export function buildLoginNackBody(
244
+ config: MockServerConfig,
245
+ transport: 'ws' | 'http',
246
+ failure: LoginError = 'INCORRECT_CREDENTIALS',
247
+ ): Row {
223
248
  if (isLegacyFidelity(config)) {
224
249
  return {
225
250
  MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
@@ -243,9 +268,9 @@ export function buildLoginNackBody(config: MockServerConfig, transport: 'ws' | '
243
268
  ERROR: [
244
269
  {
245
270
  '@type': 'LoginError',
246
- CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
271
+ CODE: failure,
247
272
  TEXT: 'Problem logging in',
248
- STATUS_CODE: '401 Unauthorized',
273
+ STATUS_CODE: LOGIN_FAILURE_STATUS[failure],
249
274
  DETAILS: null,
250
275
  },
251
276
  ],
@@ -265,24 +290,157 @@ export function buildLogoutAckBody(config: MockServerConfig): Row {
265
290
 
266
291
  // Trusted lookup by username alone — for paths where identity is already
267
292
  // established (a token this server issued, an HTTP session cookie,
268
- // httpAutoLogin). NEVER use this for a credentials login.
269
- export function findUser(config: MockServerConfig, username?: string): AuthUser | undefined {
293
+ // httpAutoLogin): the directory's user when the config has one, else a
294
+ // configured one. NEVER use this for a credentials login.
295
+ export function findUser(
296
+ config: MockServerConfig,
297
+ store: Store,
298
+ username?: string,
299
+ ): AuthUser | undefined {
270
300
  if (username === undefined) return undefined;
301
+ const directory = config.auth?.directory;
302
+ if (directory) return directory.user(username, store);
271
303
  return (config.auth?.users ?? []).find((u) => u.username === username);
272
304
  }
273
305
 
274
- // Credentials login: the supplied password must match the configured one. A
275
- // missing PASSWORD is a failed login, never a username-only lookup — treating
276
- // it as one lets any client authenticate as any configured user just by
277
- // omitting the field, defeating auth.requireAuth and every rowFilter/
278
- // hideFields rule built on the logged-in identity.
279
- export function findUserByCredentials(
306
+ // A status auth asks a new password for (UserStatus).
307
+ const needsNewPassword = (status: string | undefined) =>
308
+ status === 'PASSWORD_EXPIRED' || status === 'PASSWORD_RESET';
309
+ const statusLetsIn = (status: string | undefined) => status === undefined || status === 'ENABLED';
310
+
311
+ // Which of auth's authenticators takes a login. AuthenticationService.login
312
+ // asks RefreshTokenAuthenticator first, which takes a refresh token without
313
+ // a PASSWORD, then GenesisDbAuthenticator, which needs USER_NAME and
314
+ // PASSWORD both; a message neither takes is NO_COMPATIBLE_PROVIDERS. Under
315
+ // fidelity: 'legacy', as up to 15.47: a USER_NAME makes it a credentials
316
+ // login, and a message without one a refresh.
317
+ export type LoginKind = 'credentials' | 'refresh' | 'none';
318
+ export function loginKind(
280
319
  config: MockServerConfig,
281
- username?: string,
282
- password?: string,
283
- ): AuthUser | undefined {
284
- const user = findUser(config, username);
285
- return user && user.password === password ? user : undefined;
320
+ details: Row,
321
+ refreshToken: unknown,
322
+ ): LoginKind {
323
+ if (isLegacyFidelity(config)) return details.USER_NAME === undefined ? 'refresh' : 'credentials';
324
+ const given = (value: unknown) => value !== undefined && value !== null;
325
+ if (!given(details.PASSWORD) && given(refreshToken)) return 'refresh';
326
+ return given(details.USER_NAME) && given(details.PASSWORD) ? 'credentials' : 'none';
327
+ }
328
+
329
+ // A credentials login: the directory's when the config has one, else checked
330
+ // against the configured users in auth's order (GenesisDbAuthenticator, auth
331
+ // v8.15.5): an unknown or DISABLED user fails as a wrong password does, a
332
+ // status that asks for a new password answers PASSWORD_EXPIRED, both before
333
+ // the password is looked at, and a right password with any other status but
334
+ // ENABLED LOCKED_ACCOUNT. fidelity: 'legacy' compares the password as 15.47
335
+ // did, so a user configured without one logs in by sending none.
336
+ export function credentialsLogin(
337
+ config: MockServerConfig,
338
+ store: Store,
339
+ details: Row,
340
+ ctx: LoginCtx,
341
+ ): AuthUser | LoginFailure {
342
+ const username = String(details.USER_NAME);
343
+ const directory = config.auth?.directory;
344
+ if (directory) {
345
+ const password =
346
+ details.PASSWORD === undefined || details.PASSWORD === null
347
+ ? undefined
348
+ : String(details.PASSWORD);
349
+ return directory.login(username, password, ctx);
350
+ }
351
+ const user = findUser(config, store, username);
352
+ if (!user || user.status === 'DISABLED') return 'INCORRECT_CREDENTIALS';
353
+ if (needsNewPassword(user.status)) return 'PASSWORD_EXPIRED';
354
+ const password = isLegacyFidelity(config) ? details.PASSWORD : String(details.PASSWORD);
355
+ if (user.password !== password) return 'INCORRECT_CREDENTIALS';
356
+ return statusLetsIn(user.status) ? user : 'LOCKED_ACCOUNT';
357
+ }
358
+
359
+ // A login no authenticator takes: the directory records it (it is asked with
360
+ // no password), and it fails whatever the directory answers.
361
+ export function unclaimedLogin(
362
+ config: MockServerConfig,
363
+ details: Row,
364
+ ctx: LoginCtx,
365
+ ): LoginFailure {
366
+ const directory = config.auth?.directory;
367
+ const username = typeof details.USER_NAME === 'string' ? details.USER_NAME : '';
368
+ const answer = directory?.login(username, undefined, ctx);
369
+ return typeof answer === 'string' ? answer : 'NO_COMPATIBLE_PROVIDERS';
370
+ }
371
+
372
+ // A refresh-token login (RefreshTokenAuthenticator) as the user the token's
373
+ // session belongs to (undefined: none has it), refused when their status no
374
+ // longer lets them in.
375
+ export function refreshLogin(
376
+ config: MockServerConfig,
377
+ store: Store,
378
+ username: string | undefined,
379
+ ctx: LoginCtx,
380
+ ): AuthUser | LoginFailure {
381
+ const directory = config.auth?.directory;
382
+ if (directory) return directory.refresh(username, ctx);
383
+ const user = findUser(config, store, username);
384
+ if (!user) return isLegacyFidelity(config) ? 'INCORRECT_CREDENTIALS' : 'UNKNOWN_ACCOUNT';
385
+ if (needsNewPassword(user.status)) return 'PASSWORD_EXPIRED';
386
+ return statusLetsIn(user.status) ? user : 'LOCKED_ACCOUNT';
387
+ }
388
+
389
+ // Why a login fails as the client sees it: auth's reasons, or an error in
390
+ // the mock's own login (a directory that throws, or answers with neither a
391
+ // user nor a reason), which would otherwise leave a socket login unanswered.
392
+ export type LoginError = LoginFailure | 'INTERNAL_ERROR';
393
+
394
+ export function attemptLogin(run: () => AuthUser | LoginFailure): AuthUser | LoginError {
395
+ try {
396
+ const answer: unknown = run();
397
+ if (typeof answer === 'string' && answer in LOGIN_FAILURE_STATUS) return answer as LoginFailure;
398
+ if (typeof answer === 'object' && answer !== null) return answer as AuthUser;
399
+ console.error('[mock-server] A login answered with neither a user nor a reason:', answer);
400
+ } catch (error) {
401
+ console.error('[mock-server] Error during a login:', error);
402
+ }
403
+ return 'INTERNAL_ERROR';
404
+ }
405
+
406
+ // Tells the directory a session of `username`'s has logged out.
407
+ export function recordLogout(
408
+ config: MockServerConfig,
409
+ auth: AuthState,
410
+ username: string,
411
+ ctx: LoginCtx,
412
+ ): void {
413
+ const online = [...auth.sessions.values()].some((session) => session.username === username);
414
+ config.auth?.directory?.logout(username, online, ctx);
415
+ }
416
+
417
+ // DETAILS.HOSTNAME as GSF's router sets it on a login or logout
418
+ // (MsgCreator.kt:59-66 @v8.15.29): the HOSTNAME header, else the socket's
419
+ // address as Java prints it, up to its first ':' ("/127.0.0.1"; an IPv6 one
420
+ // keeps "/[" and its first group).
421
+ export function routerHostname(header: unknown, address: string | undefined): string {
422
+ if (typeof header === 'string' && header !== '') return header;
423
+ const ip = (address ?? '').replace(/^::ffff:(?=\d+\.)/, '');
424
+ if (!ip.includes(':')) return `/${ip}`;
425
+ return `/[${ip.startsWith(':') ? '0' : ip.split(':')[0]}`;
426
+ }
427
+
428
+ // What a login over the socket runs with.
429
+ function socketLoginCtx(
430
+ message: GenesisMessage,
431
+ connection: Connection,
432
+ store: Store,
433
+ broadcastTableChange: BroadcastTableChangeFn,
434
+ ): LoginCtx {
435
+ return {
436
+ store,
437
+ broadcastTableChange,
438
+ hostname: routerHostname(
439
+ connection.hostnameHeader ?? message.HOSTNAME,
440
+ connection.remoteAddress,
441
+ ),
442
+ messageUser: typeof message.USER_NAME === 'string' ? message.USER_NAME : null,
443
+ };
286
444
  }
287
445
 
288
446
  export function handleLogin(
@@ -290,28 +448,38 @@ export function handleLogin(
290
448
  connection: Connection,
291
449
  config: MockServerConfig,
292
450
  auth: AuthState,
451
+ store: Store,
452
+ broadcastTableChange: BroadcastTableChangeFn,
293
453
  ): void {
294
454
  const details = message.DETAILS ?? {};
295
- // Two login shapes share EVENT_LOGIN_AUTH: credentials ({USER_NAME,
296
- // PASSWORD}) and token refresh — foundation-comms' createRefreshTokenMessage
297
- // sends only DETAILS.REFRESH_AUTH_TOKEN (plus the stored SESSION_AUTH_TOKEN
298
- // at the top level), no username at all.
299
- const tokenUsername =
300
- details.USER_NAME === undefined
301
- ? (auth.tokens.get(details.REFRESH_AUTH_TOKEN) ??
455
+ const ctx = socketLoginCtx(message, connection, store, broadcastTableChange);
456
+ // The session a refresh logs out: RefreshTokenAuthenticator deletes the
457
+ // USER_SESSION whose token it used. Under fidelity: 'legacy' the old
458
+ // session stays, as up to 15.47.
459
+ let replaced: AuthSession | undefined;
460
+ const user = attemptLogin(() => {
461
+ const kind = loginKind(config, details, details.REFRESH_AUTH_TOKEN);
462
+ if (kind === 'credentials') return credentialsLogin(config, store, details, ctx);
463
+ if (kind === 'none') return unclaimedLogin(config, details, ctx);
464
+ if (isLegacyFidelity(config)) {
465
+ // foundation-comms' createRefreshTokenMessage sends the refresh token
466
+ // in DETAILS and the stored SESSION_AUTH_TOKEN at the top level.
467
+ const username =
468
+ auth.tokens.get(details.REFRESH_AUTH_TOKEN) ??
302
469
  auth.tokens.get(details.SESSION_AUTH_TOKEN) ??
303
- auth.tokens.get(message.SESSION_AUTH_TOKEN))
304
- : undefined;
305
- const user =
306
- details.USER_NAME !== undefined
307
- ? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
308
- : findUser(config, tokenUsername);
309
-
310
- if (!user) {
311
- connection.reply(message, buildLoginNackBody(config, 'ws'));
470
+ auth.tokens.get(message.SESSION_AUTH_TOKEN);
471
+ return refreshLogin(config, store, username, ctx);
472
+ }
473
+ replaced = sessionByRefreshToken(auth, details.REFRESH_AUTH_TOKEN);
474
+ return refreshLogin(config, store, replaced?.username, ctx);
475
+ });
476
+
477
+ if (typeof user === 'string') {
478
+ connection.reply(message, buildLoginNackBody(config, 'ws', user));
312
479
  return;
313
480
  }
314
481
 
482
+ if (replaced) closeSession(auth, replaced);
315
483
  const session = openSession(auth, user);
316
484
  connection.authenticated = true;
317
485
  connection.userName = user.username;
@@ -329,12 +497,18 @@ export function handleLogout(
329
497
  connection: Connection,
330
498
  config: MockServerConfig,
331
499
  auth: AuthState,
500
+ store: Store,
501
+ broadcastTableChange: BroadcastTableChangeFn,
332
502
  ): void {
333
503
  const session =
334
504
  connection.sessionAuthToken === undefined
335
505
  ? undefined
336
506
  : auth.sessions.get(connection.sessionAuthToken);
337
- if (session) closeSession(auth, session);
507
+ if (session) {
508
+ closeSession(auth, session);
509
+ const ctx = socketLoginCtx(message, connection, store, broadcastTableChange);
510
+ recordLogout(config, auth, session.username, ctx);
511
+ }
338
512
  for (const token of [connection.sessionAuthToken, connection.refreshAuthToken]) {
339
513
  if (token !== undefined) auth.tokens.delete(token);
340
514
  }