@genesislcap/mock-server 15.65.1-alpha-358eaead70.0 → 15.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +120 -4
  2. package/dist/handlers/auth.d.ts +24 -5
  3. package/dist/handlers/auth.js +196 -43
  4. package/dist/handlers/heartbeat.d.ts +2 -1
  5. package/dist/handlers/heartbeat.js +26 -3
  6. package/dist/handlers/http.d.ts +6 -3
  7. package/dist/handlers/http.js +266 -91
  8. package/dist/handlers/resources.d.ts +2 -1
  9. package/dist/handlers/resources.js +18 -2
  10. package/dist/index.d.ts +1 -1
  11. package/dist/presets/csv.d.ts +2 -0
  12. package/dist/presets/csv.js +52 -0
  13. package/dist/presets/index.d.ts +3 -0
  14. package/dist/presets/index.js +3 -0
  15. package/dist/presets/merge.d.ts +15 -0
  16. package/dist/presets/merge.js +76 -0
  17. package/dist/presets/platform/default-user.json +30 -0
  18. package/dist/presets/platform/profile-rights.json +242 -0
  19. package/dist/presets/platform/profiles.json +62 -0
  20. package/dist/presets/platform/resources.json +710 -0
  21. package/dist/presets/platform/rights.json +238 -0
  22. package/dist/presets/platform.d.ts +27 -0
  23. package/dist/presets/platform.js +410 -0
  24. package/dist/protocol/connection.d.ts +10 -2
  25. package/dist/protocol/connection.js +69 -3
  26. package/dist/protocol/msgNack.d.ts +2 -0
  27. package/dist/protocol/msgNack.js +18 -0
  28. package/dist/protocol/router.d.ts +2 -2
  29. package/dist/protocol/router.js +24 -7
  30. package/dist/server.js +30 -12
  31. package/dist/types.d.ts +18 -0
  32. package/package.json +8 -2
  33. package/src/handlers/auth.ts +232 -44
  34. package/src/handlers/heartbeat.ts +38 -4
  35. package/src/handlers/http.ts +317 -103
  36. package/src/handlers/resources.ts +19 -2
  37. package/src/index.ts +2 -0
  38. package/src/presets/csv.ts +50 -0
  39. package/src/presets/index.ts +8 -0
  40. package/src/presets/merge.ts +79 -0
  41. package/src/presets/platform/default-user.json +30 -0
  42. package/src/presets/platform/profile-rights.json +242 -0
  43. package/src/presets/platform/profiles.json +62 -0
  44. package/src/presets/platform/resources.json +710 -0
  45. package/src/presets/platform/rights.json +238 -0
  46. package/src/presets/platform.ts +503 -0
  47. package/src/protocol/connection.ts +77 -3
  48. package/src/protocol/msgNack.ts +25 -0
  49. package/src/protocol/router.ts +31 -8
  50. package/src/server.ts +35 -12
  51. package/src/types.ts +69 -3
