@genesislcap/mock-server 15.7.3-alpha-e7d4aa5.0 → 15.32.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.
package/dist/server.js CHANGED
@@ -23,36 +23,66 @@ export function createMockServer(config) {
23
23
  // predicate would evaluate against missing fields and drop the push —
24
24
  // leaving the client holding a ghost row. Deliver every DELETE instead: a
25
25
  // client that never held that ROW_REF ignores it.
26
- function subscriptionAccepts(subscription, sourceRef, operation, row) {
27
- if (operation === 'DELETE')
28
- return true;
26
+ // 'error' is kept distinct from 'no-match' because only a clean no-match may
27
+ // be turned into a DELETE below; a broken predicate must not evict rows.
28
+ function evaluateSubscription(subscription, sourceRef, row) {
29
29
  try {
30
- return subscription.predicate(row);
30
+ return subscription.predicate(row) ? 'match' : 'no-match';
31
31
  }
32
32
  catch (error) {
33
33
  console.error(`[mock-server] Error evaluating predicate for subscription ${sourceRef}:`, error);
34
- return false;
34
+ return 'error';
35
35
  }
36
36
  }
37
+ // The operation to push to one subscription, or null to skip it entirely.
38
+ // A MODIFY that moved the row out of this subscription's CRITERIA_MATCH
39
+ // becomes a DELETE so the client drops it rather than keeping a stale ghost
40
+ // row; a predicate that threw skips instead, since a broken filter must
41
+ // never evict rows.
42
+ function resolveSubscriptionOperation(subscription, sourceRef, operation, row) {
43
+ if (operation === 'DELETE')
44
+ return 'DELETE';
45
+ const verdict = evaluateSubscription(subscription, sourceRef, row);
46
+ if (verdict === 'match')
47
+ return operation;
48
+ if (verdict === 'error')
49
+ return null;
50
+ return operation === 'MODIFY' ? 'DELETE' : null;
51
+ }
37
52
  const broadcast = (resourceName, operation, row) => {
38
53
  const query = config.queries?.[resourceName];
39
54
  // The query's own filter (where-clause equivalent) applies to live pushes
40
55
  // too — a row the snapshot would exclude must not leak in via broadcast.
41
- // DELETEs always go through: dropping an unknown ROW_REF is a no-op
42
- // client-side, while a swallowed DELETE leaves a ghost row.
43
- if (operation !== 'DELETE' && query?.filter && !query.filter(row))
44
- return;
56
+ // A MODIFY that moves a row OUT of the filter is converted to a DELETE
57
+ // rather than dropped: a swallowed removal leaves the client rendering the
58
+ // row with its stale pre-modify values until a full reload. An INSERT
59
+ // outside the filter is simply dropped (the client never held it).
60
+ // DELETEs always go through: dropping an unknown ROW_REF is a no-op.
61
+ let effectiveOperation = operation;
62
+ if (operation !== 'DELETE' && query?.filter && !query.filter(row)) {
63
+ if (operation !== 'MODIFY')
64
+ return;
65
+ effectiveOperation = 'DELETE';
66
+ }
45
67
  for (const connection of connections) {
46
68
  for (const [sourceRef, subscription] of connection.subscriptions) {
47
69
  if (subscription.resourceName !== resourceName)
48
70
  continue;
49
- if (!subscriptionAccepts(subscription, sourceRef, operation, row))
71
+ const rowOperation = resolveSubscriptionOperation(subscription, sourceRef, effectiveOperation, row);
72
+ if (rowOperation === null)
50
73
  continue;
51
74
  // Per-user permissioning (auth maps / hideFields equivalent): the
52
75
  // ROW_REF is computed from the unstripped row, since pk fields may
53
76
  // themselves be hidden from this user.
77
+ const rowRef = subscription.getRowRef(row);
54
78
  let outRow = row;
55
- if (operation !== 'DELETE' && query?.auth) {
79
+ if (rowOperation !== operation) {
80
+ // Converted to a DELETE: send the row identity only — it is all the
81
+ // client needs to drop the row, and the full row may carry columns
82
+ // this user's hideFields strips.
83
+ outRow = query ? store.rowStubFromKey(query.source, rowRef) : row;
84
+ }
85
+ else if (rowOperation !== 'DELETE' && query?.auth) {
56
86
  const [permitted] = applyResourceAuth([row], query.auth, requestingUser(connection));
57
87
  if (!permitted)
58
88
  continue;
@@ -62,7 +92,7 @@ export function createMockServer(config) {
62
92
  connection.send({
63
93
  MESSAGE_TYPE: 'QUERY_UPDATE',
64
94
  SOURCE_REF: sourceRef,
65
- ROW: [stampRow(outRow, subscription.getRowRef(row), operation)],
95
+ ROW: [stampRow(outRow, rowRef, rowOperation)],
66
96
  ROWS_COUNT: 1,
67
97
  SEQUENCE_ID: subscription.sequenceId,
68
98
  });
@@ -80,8 +110,24 @@ export function createMockServer(config) {
80
110
  const isDirect = query.source === tableName;
81
111
  const view = store.views.get(query.source);
82
112
  const isViewOnTable = view?.base === tableName;
83
- if (!isDirect && !isViewOnTable)
113
+ // A view that JOINS (or anti-joins) the mutated table denormalizes its
114
+ // columns into every matching base row, so one change can affect any
115
+ // number of view rows — none of them keyed by `pk`. Re-materialize and
116
+ // push the refreshed view instead of dropping the change, or e.g.
117
+ // renaming a COUNTERPARTY never updates COUNTERPARTY_NAME in an open
118
+ // ALL_TRADES grid.
119
+ const isViewJoiningTable = !isDirect &&
120
+ !isViewOnTable &&
121
+ ((view?.joins ?? []).some((join) => join.table === tableName) ||
122
+ (view?.antiJoins ?? []).some((antiJoin) => antiJoin.table === tableName));
123
+ if (!isDirect && !isViewOnTable && !isViewJoiningTable)
124
+ continue;
125
+ if (isViewJoiningTable) {
126
+ for (const viewRow of store.getViewRows(query.source)) {
127
+ broadcast(queryName, 'MODIFY', viewRow);
128
+ }
84
129
  continue;
130
+ }
85
131
  let row;
86
132
  if (operation === 'DELETE') {
87
133
  const stub = store.rowStubFromKey(query.source, pk);
@@ -234,7 +280,15 @@ export function createMockServer(config) {
234
280
  }
235
281
  function stop() {
236
282
  return new Promise((resolve) => {
237
- if (!wss || !httpServer) {
283
+ // Release the handles up front: a closed http.Server can never emit
284
+ // 'listening' again, so leaving them set makes a later listen() wait
285
+ // forever instead of starting a fresh server (restart-between-tests
286
+ // harnesses deadlock with no error).
287
+ const socketServer = wss;
288
+ const server = httpServer;
289
+ wss = undefined;
290
+ httpServer = undefined;
291
+ if (!socketServer || !server) {
238
292
  resolve();
239
293
  return;
240
294
  }
@@ -243,12 +297,12 @@ export function createMockServer(config) {
243
297
  // — so with a browser still attached, a plain close chain never resolves
244
298
  // (and the showcase's SIGINT handler would hang forever). Terminate WS
245
299
  // clients and drop idle keep-alive HTTP sockets explicitly first.
246
- for (const client of wss.clients)
300
+ for (const client of socketServer.clients)
247
301
  client.terminate();
248
- wss.close(() => {
249
- httpServer.close(() => resolve());
302
+ socketServer.close(() => {
303
+ server.close(() => resolve());
250
304
  // Node >=18.2; optional-called because Bun's node:http may lack it.
251
- httpServer.closeAllConnections?.();
305
+ server.closeAllConnections?.();
252
306
  });
253
307
  });
254
308
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@genesislcap/mock-server",
3
- "version": "15.7.3-alpha-e7d4aa5.0",
3
+ "version": "15.32.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",
@@ -42,6 +42,5 @@
42
42
  },
43
43
  "publishConfig": {
44
44
  "access": "public"
45
- },
46
- "gitHead": "47329b0160faf49d52b2964ea22ed9362f275130"
45
+ }
47
46
  }
@@ -121,6 +121,28 @@ const EXPR_FUNCTIONS: Record<
121
121
  }
122
122
  return typeof value === 'string' && value.toLowerCase().includes(lowered);
123
123
  },
124
+ // Groovy/Java String methods the client emits in the FIELD.method(args)
125
+ // form — e.g. pbc-notify-ui's inbox subscribes with
126
+ // `((ALERT_STATUS.equals("NEW")))`. Without these the criteria fails to
127
+ // compile, the filter is dropped, and the grid shows every row instead of
128
+ // the filtered set.
129
+ equals: (record, args, resolve) => resolve(args[0], record) === resolve(args[1], record),
130
+ equalsIgnoreCase: (record, args, resolve) => {
131
+ const value = resolve(args[0], record);
132
+ const other = resolve(args[1], record);
133
+ if (typeof value !== 'string' || typeof other !== 'string') return value === other;
134
+ return value.toLowerCase() === other.toLowerCase();
135
+ },
136
+ startsWith: (record, args, resolve) => {
137
+ const value = resolve(args[0], record);
138
+ const prefix = resolve(args[1], record);
139
+ return typeof value === 'string' && typeof prefix === 'string' && value.startsWith(prefix);
140
+ },
141
+ endsWith: (record, args, resolve) => {
142
+ const value = resolve(args[0], record);
143
+ const suffix = resolve(args[1], record);
144
+ return typeof value === 'string' && typeof suffix === 'string' && value.endsWith(suffix);
145
+ },
124
146
  dateIsToday: (record, args, resolve) => {
125
147
  const day = toEpochDay(resolve(args[0], record));
126
148
  return day !== null && day === toEpochDay(Date.now());
package/src/db/store.ts CHANGED
@@ -71,6 +71,21 @@ export class Store {
71
71
  return this;
72
72
  }
73
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
+
74
89
  nextSequenceValue(sequencePrefix: string, width: number): string {
75
90
  const n = this.sequenceCounters.get(sequencePrefix) ?? 1;
76
91
  this.sequenceCounters.set(sequencePrefix, n + 1);
@@ -139,15 +154,24 @@ export class Store {
139
154
  `Primary key field(s) '${missing.join("', '")}' are required for inserting into table '${tableName}'`,
140
155
  );
141
156
  }
157
+ this.observeSequenceValue(config, row);
142
158
  table.set(keyFor(config.pkFields, row), row);
143
159
  return row;
144
160
  }
145
161
 
146
162
  updateRow(tableName: string, pk: Pk, patch: Row): Row | undefined {
147
163
  const table = this.tables.get(tableName);
148
- if (!table || !table.has(pk)) return undefined;
164
+ const config = this.tableConfig.get(tableName);
165
+ if (!table || !config || !table.has(pk)) return undefined;
149
166
  const updated = { ...table.get(pk), ...patch };
150
- 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);
151
175
  return updated;
152
176
  }
153
177
 
@@ -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
  }
@@ -2,8 +2,8 @@ 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
7
  import { applyResourceAuth, requestingUser } from './resourceAuth.ts';
8
8
 
9
9
  // DATA_LOGON opens a persistent subscription keyed by SOURCE_REF: reply with an
@@ -36,7 +36,16 @@ export function handleDataLogon(
36
36
  let rows = store.getResourceRows(query.source);
37
37
  if (query.filter) rows = rows.filter(query.filter);
38
38
  rows = filterByCriteria(rows, criteria);
39
- rows = applyResourceAuth(rows, query.auth, user);
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
+ }
40
49
 
41
50
  connection.subscribe(message.SOURCE_REF!, {
42
51
  resourceName,
@@ -47,8 +56,8 @@ export function handleDataLogon(
47
56
 
48
57
  connection.reply(message, {
49
58
  MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE,
50
- ROW: stampRows(rows, (row) => store.getRowRef(query.source, row), 'INSERT'),
51
- ROWS_COUNT: rows.length,
59
+ ROW: stampedRows,
60
+ ROWS_COUNT: stampedRows.length,
52
61
  SEQUENCE_ID: 1,
53
62
  MORE_ROWS: false,
54
63
  });
@@ -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.
@@ -165,7 +176,7 @@ export function createHttpRequestListener(
165
176
  // honor it only if the request already carries a known session.
166
177
  const user =
167
178
  details.USER_NAME !== undefined
168
- ? findUser(config, details.USER_NAME, details.PASSWORD)
179
+ ? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
169
180
  : findUser(config, sessions.get(cookies[SESSION_COOKIE]));
170
181
 
171
182
  if (!user) {
@@ -193,7 +204,10 @@ export function createHttpRequestListener(
193
204
 
194
205
  if (req.method === 'POST' && pathname.endsWith('event-logout')) {
195
206
  const cookies = parseCookies(req.headers.cookie);
196
- 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);
197
211
  sendJson(res, HTTP_STATUS.OK, { MESSAGE_TYPE: 'LOGOUT_ACK' });
198
212
  return;
199
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, {
package/src/launch.ts CHANGED
@@ -25,6 +25,10 @@ export interface LaunchStackOptions {
25
25
  // Default true: stop the mock server when the client exits, and terminate
26
26
  // the client on SIGINT/SIGTERM — one Ctrl+C tears the whole pair down.
27
27
  tieLifetimes?: boolean;
28
+ // How long the client tree gets to exit on SIGINT before it is SIGKILLed.
29
+ // Defaults to CLIENT_EXIT_GRACE_MS; lower it in tests, or raise it for a
30
+ // client that needs longer to flush.
31
+ clientExitGraceMs?: number;
28
32
  }
29
33
 
30
34
  export interface LaunchedStack {
@@ -38,8 +42,78 @@ export interface LaunchedStack {
38
42
  stop(): Promise<void>;
39
43
  }
40
44
 
45
+ // How long a client gets to exit on SIGINT before it is killed outright. A dev
46
+ // server that ignores the signal must not keep its port (or hang stop()).
47
+ const CLIENT_EXIT_GRACE_MS = 5000;
48
+ // How often the watchdog checks whether the launcher is still alive.
49
+ const WATCHDOG_POLL_MS = 500;
50
+
51
+ // Signals the client tree, not just the direct child. The client command is
52
+ // normally a launcher itself (genx -> vite -> esbuild), so signalling only the
53
+ // immediate pid can leave grandchildren holding the port. `detached: true`
54
+ // makes the child a process-group leader, and a negative pid addresses that
55
+ // whole group.
56
+ function killClientTree(client: ChildProcess, signal: NodeJS.Signals): void {
57
+ if (client.pid === undefined || client.exitCode !== null || client.signalCode !== null) return;
58
+ try {
59
+ process.kill(-client.pid, signal);
60
+ } catch {
61
+ // No process group (Windows, or the group is already gone) — fall back to
62
+ // the single child.
63
+ try {
64
+ client.kill(signal);
65
+ } catch {
66
+ // Already exited between the check and the signal; nothing to do.
67
+ }
68
+ }
69
+ }
70
+
71
+ // Nothing in THIS process runs when it is SIGKILLed or dies with the terminal,
72
+ // so parent-death cleanup cannot live here: the client would be reparented to
73
+ // init and keep serving its port forever (verified — a hard-killed launcher
74
+ // leaves vite listening). This tiny detached watcher polls for the launcher
75
+ // and takes the client's process group down with it. It also exits as soon as
76
+ // the client is gone, so it can never outlive the pair it is watching.
77
+ const WATCHDOG_SOURCE = `
78
+ const [launcher, target] = process.argv.slice(1).map(Number);
79
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
80
+ const stop = (sig) => { try { process.kill(-target, sig); } catch { try { process.kill(target, sig); } catch {} } };
81
+ const timer = setInterval(() => {
82
+ if (!alive(target)) { clearInterval(timer); process.exit(0); }
83
+ if (alive(launcher)) return;
84
+ clearInterval(timer);
85
+ stop('SIGTERM');
86
+ setTimeout(() => { stop('SIGKILL'); process.exit(0); }, ${CLIENT_EXIT_GRACE_MS});
87
+ }, ${WATCHDOG_POLL_MS});
88
+ `;
89
+
90
+ function startWatchdog(clientPid: number): ChildProcess | undefined {
91
+ try {
92
+ const watchdog = spawn(
93
+ process.execPath,
94
+ ['-e', WATCHDOG_SOURCE, String(process.pid), String(clientPid)],
95
+ { detached: true, stdio: 'ignore' },
96
+ );
97
+ // Detached + unref'd so it survives a hard kill of this process and never
98
+ // holds this process's event loop open.
99
+ watchdog.unref();
100
+ return watchdog;
101
+ } catch (error) {
102
+ console.warn('[mock-server] Could not start the client watchdog:', error);
103
+ return undefined;
104
+ }
105
+ }
106
+
41
107
  export async function launchStack(options: LaunchStackOptions): Promise<LaunchedStack> {
42
- const { config, clientCommand, port = 0, cwd, clientEnv, tieLifetimes = true } = options;
108
+ const {
109
+ config,
110
+ clientCommand,
111
+ port = 0,
112
+ cwd,
113
+ clientEnv,
114
+ tieLifetimes = true,
115
+ clientExitGraceMs = CLIENT_EXIT_GRACE_MS,
116
+ } = options;
43
117
 
44
118
  const server = createMockServer(config);
45
119
  const boundPort = await server.listen(port);
@@ -49,46 +123,97 @@ export async function launchStack(options: LaunchStackOptions): Promise<Launched
49
123
  API_HOST: `ws://localhost:${boundPort}`,
50
124
  ...clientEnv?.(boundPort),
51
125
  };
126
+ // detached: the client leads its own process group so the whole tree can be
127
+ // signalled at once. It also means a terminal Ctrl+C no longer reaches the
128
+ // client directly — it reaches this process, whose SIGINT handler below
129
+ // tears the group down, so shutdown always takes one controlled path.
52
130
  const client = Array.isArray(clientCommand)
53
- ? spawn(clientCommand[0], clientCommand.slice(1), { cwd, env, stdio: 'inherit' })
54
- : spawn(clientCommand, { cwd, env, stdio: 'inherit', shell: true });
131
+ ? spawn(clientCommand[0], clientCommand.slice(1), {
132
+ cwd,
133
+ env,
134
+ stdio: 'inherit',
135
+ detached: true,
136
+ })
137
+ : spawn(clientCommand, { cwd, env, stdio: 'inherit', shell: true, detached: true });
138
+
139
+ const watchdog = tieLifetimes && client.pid !== undefined ? startWatchdog(client.pid) : undefined;
140
+
141
+ function cleanupWatchdog(): void {
142
+ if (watchdog?.pid === undefined) return;
143
+ try {
144
+ process.kill(watchdog.pid, 'SIGKILL');
145
+ } catch {
146
+ // Already exited on noticing the client was gone.
147
+ }
148
+ }
149
+
150
+ // Resolves once the client tree is actually down, so stop() means everything
151
+ // is stopped rather than merely signalled.
152
+ function stopClient(): Promise<void> {
153
+ if (client.pid === undefined || client.exitCode !== null || client.signalCode !== null) {
154
+ return Promise.resolve();
155
+ }
156
+ return new Promise((resolve) => {
157
+ const escalate = setTimeout(() => killClientTree(client, 'SIGKILL'), clientExitGraceMs);
158
+ client.once('exit', () => {
159
+ clearTimeout(escalate);
160
+ resolve();
161
+ });
162
+ killClientTree(client, 'SIGINT');
163
+ });
164
+ }
55
165
 
56
166
  let stopping = false;
57
167
  async function stop(): Promise<void> {
58
168
  if (stopping) return;
59
169
  stopping = true;
60
- if (client.exitCode === null && !client.killed) client.kill('SIGINT');
61
- await server.stop();
170
+ removeSignalHandlers();
171
+ cleanupWatchdog();
172
+ await Promise.all([stopClient(), server.stop()]);
62
173
  }
63
174
 
64
175
  const clientExited = new Promise<number | null>((resolve) => {
65
- client.once('exit', (code) => {
66
- const finish = () => resolve(code);
67
- if (tieLifetimes) {
68
- stopping = true;
69
- server.stop().then(finish, finish);
70
- } else {
71
- finish();
176
+ const settle = (code: number | null) => {
177
+ if (!tieLifetimes) {
178
+ resolve(code);
179
+ return;
72
180
  }
73
- });
181
+ stopping = true;
182
+ removeSignalHandlers();
183
+ cleanupWatchdog();
184
+ const finish = () => resolve(code);
185
+ server.stop().then(finish, finish);
186
+ };
187
+ client.once('exit', (code) => settle(code));
74
188
  client.once('error', (error) => {
75
189
  console.error('[mock-server] Failed to spawn client command:', error);
76
- const finish = () => resolve(null);
77
- if (tieLifetimes) {
78
- stopping = true;
79
- server.stop().then(finish, finish);
80
- } else {
81
- finish();
82
- }
190
+ settle(null);
83
191
  });
84
192
  });
85
193
 
194
+ // Every path this process can still observe tears the client group down.
195
+ // SIGHUP matters for a closing terminal; 'exit' catches a plain return or an
196
+ // uncaught throw. (A SIGKILL of this process runs none of them — that is
197
+ // what the watchdog above is for.)
198
+ const onSignal = () => {
199
+ void stop();
200
+ };
201
+ const onExit = () => {
202
+ // Synchronous only: no async work runs during 'exit'.
203
+ cleanupWatchdog();
204
+ killClientTree(client, 'SIGKILL');
205
+ };
206
+ function removeSignalHandlers(): void {
207
+ process.off('SIGINT', onSignal);
208
+ process.off('SIGTERM', onSignal);
209
+ process.off('SIGHUP', onSignal);
210
+ process.off('exit', onExit);
211
+ }
86
212
  if (tieLifetimes) {
87
- const onSignal = () => {
88
- void stop();
89
- };
90
- process.once('SIGINT', onSignal);
91
- process.once('SIGTERM', onSignal);
213
+ process.on('SIGINT', onSignal);
214
+ process.on('SIGTERM', onSignal);
215
+ process.on('SIGHUP', onSignal);
216
+ process.on('exit', onExit);
92
217
  }
93
218
 
94
219
  return { server, port: boundPort, client, clientExited, stop };
@@ -21,6 +21,7 @@ export class Connection {
21
21
  readonly id = crypto.randomUUID();
22
22
  authenticated = false;
23
23
  sessionAuthToken: string | undefined;
24
+ refreshAuthToken: string | undefined;
24
25
  sessionId: string | undefined;
25
26
  userName: string | undefined;
26
27
  profile: string[] = [];
@@ -98,7 +98,7 @@ export function routeMessage(
98
98
  case MESSAGE_TYPE.EVENT_LOGIN_AUTH:
99
99
  return handleLogin(message, connection, config, tokens);
100
100
  case MESSAGE_TYPE.EVENT_LOGOUT:
101
- return handleLogout(message, connection);
101
+ return handleLogout(message, connection, tokens);
102
102
  case MESSAGE_TYPE.HEARTBEAT_PING:
103
103
  return handleHeartbeat(message, connection, config);
104
104
  case MESSAGE_TYPE.DATA_LOGON: