@genesislcap/mock-server 15.7.3-alpha-94532c4.0 → 15.31.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 (72) hide show
  1. package/README.md +246 -40
  2. package/dist/db/criteria.d.ts +5 -0
  3. package/dist/db/criteria.js +327 -0
  4. package/dist/db/metadata.d.ts +3 -0
  5. package/dist/db/metadata.js +35 -0
  6. package/dist/db/store.d.ts +28 -0
  7. package/dist/db/store.js +254 -0
  8. package/dist/handlers/auth.d.ts +10 -0
  9. package/dist/handlers/auth.js +121 -0
  10. package/dist/handlers/commitEvent.d.ts +8 -0
  11. package/dist/handlers/commitEvent.js +40 -0
  12. package/dist/handlers/dataLogon.d.ts +5 -0
  13. package/dist/handlers/dataLogon.js +56 -0
  14. package/dist/handlers/heartbeat.d.ts +3 -0
  15. package/dist/handlers/heartbeat.js +16 -0
  16. package/dist/handlers/http.d.ts +4 -0
  17. package/dist/handlers/http.js +179 -0
  18. package/dist/handlers/jsonSchema.d.ts +5 -0
  19. package/dist/handlers/jsonSchema.js +94 -0
  20. package/dist/handlers/meta.d.ts +4 -0
  21. package/dist/handlers/meta.js +42 -0
  22. package/dist/handlers/requestReply.d.ts +4 -0
  23. package/dist/handlers/requestReply.js +68 -0
  24. package/dist/handlers/resourceAuth.d.ts +5 -0
  25. package/dist/handlers/resourceAuth.js +27 -0
  26. package/dist/handlers/resources.d.ts +3 -0
  27. package/dist/handlers/resources.js +34 -0
  28. package/dist/index.d.ts +6 -0
  29. package/dist/index.js +5 -0
  30. package/dist/launch.d.ts +20 -0
  31. package/dist/launch.js +164 -0
  32. package/dist/protocol/connection.d.ts +25 -0
  33. package/dist/protocol/connection.js +36 -0
  34. package/dist/protocol/errors.d.ts +17 -0
  35. package/dist/protocol/errors.js +16 -0
  36. package/dist/protocol/messageTypes.d.ts +28 -0
  37. package/dist/protocol/messageTypes.js +42 -0
  38. package/dist/protocol/router.d.ts +6 -0
  39. package/dist/protocol/router.js +101 -0
  40. package/dist/protocol/rowUpdate.d.ts +4 -0
  41. package/dist/protocol/rowUpdate.js +17 -0
  42. package/dist/server.d.ts +23 -0
  43. package/dist/server.js +328 -0
  44. package/dist/types.d.ts +142 -0
  45. package/dist/types.js +4 -0
  46. package/package.json +16 -7
  47. package/src/db/criteria.ts +75 -21
  48. package/src/db/store.ts +126 -29
  49. package/src/handlers/auth.ts +32 -6
  50. package/src/handlers/commitEvent.ts +4 -1
  51. package/src/handlers/dataLogon.ts +23 -7
  52. package/src/handlers/heartbeat.ts +16 -3
  53. package/src/handlers/http.ts +43 -2
  54. package/src/handlers/jsonSchema.ts +21 -5
  55. package/src/handlers/meta.ts +11 -3
  56. package/src/handlers/requestReply.ts +22 -8
  57. package/src/handlers/resourceAuth.ts +37 -0
  58. package/src/handlers/resources.ts +8 -1
  59. package/src/index.ts +9 -0
  60. package/src/launch.ts +220 -0
  61. package/src/protocol/connection.ts +4 -1
  62. package/src/protocol/router.ts +2 -2
  63. package/src/protocol/rowUpdate.ts +5 -4
  64. package/src/server.ts +150 -22
  65. package/src/types.ts +124 -3
  66. package/license.txt +0 -46
  67. package/test/criteria.test.ts +0 -174
  68. package/test/jsonSchema.test.ts +0 -38
  69. package/test/metadata.test.ts +0 -49
  70. package/test/server.test.ts +0 -308
  71. package/test/store.test.ts +0 -181
  72. package/tsconfig.json +0 -18
package/src/db/store.ts CHANGED
@@ -6,11 +6,25 @@ import type { Row, TableDef, ViewDef } from '../types.ts';
6
6
  type Pk = string;
7
7
 
8
8
  interface TableConfig {
9
- pkField: string;
9
+ pkFields: string[];
10
10
  sequencePrefix?: string;
11
11
  sequenceWidth: number;
12
12
  }
13
13
 