@@ -0,0 +1,503 @@
1
+ // The Genesis platform a GSF 8.15.x app runs beside its own processes: auth
2
+ // (users, profiles, rights, the key-value store), notify's alerts, and the
3
+ // RESOURCES every platform PBC registers. Data comes from ./platform/*.json,
4
+ // which scripts/platform-preset/generate.ts builds from real recordings and the
5
+ // PBCs' own seed files; behaviour and texts cite the PBC scripts at the
6
+ // versions the showcase server pins (server/gradle.properties: GSF 8.15.29,
7
+ // auth 8.15.5, genesis-notify 8.15.16).
8
+ import { NackError } from '../protocol/errors.ts';
9
+ import type {
10
+ AuthUser,
11
+ EventHandler,
12
+ EventHandlerCtx,
13
+ FieldDef,
14
+ MockServerConfig,
15
+ ResourceItem,
16
+ Row,
17
+ TableDef,
18
+ } from '../types.ts';
19
+ import defaultUser from './platform/default-user.json' with { type: 'json' };
20
+ import platformProfileRights from './platform/profile-rights.json' with { type: 'json' };
21
+ import platformProfiles from './platform/profiles.json' with { type: 'json' };
22
+ import platformResources from './platform/resources.json' with { type: 'json' };
23
+ import platformRights from './platform/rights.json' with { type: 'json' };
24
+
25
+ export interface PlatformUser {
26
+ username: string;
27
+ // What a credentials login must send. Unset: this user can't log in with a
28
+ // password (httpAutoLogin and issued tokens still work).
29
+ password?: string;
30
+ // The profiles the user belongs to (PROFILE_USER). Unless `permission` is
31
+ // set, the user's rights are these profiles' rights (PROFILE_RIGHT), as
32
+ // auth's consolidator works them out.
33
+ profile?: string[];
34
+ // The user's rights, replacing the ones the profiles give.
35
+ permission?: string[];
36
+ // The user's USER and USER_ATTRIBUTES columns (FIRST_NAME, LAST_NAME,
37
+ // EMAIL_ADDRESS, COMPANY_NAME, STATUS, LAST_LOGIN, ACCESS_TYPE, ...): its
38
+ // ALL_USERS row.
39
+ user?: Row;
40
+ }
41
+
42
+ // Rows an app adds to the platform tables, as its data/*.csv do: loaded after
43
+ // the platform PBCs' own, a row with the same key replaces theirs.
44
+ export interface PlatformSeed {
45
+ RIGHT?: Row[];
46
+ PROFILE?: Row[];
47
+ PROFILE_RIGHT?: Row[];
48
+ NOTIFY_ALERT?: Row[];
49
+ KEY_VALUE?: Row[];
50
+ }
51
+
52
+ export interface PlatformPresetOptions {
53
+ // The users who can log in. Default: blank-app-seed's admin (password
54
+ // 'admin'), in every profile the platform PBCs seed except
55
+ // NOTIFICATION_SERVICE, as the real showcase and Create apps have it.
56
+ users?: PlatformUser[];
57
+ seed?: PlatformSeed;
58
+ // Listed in RESOURCES beside the platform's.
59
+ resources?: ResourceItem[];
60
+ // Who a connection that never logged in acts as for the per-user resources
61
+ // (the key-value store, alerts). A client that logs in over HTTP sends no
62
+ // session token on its WebSocket, so the mock can't tell who it is; the real
63
+ // server knows from the session cookie. Default: the first user.
64
+ sessionUser?: string;
65
+ }
66
+
67
+ const DEFAULT_PASSWORD = 'admin';
68
+
69
+ // --- tables --------------------------------------------------------------------
70
+
71
+ const field = (name: string, type: FieldDef['type'] = 'STRING', more: Partial<FieldDef> = {}) => ({
72
+ name,
73
+ type,
74
+ ...more,
75
+ });
76
+
77
+ // USER, genesis-tables-dictionary.kts:360 (GSF v8.15.29), types from
78
+ // genesis-fields-dictionary.kts. PASSWORD and PASSWORD_EXPIRY_DATETIME are left
79
+ // out: credentials are PlatformUser.password, and no query exposes them.
80
+ const USER_FIELDS: FieldDef[] = [
81
+ field('USER_NAME', 'STRING', { maxSize: 255 }),
82
+ field('FIRST_NAME'),
83
+ field('LAST_NAME'),
84
+ field('EMAIL_ADDRESS'),
85
+ field('LAST_LOGIN', 'DATE'),
86
+ field('STATUS'),
87
+ field('ONLINE', 'BOOLEAN', { default: false }),
88
+ field('COMPANY_NAME'),
89
+ field('COMPANY_ID'),
90
+ field('DOMAIN'),
91
+ ];
92
+
93
+ // USER_ATTRIBUTES, genesis-tables-dictionary.kts:378 (GSF v8.15.29).
94
+ const USER_ATTRIBUTE_FIELDS: FieldDef[] = [
95
+ field('USER_NAME', 'STRING', { maxSize: 255 }),
96
+ field('USER_TYPE', 'ENUM', {
97
+ values: ['USER', 'ADVISOR', 'CLIENT', 'SYSTEM', 'API'],
98
+ default: 'USER',
99
+ }),
100
+ field('ACCESS_TYPE', 'ENUM', { values: ['ALL', 'ENTITY', 'MULTI_ENTITY'], default: 'ALL' }),
101
+ ...['ADDRESS_LINE1', 'ADDRESS_LINE2', 'ADDRESS_LINE3', 'ADDRESS_LINE4'].map((name) =>
102
+ field(name, 'STRING', { maxSize: 400 }),
103
+ ),
104
+ ...[
105
+ 'CITY',
106
+ 'REGION',
107
+ 'POSTAL_CODE',
108
+ 'COUNTRY',
109
+ 'TITLE',
110
+ 'WEBSITE',
111
+ 'MOBILE_NUMBER',
112
+ 'TELEPHONE_NUMBER_DIRECT',
113
+ 'TELEPHONE_NUMBER_OFFICE',
114
+ ].map((name) => field(name)),
115
+ ];
116
+
117
+ const fieldNames = (fields: FieldDef[]) => fields.map(({ name }) => name);
118
+ const USER_COLUMNS = new Set(fieldNames(USER_FIELDS));
119
+ const ATTRIBUTE_COLUMNS = new Set(fieldNames(USER_ATTRIBUTE_FIELDS));
120
+
121
+ // auth-tables-dictionary.kts (auth v8.15.5): KEY_VALUE :2, PROFILE :12,
122
+ // PROFILE_USER :22, RIGHT :46, PROFILE_RIGHT :54; types from
123
+ // auth-fields-dictionary.kts. NOTIFY_ALERT: genesis-notify-tables-dictionary.kts:112
124
+ // (genesis-notify v8.15.16), types from genesis-notify-fields-dictionary.kts.
125
+ function platformTables(
126
+ seed: Required<PlatformSeed>,
127
+ users: PlatformUser[],
128
+ ): Record<string, TableDef> {
129
+ return {
130
+ USER: {
131
+ pkField: 'USER_NAME',
132
+ fields: USER_FIELDS,
133
+ rows: users.map(({ username, user = {} }) => ({
134
+ ...pick(user, USER_COLUMNS),
135
+ USER_NAME: username,
136
+ })),
137
+ },
138
+ USER_ATTRIBUTES: {
139
+ pkField: 'USER_NAME',
140
+ fields: USER_ATTRIBUTE_FIELDS,
141
+ rows: users.map(({ username, user = {} }) => ({
142
+ ...pick(user, ATTRIBUTE_COLUMNS),
143
+ USER_NAME: username,
144
+ })),
145
+ },
146
+ PROFILE: {
147
+ pkField: 'NAME',
148
+ fields: [
149
+ field('NAME', 'STRING', { maxSize: 255 }),
150
+ field('DESCRIPTION'),
151
+ field('STATUS'),
152
+ field('IS_PRIMARY', 'BOOLEAN', { nullable: false, default: true }),
153
+ ],
154
+ rows: seed.PROFILE,
155
+ },
156
+ PROFILE_USER: {
157
+ pkField: ['PROFILE_NAME', 'USER_NAME'],
158
+ fields: [field('PROFILE_NAME'), field('USER_NAME', 'STRING', { maxSize: 255 })],
159
+ rows: users.flatMap(({ username, profile = [] }) =>
160
+ profile.map((PROFILE_NAME) => ({ PROFILE_NAME, USER_NAME: username })),
161
+ ),
162
+ },
163
+ RIGHT: {
164
+ pkField: 'CODE',
165
+ fields: [field('CODE'), field('DESCRIPTION')],
166
+ rows: seed.RIGHT,
167
+ },
168
+ PROFILE_RIGHT: {
169
+ pkField: ['RIGHT_CODE', 'PROFILE_NAME'],
170
+ fields: [field('RIGHT_CODE'), field('PROFILE_NAME')],
171
+ rows: seed.PROFILE_RIGHT,
172
+ },
173
+ // USER_NAME, KV_KEY, KV_VALUE (RAW). Left undeclared: a declared table
174
+ // would have the engine check EVENT_KEY_VALUE_PUT's DETAILS against it,
175
+ // and the real handler skips the schema check (`schemaValidation = false`).
176
+ KEY_VALUE: { pkField: ['USER_NAME', 'KV_KEY'], rows: seed.KEY_VALUE },
177
+ NOTIFY_ALERT: {
178
+ pkField: 'ALERT_ID',
179
+ // sequence(ALERT_ID, "AL")
180
+ sequencePrefix: 'AL',
181
+ sequenceFormat: 'genesis',
182
+ fields: [
183
+ field('ALERT_ID'),
184
+ field('MESSAGE'),
185
+ field('HEADER'),
186
+ field('USER_NAME', 'STRING', { maxSize: 255 }),
187
+ field('EXPIRY', 'DATETIME'),
188
+ field('NOTIFY_SEVERITY', 'ENUM', {
189
+ values: ['Information', 'Warning', 'Serious', 'Critical'],
190
+ default: 'Information',
191
+ }),
192
+ field('CREATED_AT', 'DATETIME'),
193
+ field('TABLE_ENTITY_ID'),
194
+ field('DYNAMIC_RULE_ID'),
195
+ field('TOPIC'),
196
+ field('ALERT_STATUS', 'ENUM', { values: ['NEW', 'DISMISSED', 'EXPIRED'], default: 'NEW' }),
197
+ field('SHOW_TOAST', 'BOOLEAN', { default: true }),
198
+ ],
199
+ rows: seed.NOTIFY_ALERT,
200
+ },
201
+ };
202
+ }
203
+
204
+ function pick(row: Row, columns: Set<string>): Row {
205
+ return Object.fromEntries(Object.entries(row).filter(([name]) => columns.has(name)));
206
+ }
207
+
208
+ // A later row with the same key replaces an earlier one (GSF's data load
209
+ // upserts), keeping the first one's place.
210
+ function upsert(rows: Row[], extra: Row[] | undefined, key: (row: Row) => string): Row[] {
211
+ const byKey = new Map<string, Row>();
212
+ for (const row of [...rows, ...(extra ?? [])]) byKey.set(key(row), row);
213
+ return [...byKey.values()];
214
+ }
215
+
216
+ // --- the session user ------------------------------------------------------------
217
+
218
+ // The user an event or request runs as: the connection's login, else the
219
+ // sessionUser (see PlatformPresetOptions.sessionUser).
220
+ function sessionUserOf(userName: string | undefined, fallback: string | undefined): string {
221
+ const user = userName ?? fallback;
222
+ // GSF never runs a handler without a user: its WebSocket is authenticated.
223
+ if (user === undefined) throw NackError.standard('NOT_AUTHORISED', 'No user is logged in');
224
+ return user;
225
+ }
226
+
227
+ // --- auth: the key-value store ---------------------------------------------------
228
+
229
+ // A RAW column's value on the wire: its bytes in base64
230
+ // (GenesisSetMaskingJsonSerializer: gen.writeBinary). foundation-comms'
231
+ // kv.service base64-decodes every VALUE it reads.
232
+ const rawValue = (value: unknown) => Buffer.from(String(value ?? ''), 'utf8').toString('base64');
233
+
234
+ function keyValueHandlers(fallback: string | undefined): Record<string, EventHandler> {
235
+ const userOf = (ctx: EventHandlerCtx) => sessionUserOf(ctx.connection.userName, fallback);
236
+ return {
237
+ // auth-key-value-eventhandler.kts (auth v8.15.5), KEY_VALUE_PUT:
238
+ // `schemaValidation = false`, then entityDb.upsertAll of DETAILS.RECORDS
239
+ // [{KEY, VALUE}] under the event's user. foundation-comms' kvStorage.put
240
+ // sends them; grid column-state persistence rides on this. VALUE is kept
241
+ // as sent (KeyValueRecord's Utf8ByteArrayDeserializer stores its UTF-8
242
+ // bytes); REQ_KEY_VALUE_READ hands it back in base64.
243
+ EVENT_KEY_VALUE_PUT: (details, ctx) => {
244
+ const { store, broadcastTableChange } = ctx;
245
+ const userName = userOf(ctx);
246
+ const records = (Array.isArray(details.RECORDS) ? details.RECORDS : []) as Row[];
247
+ for (const record of records) {
248
+ // A record without a KEY fails KeyValueRecord's non-null `key` before
249
+ // the upsert, and onException NACKs with its text.
250
+ if (typeof record?.KEY !== 'string') {
251
+ const keys = records.map((each) => each?.KEY).join(',');
252
+ throw NackError.nack(
253
+ `Error when upserting record for user: ${userName} with keys: '${keys}'.`,
254
+ );
255
+ }
256
+ }
257
+ for (const { KEY, VALUE } of records) {
258
+ const existing = store.findRow('KEY_VALUE', { USER_NAME: userName, KV_KEY: KEY });
259
+ if (existing) {
260
+ const key = store.rowKey('KEY_VALUE', existing);
261
+ store.updateRow('KEY_VALUE', key, { KV_VALUE: VALUE });
262
+ broadcastTableChange('KEY_VALUE', 'MODIFY', key);
263
+ } else {
264
+ const row = store.insertRow('KEY_VALUE', {
265
+ USER_NAME: userName,
266
+ KV_KEY: KEY,
267
+ KV_VALUE: VALUE,
268
+ });
269
+ broadcastTableChange('KEY_VALUE', 'INSERT', store.rowKey('KEY_VALUE', row));
270
+ }
271
+ }
272
+ return {};
273
+ },
274
+ // KEY_VALUE_DELETE: DETAILS.KEYS (KeyValueSelectByKeys), deleted in order;
275
+ // a key that isn't there fails the delete, and onException NACKs with its
276
+ // own text. The real handler isn't transactional, so the keys deleted
277
+ // before the missing one stay deleted there; here the NACK rolls them back
278
+ // (the engine commits an event only when it acks).
279
+ EVENT_KEY_VALUE_DELETE: (details, ctx) => {
280
+ const { store, broadcastTableChange } = ctx;
281
+ const userName = userOf(ctx);
282
+ const keys = (Array.isArray(details.KEYS) ? details.KEYS : []) as string[];
283
+ for (const key of keys) {
284
+ const pk = store.rowKey('KEY_VALUE', { USER_NAME: userName, KV_KEY: key });
285
+ if (!store.deleteRow('KEY_VALUE', pk)) {
286
+ throw NackError.nack(
287
+ `Error when deleting records for user: ${userName} with Keys '${keys.join(',')}'`,
288
+ );
289
+ }
290
+ broadcastTableChange('KEY_VALUE', 'DELETE', pk);
291
+ }
292
+ return {};
293
+ },
294
+ };
295
+ }
296
+
297
+ // The KEY_VALUE records a REQ_KEY_VALUE_* request names: the REQUEST user's,
298
+ // and only the REQUEST's KEY when it has one (auth-reqrep.kts
299
+ // filterWithParameters).
300
+ function keyValues(rows: Row[], request: Row): Row[] {
301
+ return rows.filter(
302
+ (row) =>
303
+ row.USER_NAME === request.USER_NAME &&
304
+ (request.KEY === undefined || request.KEY === null || row.KV_KEY === request.KEY),
305
+ );
306
+ }
307
+
308
+ // --- notify: alerts --------------------------------------------------------------
309
+
310
+ // genesis-notify-eventhandler.kts (genesis-notify v8.15.16).
311
+ function alertHandlers(fallback: string | undefined): Record<string, EventHandler> {
312
+ return {
313
+ // :431 contextEventHandler<NotifyAlert.ByAlertId>: onValidate NACKs an
314
+ // alert that isn't there or is another user's; onCommit sets
315
+ // ALERT_STATUS DISMISSED (the inbox subscribes to ALERT_STATUS == 'NEW', so
316
+ // the engine pushes the row out of it as a DELETE).
317
+ EVENT_DISMISS_NOTIFY_ALERT: (details, ctx) => {
318
+ const { store, broadcastTableChange } = ctx;
319
+ const alert = store.findRow('NOTIFY_ALERT', { ALERT_ID: details.ALERT_ID });
320
+ if (!alert) throw NackError.nack(`Alert with ID ${details.ALERT_ID} does not exist`);
321
+ if (alert.USER_NAME !== sessionUserOf(ctx.connection.userName, fallback)) {
322
+ throw NackError.nack('Dismissing an alert targeted at another user is forbidden');
323
+ }
324
+ store.updateRow('NOTIFY_ALERT', alert.ALERT_ID, { ALERT_STATUS: 'DISMISSED' });
325
+ broadcastTableChange('NOTIFY_ALERT', 'MODIFY', alert.ALERT_ID);
326
+ return {};
327
+ },
328
+ // :453 eventHandler<Unit>: the event user's NEW alerts (NotifyAlert
329
+ // .byUserNameAlertStatus), DISMISSED in batches.
330
+ EVENT_DISMISS_ALL_NOTIFY_ALERT: (_details, ctx) => {
331
+ const { store, broadcastTableChange } = ctx;
332
+ const userName = sessionUserOf(ctx.connection.userName, fallback);
333
+ for (const alert of store.getAllRows('NOTIFY_ALERT')) {
334
+ if (alert.USER_NAME !== userName || alert.ALERT_STATUS !== 'NEW') continue;
335
+ store.updateRow('NOTIFY_ALERT', alert.ALERT_ID, { ALERT_STATUS: 'DISMISSED' });
336
+ broadcastTableChange('NOTIFY_ALERT', 'MODIFY', alert.ALERT_ID);
337
+ }
338
+ return {};
339
+ },
340
+ };
341
+ }
342
+
343
+ // --- the preset ------------------------------------------------------------------
344
+
345
+ // A user's rights: their profiles' PROFILE_RIGHT codes, sorted as the real
346
+ // login ack lists them.
347
+ function rightsOf(profiles: string[], profileRights: Row[]): string[] {
348
+ const codes = profileRights
349
+ .filter((row) => profiles.includes(row.PROFILE_NAME))
350
+ .map((row) => row.RIGHT_CODE as string);
351
+ return [...new Set(codes)].sort();
352
+ }
353
+
354
+ const DEFAULT_USER: PlatformUser = {
355
+ username: defaultUser.USER.USER_NAME,
356
+ password: DEFAULT_PASSWORD,
357
+ profile: defaultUser.PROFILE,
358
+ user: { ...defaultUser.USER, ...defaultUser.USER_ATTRIBUTES },
359
+ };
360
+
361
+ // The login ack's USER object: what the mock sent before this preset existed
362
+ // (the real ack's USER is null and its USER_DETAILS {FIRST_NAME, LAST_NAME},
363
+ // which plan item 1.19 aligns).
364
+ const LOGIN_USER_FIELDS = new Set(['FIRST_NAME', 'LAST_NAME', 'EMAIL_ADDRESS', 'COMPANY_NAME']);
365
+
366
+ /**
367
+ * The Genesis platform's data and handlers, to merge with an app's own config:
368
+ * `createMockServer(mergeConfigs(platformPreset(), appConfig))`. See the
369
+ * README's "Platform preset".
370
+ */
371
+ export function platformPreset(options: PlatformPresetOptions = {}): MockServerConfig {
372
+ const users = options.users ?? [DEFAULT_USER];
373
+ const fallback = options.sessionUser ?? users[0]?.username;
374
+ const seed: Required<PlatformSeed> = {
375
+ RIGHT: upsert(platformRights, options.seed?.RIGHT, (row) => row.CODE),
376
+ PROFILE: upsert(platformProfiles, options.seed?.PROFILE, (row) => row.NAME),
377
+ PROFILE_RIGHT: upsert(
378
+ platformProfileRights,
379
+ options.seed?.PROFILE_RIGHT,
380
+ (row) => `${row.PROFILE_NAME}|${row.RIGHT_CODE}`,
381
+ ),
382
+ NOTIFY_ALERT: options.seed?.NOTIFY_ALERT ?? [],
383
+ KEY_VALUE: options.seed?.KEY_VALUE ?? [],
384
+ };
385
+ const authUsers: AuthUser[] = users.map(
386
+ ({ username, password, profile = [], permission, user }) => ({
387
+ username,
388
+ password,
389
+ profile: [...profile].sort(),
390
+ permission: permission ?? rightsOf(profile, seed.PROFILE_RIGHT),
391
+ user: user && pick(user, LOGIN_USER_FIELDS),
392
+ }),
393
+ );
394
+ return {
395
+ tables: platformTables(seed, users),
396
+ views: {
397
+ // genesis-view-dictionary.kts:2 (GSF v8.15.29): USER and its
398
+ // USER_ATTRIBUTES, without the password, RECORD_ID and TIMESTAMP columns.
399
+ USER_VIEW: {
400
+ base: 'USER',
401
+ joins: [
402
+ {
403
+ table: 'USER_ATTRIBUTES',
404
+ on: ['USER_NAME', 'USER_NAME'],
405
+ backwardsJoin: true,
406
+ select: Object.fromEntries(
407
+ [...ATTRIBUTE_COLUMNS]
408
+ .filter((name) => name !== 'USER_NAME')
409
+ .map((name) => [name, name]),
410
+ ),
411
+ },
412
+ ],
413
+ },
414
+ // auth-view-dictionary.kts (auth v8.15.5) :50 and :65.
415
+ PROFILE_RIGHT_VIEW: {
416
+ base: 'PROFILE_RIGHT',
417
+ joins: [
418
+ { table: 'PROFILE', on: ['PROFILE_NAME', 'NAME'], type: 'INNER' },
419
+ { table: 'RIGHT', on: ['RIGHT_CODE', 'CODE'], type: 'INNER' },
420
+ ],
421
+ fields: ['PROFILE_NAME', 'RIGHT_CODE'],
422
+ },
423
+ PROFILE_USER_VIEW: {
424
+ base: 'PROFILE_USER',
425
+ joins: [
426
+ { table: 'USER', on: ['USER_NAME', 'USER_NAME'], type: 'INNER', backwardsJoin: true },
427
+ ],
428
+ fields: ['PROFILE_NAME', 'USER_NAME'],
429
+ },
430
+ // query(PROFILE) / requestReply(PROFILE) `NAME withPrefix PROFILE` and
431
+ // query(RIGHT) `CODE withPrefix RIGHT`, `DESCRIPTION withPrefix RIGHT`.
432
+ PROFILE_PREFIXED: {
433
+ base: 'PROFILE',
434
+ pkField: 'PROFILE_NAME',
435
+ select: { PROFILE_NAME: 'NAME' },
436
+ fields: ['PROFILE_NAME', 'DESCRIPTION', 'STATUS'],
437
+ },
438
+ RIGHT_PREFIXED: {
439
+ base: 'RIGHT',
440
+ pkField: 'RIGHT_CODE',
441
+ select: { RIGHT_CODE: 'CODE', RIGHT_DESCRIPTION: 'DESCRIPTION' },
442
+ fields: ['RIGHT_CODE', 'RIGHT_DESCRIPTION'],
443
+ },
444
+ },
445
+ // auth-dataserver.kts (auth v8.15.5) and genesis-notify-rules-dataserver.kts
446
+ // (genesis-notify v8.15.16).
447
+ queries: {
448
+ ALL_USERS: { source: 'USER_VIEW' },
449
+ ALL_PROFILES: { source: 'PROFILE_PREFIXED' },
450
+ ALL_RIGHTS: { source: 'RIGHT_PREFIXED' },
451
+ ALL_PROFILE_RIGHTS: { source: 'PROFILE_RIGHT_VIEW' },
452
+ ALL_PROFILE_USERS: { source: 'PROFILE_USER_VIEW' },
453
+ // `permissioning { auth { filterWithUserName { userName == data.userName } } }`
454
+ ALL_NOTIFY_ALERT_RECORDS: {
455
+ source: 'NOTIFY_ALERT',
456
+ auth: { rowFilter: (row, user) => row.USER_NAME === (user.userName ?? fallback) },
457
+ },
458
+ },
459
+ // auth-reqrep.kts (auth v8.15.5).
460
+ requestReplies: {
461
+ // :57 request { CODE } reply { CODE DESCRIPTION }, so its rows carry no
462
+ // RECORD_ID.
463
+ RIGHT: { source: 'RIGHT', fields: ['CODE', 'DESCRIPTION'] },
464
+ // :7 request { NAME withPrefix PROFILE } reply { ..., STATUS, DESCRIPTION }
465
+ PROFILE: {
466
+ source: 'PROFILE_PREFIXED',
467
+ requestFields: ['PROFILE_NAME'],
468
+ fields: ['PROFILE_NAME', 'STATUS', 'DESCRIPTION'],
469
+ },
470
+ // :212 request { USER_NAME } reply { KV_KEY withAlias "KEY" }
471
+ KEY_VALUE_LIST: {
472
+ requestFields: ['USER_NAME'],
473
+ resolver: ({ request, store }) =>
474
+ keyValues(store.getAllRows('KEY_VALUE'), request).map((row) => ({ KEY: row.KV_KEY })),
475
+ metadataRows: [{ KEY: 'example' }],
476
+ },
477
+ // :232 request { USER_NAME, KV_KEY withAlias "KEY" }
478
+ // reply { KV_KEY withAlias "KEY", KV_VALUE withAlias "VALUE" }
479
+ KEY_VALUE_READ: {
480
+ requestFields: ['USER_NAME', 'KEY'],
481
+ resolver: ({ request, store }) =>
482
+ keyValues(store.getAllRows('KEY_VALUE'), request).map((row) => ({
483
+ KEY: row.KV_KEY,
484
+ VALUE: rawValue(row.KV_VALUE),
485
+ })),
486
+ metadataRows: [{ KEY: 'example', VALUE: '' }],
487
+ },
488
+ },
489
+ eventHandlers: { ...keyValueHandlers(fallback), ...alertHandlers(fallback) },
490
+ // The DETAILS classes of the alert events, which their names alone would
491
+ // make NOTIFY_ALERT table events.
492
+ eventSchemas: {
493
+ EVENT_DISMISS_NOTIFY_ALERT: {
494
+ table: 'NOTIFY_ALERT',
495
+ pkOnly: true,
496
+ className: 'global.genesis.gen.dao.NotifyAlert.ByAlertId',
497
+ },
498
+ EVENT_DISMISS_ALL_NOTIFY_ALERT: { fields: [], className: 'kotlin.Unit' },
499
+ },
500
+ auth: { users: authUsers },
501
+ additionalResources: [...(platformResources as ResourceItem[]), ...(options.resources ?? [])],
502
+ };
503
+ }
@@ -62,6 +62,15 @@ export interface Subscription {
62
62
  encode?: (row: Row) => Row;
63
63
  }
64
64
 
65
+ // What a verbose HEARTBEAT_PONG reports per subscription (genesis-router
66
+ // QuerySubscription.kt / DataserverResource.kt @v8.15.29), all epoch millis.
67
+ interface SubscriptionStats {
68
+ createdAt: number;
69
+ lastReceived: number;
70
+ lastSent: number;
71
+ dataLogon: Row;
72
+ }
73
+
65
74
  // Wraps one WebSocket client connection: auth state and its live DATA_LOGON
66
75
  // subscriptions (keyed by SOURCE_REF, since that's the client's sole correlation
67
76
  // key — see README pitfall #1).
@@ -76,6 +85,17 @@ export class Connection {
76
85
  profile: string[] = [];
77
86
  permission: string[] = [];
78
87
  readonly subscriptions = new Map<string, Subscription>();
88
+ // The sessionAuthToken cookie the socket was opened with, under
89
+ // auth.cookieAuthentication; it authenticates every message (router.ts).
90
+ cookieSessionAuthToken: string | undefined;
91
+ // A verbose HEARTBEAT_PONG's CREATED_AT, LAST_RECEIVED and LAST_SENT, as
92
+ // genesis-router's ClientHandler keeps them (ClientHandler.kt:66-68,
93
+ // 100-113 @v8.15.29): 0 until a message other than a heartbeat goes either
94
+ // way, since pings and pongs bypass the client handler.
95
+ readonly createdAt = Date.now();
96
+ lastReceived = 0;
97
+ lastSent = 0;
98
+ private readonly subscriptionStats = new WeakMap<Subscription, SubscriptionStats>();
79
99
 
80
100
  constructor(ws: SocketLike) {
81
101
  this.ws = ws;
@@ -83,13 +103,67 @@ export class Connection {
83
103
 
84
104
  // Every response must echo the request's SOURCE_REF verbatim, or the client's
85
105
  // pending promise for that call never resolves (silent hang, no error).
86
- send(payload: Row): void {
106
+ // `track: false` for what the real router writes without its client
107
+ // handler (pongs, the cookie router's refusals): it leaves LAST_SENT alone.
108
+ send(payload: Row, track = true): void {
87
109
  if (this.ws.readyState !== WS_OPEN) return;
88
110
  this.ws.send(JSON.stringify(payload));
111
+ if (!track) return;
112
+ const now = Date.now();
113
+ this.lastSent = now;
114
+ const subscription =
115
+ typeof payload.SOURCE_REF === 'string'
116
+ ? this.subscriptions.get(payload.SOURCE_REF)
117
+ : undefined;
118
+ const stats = subscription && this.subscriptionStats.get(subscription);
119
+ if (stats) stats.lastSent = now;
120
+ }
121
+
122
+ reply(requestMessage: GenesisMessage, payload: Row, track = true): void {
123
+ this.send({ ...payload, SOURCE_REF: requestMessage.SOURCE_REF }, track);
124
+ }
125
+
126
+ // Called for every routed message but heartbeats.
127
+ noteReceived(message: GenesisMessage): void {
128
+ const now = Date.now();
129
+ this.lastReceived = now;
130
+ const subscription = this.subscriptions.get(message.SOURCE_REF ?? '');
131
+ const stats = subscription && this.subscriptionStats.get(subscription);
132
+ if (stats) stats.lastReceived = now;
133
+ }
134
+
135
+ // Called after a DATA_LOGON was handled: starts the stats of the
136
+ // subscription it opened, if it opened one.
137
+ noteLogon(message: GenesisMessage): void {
138
+ const subscription = this.subscriptions.get(message.SOURCE_REF ?? '');
139
+ if (!subscription || this.subscriptionStats.has(subscription)) return;
140
+ const now = Date.now();
141
+ this.subscriptionStats.set(subscription, {
142
+ createdAt: now,
143
+ lastReceived: now,
144
+ lastSent: now,
145
+ dataLogon: message.DETAILS ?? {},
146
+ });
89
147
  }
90
148
 
91
- reply(requestMessage: GenesisMessage, payload: Row): void {
92
- this.send({ ...payload, SOURCE_REF: requestMessage.SOURCE_REF });
149
+ // A verbose HEARTBEAT_PONG's RESOURCES: the live subscriptions by resource
150
+ // name (FullDuplexClientHandler.kt:60-66 @v8.15.29), each a serialized
151
+ // DataserverResource.
152
+ dataserverResources(): Record<string, Row[]> {
153
+ const resources: Record<string, Row[]> = {};
154
+ for (const [sourceRef, subscription] of this.subscriptions) {
155
+ const stats = this.subscriptionStats.get(subscription);
156
+ if (!stats) continue;
157
+ (resources[subscription.resourceName] ??= []).push({
158
+ NAME: subscription.resourceName,
159
+ CREATED_AT: stats.createdAt,
160
+ LAST_RECEIVED: stats.lastReceived,
161
+ LAST_SENT: stats.lastSent,
162
+ SOURCE_REF: sourceRef,
163
+ DATA_LOGON: stats.dataLogon,
164
+ });
165
+ }
166
+ return resources;
93
167
  }
94
168
 
95
169
  subscribe(sourceRef: string, subscription: Subscription): void {
@@ -60,3 +60,28 @@ export function subscriptionAlreadyExistsNack(): Row {
60
60
  'Subscription exists for source ref. If using HTTP, try HTTP GET instead of HTTP POST',
61
61
  );
62
62
  }
63
+
64
+ const HTTP_UNAUTHORIZED = 401;
65
+ const HTTP_FORBIDDEN = 403;
66
+
67
+ // A cookie-authenticated router refuses EVENT_LOGIN_AUTH and EVENT_LOGOUT on
68
+ // a socket, which the cookie already authenticates (genesis-router
69
+ // WebsocketHandler.kt:54-58 @v8.15.29). Recorded in ws-login.json and
70
+ // ws-logout.json.
71
+ export function websocketForbiddenNack(messageType: string): Row {
72
+ return routerNack(HTTP_FORBIDDEN, 'Forbidden', `Unable to call ${messageType} via websocket`);
73
+ }
74
+
75
+ // An HTTP request that needs a session but names none (AuthModel.kt:134-137
76
+ // @v8.15.29), or names one that is not live (genesis-commons ErrorMessage
77
+ // INVALID_AUTH_TOKEN_MSG). Sent with HTTP status 401; recorded in
78
+ // http-login-failed.json and http-login.json.
79
+ export function notLoggedInNack(tokenSupplied: boolean): Row {
80
+ return routerNack(
81
+ HTTP_UNAUTHORIZED,
82
+ 'Unauthorized',
83
+ tokenSupplied
84
+ ? 'User is not logged in and supplied auth token is invalid.'
85
+ : 'This request needs the user to be logged in, but the current authentication status is logged out',
86
+ );
87
+ }