14
+ // Composite keys join the pk fields' values with '|' (so values must not
15
+ // contain '|'). Single-field keys stay the raw value, preserving
16
+ // getRow('TABLE', 'TR001')-style lookups.
17
+ const COMPOSITE_KEY_SEPARATOR = '|';
18
+
19
+ function normalizePkFields(pkField: string | string[]): string[] {
20
+ return Array.isArray(pkField) ? pkField : [pkField];
21
+ }
22
+
23
+ function keyFor(pkFields: string[], row: Row): Pk {
24
+ if (pkFields.length === 1) return row[pkFields[0]];
25
+ return pkFields.map((field) => String(row[field])).join(COMPOSITE_KEY_SEPARATOR);
26
+ }
27
+
14
28
  export class Store {
15
29
  private tables = new Map<string, Map<Pk, Row>>();
16
30
  private tableConfig = new Map<string, TableConfig>();
@@ -25,21 +39,23 @@ export class Store {
25
39
  tableName: string,
26
40
  { pkField, sequencePrefix, sequenceWidth = 3, rows = [] }: TableDef,
27
41
  ): this {
42
+ const pkFields = normalizePkFields(pkField);
28
43
  const table = new Map<Pk, Row>();
29
44
  for (const row of rows) {
30
- table.set(row[pkField], { ...row });
45
+ table.set(keyFor(pkFields, row), { ...row });
31
46
  }
32
47
  this.tables.set(tableName, table);
33
- this.tableConfig.set(tableName, { pkField, sequencePrefix, sequenceWidth });
48
+ this.tableConfig.set(tableName, { pkFields, sequencePrefix, sequenceWidth });
34
49
  this.seedRows.set(
35
50
  tableName,
36
51
  rows.map((row) => ({ ...row })),
37
52
  );
38
53
 
39
- if (sequencePrefix) {
54
+ // Sequence generation only makes sense for a single-field pk.
55
+ if (sequencePrefix && pkFields.length === 1) {
40
56
  let maxN = 0;
41
57
  for (const row of rows) {
42
- const pk = String(row[pkField] ?? '');
58
+ const pk = String(row[pkFields[0]] ?? '');
43
59
  if (pk.startsWith(sequencePrefix)) {
44
60
  const n = parseInt(pk.slice(sequencePrefix.length), 10);
45
61
  if (Number.isFinite(n)) maxN = Math.max(maxN, n);
@@ -55,6 +71,21 @@ export class Store {
55
71
  return this;
56
72
  }
57
73
 
74
+ // An explicitly-supplied pk inside the sequence's own range must advance the
75
+ // counter too. Without this, inserting e.g. 'TR002' by hand leaves the
76
+ // counter at 2, and the next auto-generated insert mints 'TR002' again and
77
+ // silently overwrites the hand-keyed row (Map.set, no error, event still
78
+ // acks success).
79
+ private observeSequenceValue(config: TableConfig, row: Row): void {
80
+ if (!config.sequencePrefix || config.pkFields.length !== 1) return;
81
+ const pk = String(row[config.pkFields[0]] ?? '');
82
+ if (!pk.startsWith(config.sequencePrefix)) return;
83
+ const n = parseInt(pk.slice(config.sequencePrefix.length), 10);
84
+ if (!Number.isFinite(n)) return;
85
+ const next = this.sequenceCounters.get(config.sequencePrefix) ?? 1;
86
+ if (n + 1 > next) this.sequenceCounters.set(config.sequencePrefix, n + 1);
87
+ }
88
+
58
89
  nextSequenceValue(sequencePrefix: string, width: number): string {
59
90
  const n = this.sequenceCounters.get(sequencePrefix) ?? 1;
60
91
  this.sequenceCounters.set(sequencePrefix, n + 1);
@@ -71,16 +102,26 @@ export class Store {
71
102
  return this.tables.get(tableName)?.get(pk);
72
103
  }
73
104
 
74
- // Fallback matching for composite-key tables where no single field is a stable
75
- // identifier: try ROW_REF/pk field first, then any single field that uniquely
76
- // identifies one row, then the full combination of provided fields.
105
+ // The storage/broadcast key for a row: the pk field's value, or for
106
+ // composite-keyed tables the pk fields' values joined with '|'. Event
107
+ // handlers on composite tables pass this to broadcastTableChange.
108
+ rowKey(tableName: string, row: Row): Pk {
109
+ const config = this.tableConfig.get(tableName);
110
+ if (!config) throw new Error(`Unknown table: ${tableName}`);
111
+ return keyFor(config.pkFields, row);
112
+ }
113
+
114
+ // Fallback matching for tables where the caller doesn't have the full key:
115
+ // try the pk field(s) first, then any single field that uniquely identifies
116
+ // one row, then the full combination of provided fields.
77
117
  findRow(tableName: string, criteria: Row): Row | undefined {
78
118
  const table = this.tables.get(tableName);
79
119
  if (!table) return undefined;
80
- const { pkField } = this.tableConfig.get(tableName) ?? {};
120
+ const { pkFields } = this.tableConfig.get(tableName) ?? { pkFields: [] };
81
121
 
82
- if (pkField && criteria[pkField] !== undefined) {
83
- return table.get(criteria[pkField]);
122
+ if (pkFields.length > 0 && pkFields.every((field) => criteria[field] !== undefined)) {
123
+ const byKey = table.get(keyFor(pkFields, criteria));
124
+ if (byKey) return byKey;
84
125
  }
85
126
 
86
127
  const rows = Array.from(table.values());
@@ -100,23 +141,37 @@ export class Store {
100
141
  if (!table || !config) throw new Error(`Unknown table: ${tableName}`);
101
142
 
102
143
  const row = { ...record };
103
- if (row[config.pkField] === undefined && config.sequencePrefix) {
104
- row[config.pkField] = this.nextSequenceValue(config.sequencePrefix, config.sequenceWidth);
144
+ if (
145
+ config.pkFields.length === 1 &&
146
+ row[config.pkFields[0]] === undefined &&
147
+ config.sequencePrefix
148
+ ) {
149
+ row[config.pkFields[0]] = this.nextSequenceValue(config.sequencePrefix, config.sequenceWidth);
105
150
  }
106
- if (row[config.pkField] === undefined) {
151
+ const missing = config.pkFields.filter((field) => row[field] === undefined);
152
+ if (missing.length > 0) {
107
153
  throw new Error(
108
- `Primary key '${config.pkField}' is required for inserting into table '${tableName}'`,
154
+ `Primary key field(s) '${missing.join("', '")}' are required for inserting into table '${tableName}'`,
109
155
  );
110
156
  }
111
- table.set(row[config.pkField], row);
157
+ this.observeSequenceValue(config, row);
158
+ table.set(keyFor(config.pkFields, row), row);
112
159
  return row;
113
160
  }
114
161
 
115
162
  updateRow(tableName: string, pk: Pk, patch: Row): Row | undefined {
116
163
  const table = this.tables.get(tableName);
117
- if (!table || !table.has(pk)) return undefined;
164
+ const config = this.tableConfig.get(tableName);
165
+ if (!table || !config || !table.has(pk)) return undefined;
118
166
  const updated = { ...table.get(pk), ...patch };
119
- table.set(pk, updated);
167
+ // A patch that changes a pk field (e.g. an entity-management form posting
168
+ // its full DETAILS after the user edited the key column) must move the row
169
+ // to its new key. Leaving it under the old one makes the index disagree
170
+ // with the row itself: getRow(newKey) misses, while rowKey()/getRowRef()
171
+ // report the new key, so the matching broadcast finds nothing to push.
172
+ const nextKey = keyFor(config.pkFields, updated);
173
+ if (nextKey !== pk) table.delete(pk);
174
+ table.set(nextKey, updated);
120
175
  return updated;
121
176
  }
122
177
 
@@ -126,7 +181,9 @@ export class Store {
126
181
  return table.delete(pk);
127
182
  }
128
183
 
129
- // Materializes a view: base table left-joined to related tables, plus derived fields.
184
+ // Materializes a view: base table left-joined to related tables (optionally
185
+ // narrowed by per-join `where` predicates), minus anti-joined rows, plus
186
+ // derived fields.
130
187
  getViewRows(viewName: string): Row[] {
131
188
  const view = this.views.get(viewName);
132
189
  if (!view) throw new Error(`Unknown view: ${viewName}`);
@@ -136,13 +193,34 @@ export class Store {
136
193
  private materializeView(view: ViewDef, getRows: (tableName: string) => Row[]): Row[] {
137
194
  let rows = getRows(view.base).map((row) => ({ ...row }));
138
195
 
196
+ for (const antiJoin of view.antiJoins ?? []) {
197
+ const joinRows = getRows(antiJoin.table);
198
+ rows = rows.filter(
199
+ (row) =>
200
+ !joinRows.some(
201
+ (joinRow) =>
202
+ joinRow[antiJoin.on[1]] === row[antiJoin.on[0]] &&
203
+ (antiJoin.where?.(joinRow, row) ?? true),
204
+ ),
205
+ );
206
+ }
207
+
139
208
  for (const join of view.joins ?? []) {
140
- const joinIndex = new Map<unknown, Row>();
141
- for (const row of getRows(join.table)) {
142
- joinIndex.set(row[join.on[1]], row);
209
+ const joinRows = getRows(join.table);
210
+ // A `where` predicate sees the base row, so an index keyed on the `on`
211
+ // field alone can't answer it — scan per base row instead.
212
+ const joinIndex = join.where ? undefined : new Map<unknown, Row>();
213
+ if (joinIndex) {
214
+ for (const row of joinRows) {
215
+ joinIndex.set(row[join.on[1]], row);
216
+ }
143
217
  }
144
218
  rows = rows.map((row) => {
145
- const match = joinIndex.get(row[join.on[0]]);
219
+ const match = joinIndex
220
+ ? joinIndex.get(row[join.on[0]])
221
+ : joinRows.find(
222
+ (joinRow) => joinRow[join.on[1]] === row[join.on[0]] && join.where!(joinRow, row),
223
+ );
146
224
  const merged = { ...row };
147
225
  for (const [alias, sourceField] of Object.entries(join.select ?? {})) {
148
226
  merged[alias] = match?.[sourceField];
@@ -184,12 +262,31 @@ export class Store {
184
262
  return this.seedRows.get(resourceName) ?? [];
185
263
  }
186
264
 
187
- // Row-identity field for a table or view, used to stamp DETAILS.ROW_REF on
188
- // QUERY_UPDATE rows (see handlers/dataLogon.ts and dataServerResultFilter.ts
189
- // client-side, which keys inserts/amends/deletes off this field).
190
- getPkField(resourceName: string): string | undefined {
265
+ // Row-identity fields for a table or view; empty when unknown.
266
+ getPkFields(resourceName: string): string[] {
191
267
  const view = this.views.get(resourceName);
192
- if (view) return view.pkField ?? this.tableConfig.get(view.base)?.pkField;
193
- return this.tableConfig.get(resourceName)?.pkField;
268
+ if (view) {
269
+ if (view.pkField) return normalizePkFields(view.pkField);
270
+ return this.tableConfig.get(view.base)?.pkFields ?? [];
271
+ }
272
+ return this.tableConfig.get(resourceName)?.pkFields ?? [];
273
+ }
274
+
275
+ // The DETAILS.ROW_REF value stamped on QUERY_UPDATE rows (see
276
+ // protocol/rowUpdate.ts): the pk field's value, or the composite key. The
277
+ // client's dataServerResultFilter keys inserts/amends/deletes off this.
278
+ getRowRef(resourceName: string, row: Row): unknown {
279
+ const pkFields = this.getPkFields(resourceName);
280
+ if (pkFields.length === 0) return undefined;
281
+ return keyFor(pkFields, row);
282
+ }
283
+
284
+ // Rebuilds a DELETE stub row carrying the pk field(s) from a stored key, so
285
+ // subscribers can be told which row to drop after it's already gone.
286
+ rowStubFromKey(resourceName: string, key: Pk): Row {
287
+ const pkFields = this.getPkFields(resourceName);
288
+ if (pkFields.length <= 1) return pkFields.length ? { [pkFields[0]]: key } : {};
289
+ const parts = String(key).split(COMPOSITE_KEY_SEPARATOR);
290
+ return Object.fromEntries(pkFields.map((field, i) => [field, parts[i]]));
194
291
  }
195
292
  }
@@ -66,14 +66,26 @@ export function buildLoginAckBody(
66
66
  };
67
67
  }
68
68
 
69
- export function findUser(
69
+ // Trusted lookup by username alone — for paths where identity is already
70
+ // established (a token this server issued, an HTTP session cookie,
71
+ // httpAutoLogin). NEVER use this for a credentials login.
72
+ export function findUser(config: MockServerConfig, username?: string): AuthUser | undefined {
73
+ if (username === undefined) return undefined;
74
+ return (config.auth?.users ?? []).find((u) => u.username === username);
75
+ }
76
+
77
+ // Credentials login: the supplied password must match the configured one. A
78
+ // missing PASSWORD is a failed login, never a username-only lookup — treating
79
+ // it as one lets any client authenticate as any configured user just by
80
+ // omitting the field, defeating auth.requireAuth and every rowFilter/
81
+ // hideFields rule built on the logged-in identity.
82
+ export function findUserByCredentials(
70
83
  config: MockServerConfig,
71
84
  username?: string,
72
85
  password?: string,
73
86
  ): AuthUser | undefined {
74
- const users = config.auth?.users ?? [];
75
- if (password === undefined) return users.find((u) => u.username === username);
76
- return users.find((u) => u.username === username && u.password === password);
87
+ const user = findUser(config, username);
88
+ return user && user.password === password ? user : undefined;
77
89
  }
78
90
 
79
91
  export function handleLogin(
@@ -95,7 +107,7 @@ export function handleLogin(
95
107
  : undefined;
96
108
  const user =
97
109
  details.USER_NAME !== undefined
98
- ? findUser(config, details.USER_NAME, details.PASSWORD)
110
+ ? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
99
111
  : findUser(config, tokenUsername);
100
112
 
101
113
  if (!user) {
@@ -120,13 +132,27 @@ export function handleLogin(
120
132
  connection.profile = user.profile ?? [];
121
133
  connection.permission = user.permission ?? [];
122
134
  connection.sessionAuthToken = ack.SESSION_AUTH_TOKEN;
135
+ connection.refreshAuthToken = ack.REFRESH_AUTH_TOKEN;
123
136
  connection.sessionId = ack.SESSION_ID;
124
137
 
125
138
  connection.reply(message, ack);
126
139
  }
127
140
 
128
- export function handleLogout(message: GenesisMessage, connection: Connection): void {
141
+ export function handleLogout(
142
+ message: GenesisMessage,
143
+ connection: Connection,
144
+ tokens: TokenRegistry,
145
+ ): void {
146
+ // Revoke this connection's tokens, not just its authenticated flag: every
147
+ // message re-adopts a stamped SESSION_AUTH_TOKEN (see router.ts), so a
148
+ // token left in the registry silently logs the connection straight back in
149
+ // on its very next request.
150
+ for (const token of [connection.sessionAuthToken, connection.refreshAuthToken]) {
151
+ if (token !== undefined) tokens.delete(token);
152
+ }
129
153
  connection.authenticated = false;
154
+ connection.sessionAuthToken = undefined;
155
+ connection.refreshAuthToken = undefined;
130
156
  connection.subscriptions.clear();
131
157
  connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.LOGOUT_ACK });
132
158
  }
@@ -26,7 +26,10 @@ export function handleCommitEvent(
26
26
  ctx: CommitEventCtx,
27
27
  ): void {
28
28
  const eventName = message.MESSAGE_TYPE;
29
- const handler = config.eventHandlers?.[eventName];
29
+ // defaultEventHandler catches anything unregistered — lets projects with
30
+ // dozens of commit events adopt incrementally (e.g. `() => ({})` to ack
31
+ // everything unhandled) instead of enumerating ack-only handlers.
32
+ const handler = config.eventHandlers?.[eventName] ?? config.defaultEventHandler;
30
33
 
31
34
  // Replies use the GENERIC EVENT_ACK/EVENT_NACK — correlation is purely via
32
35
  // SOURCE_REF. See the note on MESSAGE_TYPE in protocol/messageTypes.ts:
@@ -2,8 +2,9 @@ import { compileCriteria, filterByCriteria } from '../db/criteria.ts';
2
2
  import type { Store } from '../db/store.ts';
3
3
  import type { Connection } from '../protocol/connection.ts';
4
4
  import { MESSAGE_TYPE, ERROR_CODE } from '../protocol/messageTypes.ts';
5
- import { stampRows } from '../protocol/rowUpdate.ts';
6
- import type { GenesisMessage, MockServerConfig } from '../types.ts';
5
+ import { stampRow } from '../protocol/rowUpdate.ts';
6
+ import type { GenesisMessage, MockServerConfig, Row } from '../types.ts';
7
+ import { applyResourceAuth, requestingUser } from './resourceAuth.ts';
7
8
 
8
9
  // DATA_LOGON opens a persistent subscription keyed by SOURCE_REF: reply with an
9
10
  // initial snapshot, then keep the SOURCE_REF registered so later inserts/amends/
@@ -28,20 +29,35 @@ export function handleDataLogon(
28
29
  }
29
30
 
30
31
  const criteria = details.CRITERIA_MATCH;
31
- const pkField = store.getPkField(query.source);
32
- const rows = filterByCriteria(store.getResourceRows(query.source), criteria);
32
+ const user = requestingUser(connection);
33
+ // Order matters: the query's own filter (the where-clause equivalent) and
34
+ // the user's row permissioning narrow the set BEFORE the client's
35
+ // CRITERIA_MATCH; hidden fields are stripped last, off the final rows.
36
+ let rows = store.getResourceRows(query.source);
37
+ if (query.filter) rows = rows.filter(query.filter);
38
+ rows = filterByCriteria(rows, criteria);
39
+ // Permissioning is applied per row so the ROW_REF can still be computed from
40
+ // the UNSTRIPPED row — pk fields may themselves be hidden from this user,
41
+ // and a snapshot row with no ROW_REF can never be matched to the later
42
+ // INSERT/MODIFY/DELETE pushes (which stamp the real ref, see server.ts).
43
+ const stampedRows: Row[] = [];
44
+ for (const row of rows) {
45
+ const [permitted] = applyResourceAuth([row], query.auth, user);
46
+ if (!permitted) continue;
47
+ stampedRows.push(stampRow(permitted, store.getRowRef(query.source, row), 'INSERT'));
48
+ }
33
49
 
34
50
  connection.subscribe(message.SOURCE_REF!, {
35
51
  resourceName,
36
- pkField,
52
+ getRowRef: (row) => store.getRowRef(query.source, row),
37
53
  predicate: compileCriteria(criteria),
38
54
  sequenceId: 1,
39
55
  });
40
56
 
41
57
  connection.reply(message, {
42
58
  MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE,
43
- ROW: stampRows(rows, pkField, 'INSERT'),
44
- ROWS_COUNT: rows.length,
59
+ ROW: stampedRows,
60
+ ROWS_COUNT: stampedRows.length,
45
61
  SEQUENCE_ID: 1,
46
62
  MORE_ROWS: false,
47
63
  });
@@ -1,10 +1,23 @@
1
1
  import type { Connection } from '../protocol/connection.ts';
2
2
  import { MESSAGE_TYPE } from '../protocol/messageTypes.ts';
3
- import type { GenesisMessage } from '../types.ts';
3
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
4
4
 
5
- export function handleHeartbeat(message: GenesisMessage, connection: Connection): void {
5
+ export function handleHeartbeat(
6
+ message: GenesisMessage,
7
+ connection: Connection,
8
+ config: MockServerConfig,
9
+ ): void {
10
+ // With the auth gate off (the default), this server accepts every data
11
+ // message — so the pong must report IS_AUTHENTICATED: true even though the
12
+ // WS connection itself never "logged in". HTTP-login clients (httpAutoLogin
13
+ // included) send no SESSION_AUTH_TOKEN on WS messages, so
14
+ // connection.authenticated stays false forever on their connections; report
15
+ // that raw flag and the client treats the session as dead and tears it
16
+ // down, defeating httpAutoLogin entirely. Only when a project opts into
17
+ // auth.requireAuth does the flag reflect real connection auth state.
18
+ const requireAuth = config.auth?.requireAuth ?? false;
6
19
  connection.reply(message, {
7
20
  MESSAGE_TYPE: MESSAGE_TYPE.HEARTBEAT_PONG,
8
- IS_AUTHENTICATED: connection.authenticated,
21
+ IS_AUTHENTICATED: connection.authenticated || !requireAuth,
9
22
  });
10
23
  }
@@ -6,6 +6,7 @@ import {
6
6
  buildLoginAckBody,
7
7
  capRegistry,
8
8
  findUser,
9
+ findUserByCredentials,
9
10
  registerAckTokens,
10
11
  type TokenRegistry,
11
12
  } from './auth.ts';
@@ -64,6 +65,16 @@ async function readJsonBody(req: IncomingMessage): Promise<Record<string, any>>
64
65
  return raw ? JSON.parse(raw) : {};
65
66
  }
66
67
 
68
+ // Drops every token this server minted for `username`. Logout has to do this,
69
+ // not just forget the session: router.ts re-adopts any known SESSION_AUTH_TOKEN
70
+ // on every message, so a token left in the registry logs a WS connection
71
+ // straight back in on its next request.
72
+ function revokeTokensFor(tokens: TokenRegistry, username: string): void {
73
+ for (const [token, owner] of tokens) {
74
+ if (owner === username) tokens.delete(token);
75
+ }
76
+ }
77
+
67
78
  // Reuse the request's own session when its cookie already maps to this user —
68
79
  // otherwise every page load would mint (and leak) a fresh session entry on a
69
80
  // long-lived dev/CI server.
@@ -88,6 +99,33 @@ export function createHttpRequestListener(
88
99
  const pathname = (req.url ?? '').split('?')[0];
89
100
 
90
101
  try {
102
+ // Project-defined routes run first (see HttpRouteDef) — endpoints the
103
+ // protocol doesn't cover (e.g. GET pbi/configs), or overrides of the
104
+ // built-ins below.
105
+ const route = (config.httpRoutes ?? []).find(
106
+ (candidate) =>
107
+ (!candidate.method || candidate.method.toUpperCase() === req.method) &&
108
+ (typeof candidate.path === 'string'
109
+ ? pathname.endsWith(candidate.path)
110
+ : candidate.path.test(pathname)),
111
+ );
112
+ if (route) {
113
+ await route.handler(req, res);
114
+ return;
115
+ }
116
+
117
+ // foundation-auth's login screen fetches this whenever SSO is toggled
118
+ // on, and treats both a failed fetch and an empty IDPS list as fatal
119
+ // (red error, credentials form hidden). Serve the configured providers,
120
+ // or one non-functional placeholder so the screen still renders.
121
+ if (req.method === 'GET' && pathname.endsWith('sso/list')) {
122
+ const idps = config.auth?.ssoIdentityProviders ?? [
123
+ { ID: 'mock-sso', DESCRIPTION: 'Mock SSO (placeholder, not functional)', TYPE: 'saml' },
124
+ ];
125
+ sendJson(res, HTTP_STATUS.OK, { IDPS: idps });
126
+ return;
127
+ }
128
+
91
129
  // Cookie-based silent login on app load — auto-authenticates as the
92
130
  // configured user when config.auth.httpAutoLogin is set, so the login
93
131
  // screen never appears (matches how a real session cookie would behave
@@ -138,7 +176,7 @@ export function createHttpRequestListener(
138
176
  // honor it only if the request already carries a known session.
139
177
  const user =
140
178
  details.USER_NAME !== undefined
141
- ? findUser(config, details.USER_NAME, details.PASSWORD)
179
+ ? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
142
180
  : findUser(config, sessions.get(cookies[SESSION_COOKIE]));
143
181
 
144
182
  if (!user) {
@@ -166,7 +204,10 @@ export function createHttpRequestListener(
166
204
 
167
205
  if (req.method === 'POST' && pathname.endsWith('event-logout')) {
168
206
  const cookies = parseCookies(req.headers.cookie);
169
- sessions.delete(cookies[SESSION_COOKIE]);
207
+ const sessionId = cookies[SESSION_COOKIE];
208
+ const username = sessions.get(sessionId);
209
+ sessions.delete(sessionId);
210
+ if (username !== undefined) revokeTokensFor(tokens, username);
170
211
  sendJson(res, HTTP_STATUS.OK, { MESSAGE_TYPE: 'LOGOUT_ACK' });
171
212
  return;
172
213
  }
@@ -56,7 +56,13 @@ export function inferEventTable(
56
56
  eventName: string | undefined,
57
57
  tableNames: string[],
58
58
  ): string | undefined {
59
- if (!eventName?.startsWith('EVENT_')) return undefined;
59
+ if (!eventName) return undefined;
60
+ // Not every caller asks by event name: entity-management resolves a grid's
61
+ // schema from the bare resource/table name (FEATURE: 'TRADE'), so accept an
62
+ // exact table match before requiring the EVENT_ prefix. Without this the
63
+ // request errors with UNKNOWN_RESOURCE and the form renders no fields.
64
+ if (tableNames.includes(eventName)) return eventName;
65
+ if (!eventName.startsWith('EVENT_')) return undefined;
60
66
  const rest = eventName.slice('EVENT_'.length);
61
67
  const candidates = tableNames.filter((name) => rest === name || rest.startsWith(`${name}_`));
62
68
  candidates.sort((a, b) => b.length - a.length);
@@ -71,7 +77,17 @@ export function handleJsonSchemaRequest(
71
77
  ): void {
72
78
  const eventName: string | undefined = message.DETAILS?.FEATURE;
73
79
  const override = eventName ? config.eventSchemas?.[eventName] : undefined;
74
- const table = override?.table ?? inferEventTable(eventName, Object.keys(config.tables ?? {}));
80
+ // A DATASERVER/REQUEST_SERVER resource name (e.g. 'ALL_USERS') resolves
81
+ // through its own definition to the backing table/view. The FAST-Element
82
+ // showcase's entity-management grids ask by query name, not by table or
83
+ // event name, so without this their create/update forms render empty.
84
+ const resourceSource = eventName
85
+ ? (config.queries?.[eventName]?.source ?? config.requestReplies?.[eventName]?.source)
86
+ : undefined;
87
+ const table =
88
+ override?.table ??
89
+ resourceSource ??
90
+ inferEventTable(eventName, Object.keys(config.tables ?? {}));
75
91
 
76
92
  if (!table) {
77
93
  connection.reply(message, {
@@ -82,11 +98,11 @@ export function handleJsonSchemaRequest(
82
98
  }
83
99
 
84
100
  const pkOnly = override?.pkOnly ?? DELETE_EVENT_RE.test(eventName!);
85
- const pkField = store.getPkField(table);
101
+ const pkFields = store.getPkFields(table);
86
102
  let fields = deriveFields(store.getMetadataRows(table), override?.fieldTypes);
87
- if (pkOnly) fields = fields.filter((field) => field.NAME === pkField);
103
+ if (pkOnly) fields = fields.filter((field) => pkFields.includes(field.NAME));
88
104
 
89
- const schema = buildSchema(fields, pkOnly && pkField ? [pkField] : []);
105
+ const schema = buildSchema(fields, pkOnly ? pkFields : []);
90
106
 
91
107
  connection.reply(message, {
92
108
  MESSAGE_TYPE: message.MESSAGE_TYPE,
@@ -2,7 +2,8 @@ import { deriveFields } from '../db/metadata.ts';
2
2
  import type { Store } from '../db/store.ts';
3
3
  import type { Connection } from '../protocol/connection.ts';
4
4
  import { ERROR_CODE } from '../protocol/messageTypes.ts';
5
- import type { GenesisMessage, MockServerConfig } from '../types.ts';
5
+ import type { GenesisMessage, MockServerConfig, Row } from '../types.ts';
6
+ import { hiddenFields, requestingUser } from './resourceAuth.ts';
6
7
 
7
8
  // createMetaRequestMessage (foundation-comms/src/connect/message.ts) puts the
8
9
  // resource name in DETAILS.FEATURE — not DATASOURCE_NAME/RESOURCE_NAME despite
@@ -37,8 +38,15 @@ export function handleMetaRequest(
37
38
  }
38
39
 
39
40
  const resolved = (query ?? requestReply)!;
40
- const rows = store.getMetadataRows(resolved.source);
41
- const fields = deriveFields(rows, resolved.fieldTypes);
41
+ // Resolver-only request-replies have no backing table/view — their field
42
+ // metadata comes from the def's own metadataRows sample (plus fieldTypes).
43
+ const rows: Row[] = resolved.source
44
+ ? store.getMetadataRows(resolved.source)
45
+ : (requestReply?.metadataRows ?? []);
46
+ // Hidden fields disappear from the metadata too — a column the user can't
47
+ // see must not be offered to the grid at all.
48
+ const hidden = hiddenFields(resolved.auth, requestingUser(connection));
49
+ const fields = deriveFields(rows, resolved.fieldTypes).filter((field) => !hidden.has(field.NAME));
42
50
 
43
51
  connection.reply(message, {
44
52
  MESSAGE_TYPE: message.MESSAGE_TYPE,
@@ -4,6 +4,7 @@ import type { Connection } from '../protocol/connection.ts';
4
4
  import { NackError } from '../protocol/errors.ts';
5
5
  import { ERROR_CODE } from '../protocol/messageTypes.ts';
6
6
  import type { GenesisMessage, MockServerConfig, Row } from '../types.ts';
7
+ import { applyResourceAuth, requestingUser } from './resourceAuth.ts';
7
8
 
8
9
  // Keyed lookups: foundation-comms' createRequestMessage spreads RequestParams
9
10
  // onto the message, so REQUEST is a *top-level* field ({FIELD: value} pairs
@@ -27,7 +28,7 @@ export function handleRequestReply(
27
28
  const resourceName = message.MESSAGE_TYPE.replace(/^REQ_/, '');
28
29
  const requestReply = config.requestReplies?.[resourceName];
29
30
 
30
- if (!requestReply) {
31
+ if (!requestReply || (!requestReply.resolver && !requestReply.source)) {
31
32
  connection.reply(message, {
32
33
  MESSAGE_TYPE: `REP_${resourceName}`,
33
34
  ERROR: [
@@ -40,15 +41,28 @@ export function handleRequestReply(
40
41
  return;
41
42
  }
42
43
 
44
+ const user = requestingUser(connection);
45
+ const request: Row =
46
+ (typeof message.REQUEST === 'object' && message.REQUEST) || message.DETAILS?.REQUEST || {};
47
+
43
48
  try {
44
- let rows = store.getResourceRows(requestReply.source);
45
- const request = message.REQUEST ?? message.DETAILS?.REQUEST;
46
- if (request && typeof request === 'object') {
47
- rows = rows.filter((row) => matchesRequestFields(row, request));
49
+ let rows: Row[];
50
+ if (requestReply.resolver) {
51
+ // Computed reply (date calcs, holiday roll, composite lookups...): the
52
+ // resolver owns REQUEST interpretation entirely — no generic REQUEST/
53
+ // CRITERIA filtering is applied on top, since a computed reply's rows
54
+ // needn't echo the request's fields at all.
55
+ rows = requestReply.resolver({ request, message, user, store });
56
+ } else {
57
+ rows = store.getResourceRows(requestReply.source!);
58
+ if (Object.keys(request).length > 0) {
59
+ rows = rows.filter((row) => matchesRequestFields(row, request));
60
+ }
61
+ const criteria = message.DETAILS?.CRITERIA_MATCH ?? message.CRITERIA_MATCH;
62
+ if (criteria) rows = filterByCriteria(rows, criteria);
63
+ if (requestReply.filter) rows = rows.filter(requestReply.filter);
48
64
  }
49
- const criteria = message.DETAILS?.CRITERIA_MATCH ?? message.CRITERIA_MATCH;
50
- if (criteria) rows = filterByCriteria(rows, criteria);
51
- if (requestReply.filter) rows = rows.filter(requestReply.filter);
65
+ rows = applyResourceAuth(rows, requestReply.auth, user);
52
66
 
53
67
  connection.reply(message, {
54
68
  MESSAGE_TYPE: `REP_${resourceName}`,
@@ -0,0 +1,37 @@
1
+ import type { Connection } from '../protocol/connection.ts';
2
+ import type { ResourceAuthDef, RequestingUser, Row } from '../types.ts';
3
+
4
+ // The identity a resource-level auth hook (rowFilter/hideFields) sees for the
5
+ // requesting connection. userName is undefined for unauthenticated
6
+ // connections — possible when requireAuth is off, or pre-login.
7
+ export function requestingUser(connection: Connection): RequestingUser {
8
+ return {
9
+ userName: connection.userName,
10
+ profile: connection.profile,
11
+ permission: connection.permission,
12
+ };
13
+ }
14
+
15
+ export function hiddenFields(auth: ResourceAuthDef | undefined, user: RequestingUser): Set<string> {
16
+ const fields = typeof auth?.hideFields === 'function' ? auth.hideFields(user) : auth?.hideFields;
17
+ return new Set(fields ?? []);
18
+ }
19
+
20
+ // Applies a resource's permissioning to a reply/snapshot row set: drops rows
21
+ // the user's rowFilter rejects, then strips hidden fields from what's left.
22
+ // Mirrors dataserver auth maps + hideFields on the real server.
23
+ export function applyResourceAuth(
24
+ rows: Row[],
25
+ auth: ResourceAuthDef | undefined,
26
+ user: RequestingUser,
27
+ ): Row[] {
28
+ if (!auth) return rows;
29
+ let result = auth.rowFilter ? rows.filter((row) => auth.rowFilter!(row, user)) : rows;
30
+ const hidden = hiddenFields(auth, user);
31
+ if (hidden.size > 0) {
32
+ result = result.map((row) =>
33
+ Object.fromEntries(Object.entries(row).filter(([field]) => !hidden.has(field))),
34
+ );
35
+ }
36
+ return result;
37
+ }