@genesislcap/mock-server 15.7.3-alpha-e7d4aa5.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.
- package/README.md +38 -7
- package/dist/db/criteria.js +23 -0
- package/dist/db/store.d.ts +1 -0
- package/dist/db/store.js +30 -2
- package/dist/handlers/auth.d.ts +3 -2
- package/dist/handlers/auth.js +29 -7
- package/dist/handlers/dataLogon.js +14 -4
- package/dist/handlers/http.js +17 -3
- package/dist/handlers/jsonSchema.js +19 -2
- package/dist/launch.d.ts +1 -0
- package/dist/launch.js +133 -28
- package/dist/protocol/connection.d.ts +1 -0
- package/dist/protocol/connection.js +1 -0
- package/dist/protocol/router.js +1 -1
- package/dist/server.js +72 -18
- package/package.json +2 -3
- package/src/db/criteria.ts +22 -0
- package/src/db/store.ts +26 -2
- package/src/handlers/auth.ts +32 -6
- package/src/handlers/dataLogon.ts +14 -5
- package/src/handlers/http.ts +16 -2
- package/src/handlers/jsonSchema.ts +18 -2
- package/src/launch.ts +150 -25
- package/src/protocol/connection.ts +1 -0
- package/src/protocol/router.ts +1 -1
- package/src/server.ts +82 -19
- package/license.txt +0 -46
package/README.md
CHANGED
|
@@ -12,7 +12,7 @@ All relative imports use explicit `.ts` extensions
|
|
|
12
12
|
requires the literal extension match; `allowImportingTsExtensions` keeps
|
|
13
13
|
`tsc` happy with that.
|
|
14
14
|
|
|
15
|
-
**Consumers get compiled JavaScript.** `
|
|
15
|
+
**Consumers get compiled JavaScript.** The `build` script (`tsc -p
|
|
16
16
|
tsconfig.build.json`, with `rewriteRelativeImportExtensions` turning the
|
|
17
17
|
`.ts` specifiers into `.js`) emits `dist/`, and the package's
|
|
18
18
|
`main`/`types`/`exports` point there. This is not optional polish: Node
|
|
@@ -22,10 +22,9 @@ published package shipping only `.ts` is unusable with plain `node` outside
|
|
|
22
22
|
this monorepo. The `exports` map keeps a `"bun"` condition on `src/index.ts`
|
|
23
23
|
so Bun users still run the source directly. In-repo, `npm run bootstrap`
|
|
24
24
|
builds `dist` (via `lerna run build --no-private`); when hacking on the
|
|
25
|
-
engine against a consumer, keep `
|
|
26
|
-
build:watch` running.
|
|
25
|
+
engine against a consumer, keep `pnpm --filter @genesislcap/mock-server build:watch` running.
|
|
27
26
|
|
|
28
|
-
Type-check with `
|
|
27
|
+
Type-check with `pnpm --filter @genesislcap/mock-server typecheck`
|
|
29
28
|
(`tsc --noEmit` over src + tests).
|
|
30
29
|
|
|
31
30
|
This package is the **protocol engine only**: message routing, `SOURCE_REF`
|
|
@@ -184,7 +183,7 @@ pair):
|
|
|
184
183
|
import { launchStack } from '@genesislcap/mock-server';
|
|
185
184
|
import { config } from './config.ts';
|
|
186
185
|
|
|
187
|
-
await launchStack({ config, clientCommand: '
|
|
186
|
+
await launchStack({ config, clientCommand: 'pnpm run dev:vite' });
|
|
188
187
|
```
|
|
189
188
|
|
|
190
189
|
`clientEnv: (port) => ({ ... })` adds per-instance env on top of the default
|
|
@@ -193,6 +192,24 @@ auto-increment already avoids collisions otherwise). Pass
|
|
|
193
192
|
`tieLifetimes: false` to manage shutdown yourself (e.g. inside a test
|
|
194
193
|
runner).
|
|
195
194
|
|
|
195
|
+
### Shutdown, and why there is a watchdog process
|
|
196
|
+
|
|
197
|
+
A client dev command is normally a launcher itself (`genx` -> `vite` ->
|
|
198
|
+
`esbuild`), so shutdown has to reach the whole tree, not just the pid that
|
|
199
|
+
was spawned. `launchStack` therefore starts the client as its own process
|
|
200
|
+
group leader and signals the **group**: SIGINT first, then SIGKILL after
|
|
201
|
+
`clientExitGraceMs` (default 5s) for anything that ignores it. `stop()`
|
|
202
|
+
resolves once the tree is actually down, not merely signalled. SIGINT,
|
|
203
|
+
SIGTERM, SIGHUP and process exit all take that same path.
|
|
204
|
+
|
|
205
|
+
None of that can run if the launcher itself is SIGKILLed — and then the
|
|
206
|
+
client is reparented to init and keeps holding its port, invisible on an
|
|
207
|
+
ephemeral-port setup. So `launchStack` also spawns a tiny detached watchdog
|
|
208
|
+
that polls for the launcher and takes the client's group down when it
|
|
209
|
+
disappears; the watchdog exits as soon as either side is gone, so it can
|
|
210
|
+
never outlive the pair it watches. Set `tieLifetimes: false` and you own all
|
|
211
|
+
of this yourself — no watchdog is started.
|
|
212
|
+
|
|
196
213
|
## Extension points
|
|
197
214
|
|
|
198
215
|
For everything the protocol handlers don't cover, three hooks avoid ever
|
|
@@ -322,6 +339,16 @@ every field on that table. This covers naming variants like
|
|
|
322
339
|
`config.eventSchemas['<eventName>'] = { table, pkOnly, fieldTypes }` for
|
|
323
340
|
names that don't follow the convention.
|
|
324
341
|
|
|
342
|
+
The `FEATURE` doesn't have to be an event name. It also resolves, in order:
|
|
343
|
+
an entry in `config.eventSchemas`, a **resource name** (a `config.queries` or
|
|
344
|
+
`config.requestReplies` key, via its `source` — `'ALL_TRADES'` →
|
|
345
|
+
`TRADE_VIEW`), and a bare **table name** (`'TRADE'`). Both matter in practice:
|
|
346
|
+
`<entity-management resourceName="COUNTERPARTY">` asks by table and the
|
|
347
|
+
showcase's react-client Admin page does that, while the FAST-Element client's
|
|
348
|
+
grids ask by query name (`ALL_USERS`, `ALL_PROFILES`, `ALL_TRADES`). Resolve
|
|
349
|
+
only event names and those requests error with `UNKNOWN_RESOURCE` and the form
|
|
350
|
+
renders no fields — the same dead button as above, from the other direction.
|
|
351
|
+
|
|
325
352
|
Everything else `<entity-management>` needs — resource discovery
|
|
326
353
|
(`RESOURCES_REQUEST`), grid metadata (`META_REQUEST`), row data (`DATA_LOGON`
|
|
327
354
|
or `REQ_<name>` depending on `datasourceType`), and the actual
|
|
@@ -435,7 +462,11 @@ extracted from for how each was actually found:
|
|
|
435
462
|
filter, and the `<FIELD>.<fn>(value)` method-call form project filter
|
|
436
463
|
builders generate (e.g. `DEAL_CURRENCIES.containsIgnoreCase('USD')`) —
|
|
437
464
|
both share the same functions: `contains`, `containsIgnoreCase` (substring
|
|
438
|
-
on strings, membership on array-valued fields),
|
|
465
|
+
on strings, membership on array-valued fields), the Java/Groovy string
|
|
466
|
+
methods `equals`, `equalsIgnoreCase`, `startsWith`, `endsWith` (pbc-notify-ui's
|
|
467
|
+
inbox subscribes with `((ALERT_STATUS.equals("NEW")))`, and an unsupported
|
|
468
|
+
method makes the whole criteria fail to compile — the filter is dropped and
|
|
469
|
+
the grid shows every row), `dateIsToday`,
|
|
439
470
|
`dateIsEqual`, `dateIsGreaterEqual`, `dateIsLessEqual`, `dateTimeIsEqual`,
|
|
440
471
|
`dateTimeIsGreaterEqual`, `dateTimeIsLessEqual`, `dateTimeIsAfter`,
|
|
441
472
|
`dateTimeIsBefore` (`dateIs*` compares by calendar day, `dateTimeIs*` by
|
|
@@ -473,7 +504,7 @@ never held that `ROW_REF` ignores the message.
|
|
|
473
504
|
|
|
474
505
|
## Tests
|
|
475
506
|
|
|
476
|
-
`
|
|
507
|
+
`pnpm --filter @genesislcap/mock-server test` runs the unit tests for
|
|
477
508
|
the criteria grammar, store, metadata inference, and event-table inference
|
|
478
509
|
plus end-to-end WS/HTTP tests (auth gating, filtered-subscription DELETE
|
|
479
510
|
delivery, keyed `REQ_*` lookups, session reuse, clean shutdown) via
|
package/dist/db/criteria.js
CHANGED
|
@@ -105,6 +105,29 @@ const EXPR_FUNCTIONS = {
|
|
|
105
105
|
}
|
|
106
106
|
return typeof value === 'string' && value.toLowerCase().includes(lowered);
|
|
107
107
|
},
|
|
108
|
+
// Groovy/Java String methods the client emits in the FIELD.method(args)
|
|
109
|
+
// form — e.g. pbc-notify-ui's inbox subscribes with
|
|
110
|
+
// `((ALERT_STATUS.equals("NEW")))`. Without these the criteria fails to
|
|
111
|
+
// compile, the filter is dropped, and the grid shows every row instead of
|
|
112
|
+
// the filtered set.
|
|
113
|
+
equals: (record, args, resolve) => resolve(args[0], record) === resolve(args[1], record),
|
|
114
|
+
equalsIgnoreCase: (record, args, resolve) => {
|
|
115
|
+
const value = resolve(args[0], record);
|
|
116
|
+
const other = resolve(args[1], record);
|
|
117
|
+
if (typeof value !== 'string' || typeof other !== 'string')
|
|
118
|
+
return value === other;
|
|
119
|
+
return value.toLowerCase() === other.toLowerCase();
|
|
120
|
+
},
|
|
121
|
+
startsWith: (record, args, resolve) => {
|
|
122
|
+
const value = resolve(args[0], record);
|
|
123
|
+
const prefix = resolve(args[1], record);
|
|
124
|
+
return typeof value === 'string' && typeof prefix === 'string' && value.startsWith(prefix);
|
|
125
|
+
},
|
|
126
|
+
endsWith: (record, args, resolve) => {
|
|
127
|
+
const value = resolve(args[0], record);
|
|
128
|
+
const suffix = resolve(args[1], record);
|
|
129
|
+
return typeof value === 'string' && typeof suffix === 'string' && value.endsWith(suffix);
|
|
130
|
+
},
|
|
108
131
|
dateIsToday: (record, args, resolve) => {
|
|
109
132
|
const day = toEpochDay(resolve(args[0], record));
|
|
110
133
|
return day !== null && day === toEpochDay(Date.now());
|
package/dist/db/store.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ export declare class Store {
|
|
|
8
8
|
readonly views: Map<string, ViewDef>;
|
|
9
9
|
registerTable(tableName: string, { pkField, sequencePrefix, sequenceWidth, rows }: TableDef): this;
|
|
10
10
|
registerView(viewName: string, definition: ViewDef): this;
|
|
11
|
+
private observeSequenceValue;
|
|
11
12
|
nextSequenceValue(sequencePrefix: string, width: number): string;
|
|
12
13
|
getAllRows(tableName: string): Row[];
|
|
13
14
|
getRow(tableName: string, pk: Pk): Row | undefined;
|
package/dist/db/store.js
CHANGED
|
@@ -49,6 +49,24 @@ export class Store {
|
|
|
49
49
|
this.views.set(viewName, definition);
|
|
50
50
|
return this;
|
|
51
51
|
}
|
|
52
|
+
// An explicitly-supplied pk inside the sequence's own range must advance the
|
|
53
|
+
// counter too. Without this, inserting e.g. 'TR002' by hand leaves the
|
|
54
|
+
// counter at 2, and the next auto-generated insert mints 'TR002' again and
|
|
55
|
+
// silently overwrites the hand-keyed row (Map.set, no error, event still
|
|
56
|
+
// acks success).
|
|
57
|
+
observeSequenceValue(config, row) {
|
|
58
|
+
if (!config.sequencePrefix || config.pkFields.length !== 1)
|
|
59
|
+
return;
|
|
60
|
+
const pk = String(row[config.pkFields[0]] ?? '');
|
|
61
|
+
if (!pk.startsWith(config.sequencePrefix))
|
|
62
|
+
return;
|
|
63
|
+
const n = parseInt(pk.slice(config.sequencePrefix.length), 10);
|
|
64
|
+
if (!Number.isFinite(n))
|
|
65
|
+
return;
|
|
66
|
+
const next = this.sequenceCounters.get(config.sequencePrefix) ?? 1;
|
|
67
|
+
if (n + 1 > next)
|
|
68
|
+
this.sequenceCounters.set(config.sequencePrefix, n + 1);
|
|
69
|
+
}
|
|
52
70
|
nextSequenceValue(sequencePrefix, width) {
|
|
53
71
|
const n = this.sequenceCounters.get(sequencePrefix) ?? 1;
|
|
54
72
|
this.sequenceCounters.set(sequencePrefix, n + 1);
|
|
@@ -109,15 +127,25 @@ export class Store {
|
|
|
109
127
|
if (missing.length > 0) {
|
|
110
128
|
throw new Error(`Primary key field(s) '${missing.join("', '")}' are required for inserting into table '${tableName}'`);
|
|
111
129
|
}
|
|
130
|
+
this.observeSequenceValue(config, row);
|
|
112
131
|
table.set(keyFor(config.pkFields, row), row);
|
|
113
132
|
return row;
|
|
114
133
|
}
|
|
115
134
|
updateRow(tableName, pk, patch) {
|
|
116
135
|
const table = this.tables.get(tableName);
|
|
117
|
-
|
|
136
|
+
const config = this.tableConfig.get(tableName);
|
|
137
|
+
if (!table || !config || !table.has(pk))
|
|
118
138
|
return undefined;
|
|
119
139
|
const updated = { ...table.get(pk), ...patch };
|
|
120
|
-
|
|
140
|
+
// A patch that changes a pk field (e.g. an entity-management form posting
|
|
141
|
+
// its full DETAILS after the user edited the key column) must move the row
|
|
142
|
+
// to its new key. Leaving it under the old one makes the index disagree
|
|
143
|
+
// with the row itself: getRow(newKey) misses, while rowKey()/getRowRef()
|
|
144
|
+
// report the new key, so the matching broadcast finds nothing to push.
|
|
145
|
+
const nextKey = keyFor(config.pkFields, updated);
|
|
146
|
+
if (nextKey !== pk)
|
|
147
|
+
table.delete(pk);
|
|
148
|
+
table.set(nextKey, updated);
|
|
121
149
|
return updated;
|
|
122
150
|
}
|
|
123
151
|
deleteRow(tableName, pk) {
|
package/dist/handlers/auth.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ export type TokenRegistry = Map<string, string>;
|
|
|
4
4
|
export declare function capRegistry(registry: Map<string, string>): void;
|
|
5
5
|
export declare function registerAckTokens(ack: Row, username: string, tokens: TokenRegistry): void;
|
|
6
6
|
export declare function buildLoginAckBody(user: AuthUser, config: MockServerConfig, messageType?: string): Row;
|
|
7
|
-
export declare function findUser(config: MockServerConfig, username?: string
|
|
7
|
+
export declare function findUser(config: MockServerConfig, username?: string): AuthUser | undefined;
|
|
8
|
+
export declare function findUserByCredentials(config: MockServerConfig, username?: string, password?: string): AuthUser | undefined;
|
|
8
9
|
export declare function handleLogin(message: GenesisMessage, connection: Connection, config: MockServerConfig, tokens: TokenRegistry): void;
|
|
9
|
-
export declare function handleLogout(message: GenesisMessage, connection: Connection): void;
|
|
10
|
+
export declare function handleLogout(message: GenesisMessage, connection: Connection, tokens: TokenRegistry): void;
|
package/dist/handlers/auth.js
CHANGED
|
@@ -48,11 +48,22 @@ export function buildLoginAckBody(user, config, messageType = MESSAGE_TYPE.EVENT
|
|
|
48
48
|
PROFILE: user.profile ?? [],
|
|
49
49
|
};
|
|
50
50
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
51
|
+
// Trusted lookup by username alone — for paths where identity is already
|
|
52
|
+
// established (a token this server issued, an HTTP session cookie,
|
|
53
|
+
// httpAutoLogin). NEVER use this for a credentials login.
|
|
54
|
+
export function findUser(config, username) {
|
|
55
|
+
if (username === undefined)
|
|
56
|
+
return undefined;
|
|
57
|
+
return (config.auth?.users ?? []).find((u) => u.username === username);
|
|
58
|
+
}
|
|
59
|
+
// Credentials login: the supplied password must match the configured one. A
|
|
60
|
+
// missing PASSWORD is a failed login, never a username-only lookup — treating
|
|
61
|
+
// it as one lets any client authenticate as any configured user just by
|
|
62
|
+
// omitting the field, defeating auth.requireAuth and every rowFilter/
|
|
63
|
+
// hideFields rule built on the logged-in identity.
|
|
64
|
+
export function findUserByCredentials(config, username, password) {
|
|
65
|
+
const user = findUser(config, username);
|
|
66
|
+
return user && user.password === password ? user : undefined;
|
|
56
67
|
}
|
|
57
68
|
export function handleLogin(message, connection, config, tokens) {
|
|
58
69
|
const details = message.DETAILS ?? {};
|
|
@@ -66,7 +77,7 @@ export function handleLogin(message, connection, config, tokens) {
|
|
|
66
77
|
tokens.get(message.SESSION_AUTH_TOKEN))
|
|
67
78
|
: undefined;
|
|
68
79
|
const user = details.USER_NAME !== undefined
|
|
69
|
-
?
|
|
80
|
+
? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
|
|
70
81
|
: findUser(config, tokenUsername);
|
|
71
82
|
if (!user) {
|
|
72
83
|
connection.reply(message, {
|
|
@@ -89,11 +100,22 @@ export function handleLogin(message, connection, config, tokens) {
|
|
|
89
100
|
connection.profile = user.profile ?? [];
|
|
90
101
|
connection.permission = user.permission ?? [];
|
|
91
102
|
connection.sessionAuthToken = ack.SESSION_AUTH_TOKEN;
|
|
103
|
+
connection.refreshAuthToken = ack.REFRESH_AUTH_TOKEN;
|
|
92
104
|
connection.sessionId = ack.SESSION_ID;
|
|
93
105
|
connection.reply(message, ack);
|
|
94
106
|
}
|
|
95
|
-
export function handleLogout(message, connection) {
|
|
107
|
+
export function handleLogout(message, connection, tokens) {
|
|
108
|
+
// Revoke this connection's tokens, not just its authenticated flag: every
|
|
109
|
+
// message re-adopts a stamped SESSION_AUTH_TOKEN (see router.ts), so a
|
|
110
|
+
// token left in the registry silently logs the connection straight back in
|
|
111
|
+
// on its very next request.
|
|
112
|
+
for (const token of [connection.sessionAuthToken, connection.refreshAuthToken]) {
|
|
113
|
+
if (token !== undefined)
|
|
114
|
+
tokens.delete(token);
|
|
115
|
+
}
|
|
96
116
|
connection.authenticated = false;
|
|
117
|
+
connection.sessionAuthToken = undefined;
|
|
118
|
+
connection.refreshAuthToken = undefined;
|
|
97
119
|
connection.subscriptions.clear();
|
|
98
120
|
connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.LOGOUT_ACK });
|
|
99
121
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { compileCriteria, filterByCriteria } from "../db/criteria.js";
|
|
2
2
|
import { MESSAGE_TYPE, ERROR_CODE } from "../protocol/messageTypes.js";
|
|
3
|
-
import {
|
|
3
|
+
import { stampRow } from "../protocol/rowUpdate.js";
|
|
4
4
|
import { applyResourceAuth, requestingUser } from "./resourceAuth.js";
|
|
5
5
|
// DATA_LOGON opens a persistent subscription keyed by SOURCE_REF: reply with an
|
|
6
6
|
// initial snapshot, then keep the SOURCE_REF registered so later inserts/amends/
|
|
@@ -26,7 +26,17 @@ export function handleDataLogon(message, connection, config, store) {
|
|
|
26
26
|
if (query.filter)
|
|
27
27
|
rows = rows.filter(query.filter);
|
|
28
28
|
rows = filterByCriteria(rows, criteria);
|
|
29
|
-
|
|
29
|
+
// Permissioning is applied per row so the ROW_REF can still be computed from
|
|
30
|
+
// the UNSTRIPPED row — pk fields may themselves be hidden from this user,
|
|
31
|
+
// and a snapshot row with no ROW_REF can never be matched to the later
|
|
32
|
+
// INSERT/MODIFY/DELETE pushes (which stamp the real ref, see server.ts).
|
|
33
|
+
const stampedRows = [];
|
|
34
|
+
for (const row of rows) {
|
|
35
|
+
const [permitted] = applyResourceAuth([row], query.auth, user);
|
|
36
|
+
if (!permitted)
|
|
37
|
+
continue;
|
|
38
|
+
stampedRows.push(stampRow(permitted, store.getRowRef(query.source, row), 'INSERT'));
|
|
39
|
+
}
|
|
30
40
|
connection.subscribe(message.SOURCE_REF, {
|
|
31
41
|
resourceName,
|
|
32
42
|
getRowRef: (row) => store.getRowRef(query.source, row),
|
|
@@ -35,8 +45,8 @@ export function handleDataLogon(message, connection, config, store) {
|
|
|
35
45
|
});
|
|
36
46
|
connection.reply(message, {
|
|
37
47
|
MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE,
|
|
38
|
-
ROW:
|
|
39
|
-
ROWS_COUNT:
|
|
48
|
+
ROW: stampedRows,
|
|
49
|
+
ROWS_COUNT: stampedRows.length,
|
|
40
50
|
SEQUENCE_ID: 1,
|
|
41
51
|
MORE_ROWS: false,
|
|
42
52
|
});
|
package/dist/handlers/http.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import crypto from 'node:crypto';
|
|
2
2
|
import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
|
|
3
|
-
import { buildLoginAckBody, capRegistry, findUser, registerAckTokens, } from "./auth.js";
|
|
3
|
+
import { buildLoginAckBody, capRegistry, findUser, findUserByCredentials, registerAckTokens, } from "./auth.js";
|
|
4
4
|
const SESSION_COOKIE = 'MOCK_SESSION_ID';
|
|
5
5
|
const HTTP_STATUS = {
|
|
6
6
|
OK: 200,
|
|
@@ -49,6 +49,16 @@ async function readJsonBody(req) {
|
|
|
49
49
|
const raw = Buffer.concat(chunks).toString('utf8');
|
|
50
50
|
return raw ? JSON.parse(raw) : {};
|
|
51
51
|
}
|
|
52
|
+
// Drops every token this server minted for `username`. Logout has to do this,
|
|
53
|
+
// not just forget the session: router.ts re-adopts any known SESSION_AUTH_TOKEN
|
|
54
|
+
// on every message, so a token left in the registry logs a WS connection
|
|
55
|
+
// straight back in on its next request.
|
|
56
|
+
function revokeTokensFor(tokens, username) {
|
|
57
|
+
for (const [token, owner] of tokens) {
|
|
58
|
+
if (owner === username)
|
|
59
|
+
tokens.delete(token);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
52
62
|
// Reuse the request's own session when its cookie already maps to this user —
|
|
53
63
|
// otherwise every page load would mint (and leak) a fresh session entry on a
|
|
54
64
|
// long-lived dev/CI server.
|
|
@@ -126,7 +136,7 @@ export function createHttpRequestListener(config, sessions, tokens = new Map())
|
|
|
126
136
|
// sessionRefresh.performRefresh), not a fresh credentials login —
|
|
127
137
|
// honor it only if the request already carries a known session.
|
|
128
138
|
const user = details.USER_NAME !== undefined
|
|
129
|
-
?
|
|
139
|
+
? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
|
|
130
140
|
: findUser(config, sessions.get(cookies[SESSION_COOKIE]));
|
|
131
141
|
if (!user) {
|
|
132
142
|
sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
|
|
@@ -151,7 +161,11 @@ export function createHttpRequestListener(config, sessions, tokens = new Map())
|
|
|
151
161
|
}
|
|
152
162
|
if (req.method === 'POST' && pathname.endsWith('event-logout')) {
|
|
153
163
|
const cookies = parseCookies(req.headers.cookie);
|
|
154
|
-
|
|
164
|
+
const sessionId = cookies[SESSION_COOKIE];
|
|
165
|
+
const username = sessions.get(sessionId);
|
|
166
|
+
sessions.delete(sessionId);
|
|
167
|
+
if (username !== undefined)
|
|
168
|
+
revokeTokensFor(tokens, username);
|
|
155
169
|
sendJson(res, HTTP_STATUS.OK, { MESSAGE_TYPE: 'LOGOUT_ACK' });
|
|
156
170
|
return;
|
|
157
171
|
}
|
|
@@ -45,7 +45,15 @@ const DELETE_EVENT_RE = /_DELETE(_|$)/;
|
|
|
45
45
|
// config.eventSchemas for names that don't follow this convention.
|
|
46
46
|
// Exported for unit tests only.
|
|
47
47
|
export function inferEventTable(eventName, tableNames) {
|
|
48
|
-
if (!eventName
|
|
48
|
+
if (!eventName)
|
|
49
|
+
return undefined;
|
|
50
|
+
// Not every caller asks by event name: entity-management resolves a grid's
|
|
51
|
+
// schema from the bare resource/table name (FEATURE: 'TRADE'), so accept an
|
|
52
|
+
// exact table match before requiring the EVENT_ prefix. Without this the
|
|
53
|
+
// request errors with UNKNOWN_RESOURCE and the form renders no fields.
|
|
54
|
+
if (tableNames.includes(eventName))
|
|
55
|
+
return eventName;
|
|
56
|
+
if (!eventName.startsWith('EVENT_'))
|
|
49
57
|
return undefined;
|
|
50
58
|
const rest = eventName.slice('EVENT_'.length);
|
|
51
59
|
const candidates = tableNames.filter((name) => rest === name || rest.startsWith(`${name}_`));
|
|
@@ -55,7 +63,16 @@ export function inferEventTable(eventName, tableNames) {
|
|
|
55
63
|
export function handleJsonSchemaRequest(message, connection, config, store) {
|
|
56
64
|
const eventName = message.DETAILS?.FEATURE;
|
|
57
65
|
const override = eventName ? config.eventSchemas?.[eventName] : undefined;
|
|
58
|
-
|
|
66
|
+
// A DATASERVER/REQUEST_SERVER resource name (e.g. 'ALL_USERS') resolves
|
|
67
|
+
// through its own definition to the backing table/view. The FAST-Element
|
|
68
|
+
// showcase's entity-management grids ask by query name, not by table or
|
|
69
|
+
// event name, so without this their create/update forms render empty.
|
|
70
|
+
const resourceSource = eventName
|
|
71
|
+
? (config.queries?.[eventName]?.source ?? config.requestReplies?.[eventName]?.source)
|
|
72
|
+
: undefined;
|
|
73
|
+
const table = override?.table ??
|
|
74
|
+
resourceSource ??
|
|
75
|
+
inferEventTable(eventName, Object.keys(config.tables ?? {}));
|
|
59
76
|
if (!table) {
|
|
60
77
|
connection.reply(message, {
|
|
61
78
|
MESSAGE_TYPE: message.MESSAGE_TYPE,
|
package/dist/launch.d.ts
CHANGED
package/dist/launch.js
CHANGED
|
@@ -4,8 +4,66 @@
|
|
|
4
4
|
// ports or orphaning processes.
|
|
5
5
|
import { spawn } from 'node:child_process';
|
|
6
6
|
import { createMockServer } from "./server.js";
|
|
7
|
+
// How long a client gets to exit on SIGINT before it is killed outright. A dev
|
|
8
|
+
// server that ignores the signal must not keep its port (or hang stop()).
|
|
9
|
+
const CLIENT_EXIT_GRACE_MS = 5000;
|
|
10
|
+
// How often the watchdog checks whether the launcher is still alive.
|
|
11
|
+
const WATCHDOG_POLL_MS = 500;
|
|
12
|
+
// Signals the client tree, not just the direct child. The client command is
|
|
13
|
+
// normally a launcher itself (genx -> vite -> esbuild), so signalling only the
|
|
14
|
+
// immediate pid can leave grandchildren holding the port. `detached: true`
|
|
15
|
+
// makes the child a process-group leader, and a negative pid addresses that
|
|
16
|
+
// whole group.
|
|
17
|
+
function killClientTree(client, signal) {
|
|
18
|
+
if (client.pid === undefined || client.exitCode !== null || client.signalCode !== null)
|
|
19
|
+
return;
|
|
20
|
+
try {
|
|
21
|
+
process.kill(-client.pid, signal);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
// No process group (Windows, or the group is already gone) — fall back to
|
|
25
|
+
// the single child.
|
|
26
|
+
try {
|
|
27
|
+
client.kill(signal);
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
// Already exited between the check and the signal; nothing to do.
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
// Nothing in THIS process runs when it is SIGKILLed or dies with the terminal,
|
|
35
|
+
// so parent-death cleanup cannot live here: the client would be reparented to
|
|
36
|
+
// init and keep serving its port forever (verified — a hard-killed launcher
|
|
37
|
+
// leaves vite listening). This tiny detached watcher polls for the launcher
|
|
38
|
+
// and takes the client's process group down with it. It also exits as soon as
|
|
39
|
+
// the client is gone, so it can never outlive the pair it is watching.
|
|
40
|
+
const WATCHDOG_SOURCE = `
|
|
41
|
+
const [launcher, target] = process.argv.slice(1).map(Number);
|
|
42
|
+
const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
43
|
+
const stop = (sig) => { try { process.kill(-target, sig); } catch { try { process.kill(target, sig); } catch {} } };
|
|
44
|
+
const timer = setInterval(() => {
|
|
45
|
+
if (!alive(target)) { clearInterval(timer); process.exit(0); }
|
|
46
|
+
if (alive(launcher)) return;
|
|
47
|
+
clearInterval(timer);
|
|
48
|
+
stop('SIGTERM');
|
|
49
|
+
setTimeout(() => { stop('SIGKILL'); process.exit(0); }, ${CLIENT_EXIT_GRACE_MS});
|
|
50
|
+
}, ${WATCHDOG_POLL_MS});
|
|
51
|
+
`;
|
|
52
|
+
function startWatchdog(clientPid) {
|
|
53
|
+
try {
|
|
54
|
+
const watchdog = spawn(process.execPath, ['-e', WATCHDOG_SOURCE, String(process.pid), String(clientPid)], { detached: true, stdio: 'ignore' });
|
|
55
|
+
// Detached + unref'd so it survives a hard kill of this process and never
|
|
56
|
+
// holds this process's event loop open.
|
|
57
|
+
watchdog.unref();
|
|
58
|
+
return watchdog;
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
console.warn('[mock-server] Could not start the client watchdog:', error);
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
7
65
|
export async function launchStack(options) {
|
|
8
|
-
const { config, clientCommand, port = 0, cwd, clientEnv, tieLifetimes = true } = options;
|
|
66
|
+
const { config, clientCommand, port = 0, cwd, clientEnv, tieLifetimes = true, clientExitGraceMs = CLIENT_EXIT_GRACE_MS, } = options;
|
|
9
67
|
const server = createMockServer(config);
|
|
10
68
|
const boundPort = await server.listen(port);
|
|
11
69
|
const env = {
|
|
@@ -13,47 +71,94 @@ export async function launchStack(options) {
|
|
|
13
71
|
API_HOST: `ws://localhost:${boundPort}`,
|
|
14
72
|
...clientEnv?.(boundPort),
|
|
15
73
|
};
|
|
74
|
+
// detached: the client leads its own process group so the whole tree can be
|
|
75
|
+
// signalled at once. It also means a terminal Ctrl+C no longer reaches the
|
|
76
|
+
// client directly — it reaches this process, whose SIGINT handler below
|
|
77
|
+
// tears the group down, so shutdown always takes one controlled path.
|
|
16
78
|
const client = Array.isArray(clientCommand)
|
|
17
|
-
? spawn(clientCommand[0], clientCommand.slice(1), {
|
|
18
|
-
|
|
79
|
+
? spawn(clientCommand[0], clientCommand.slice(1), {
|
|
80
|
+
cwd,
|
|
81
|
+
env,
|
|
82
|
+
stdio: 'inherit',
|
|
83
|
+
detached: true,
|
|
84
|
+
})
|
|
85
|
+
: spawn(clientCommand, { cwd, env, stdio: 'inherit', shell: true, detached: true });
|
|
86
|
+
const watchdog = tieLifetimes && client.pid !== undefined ? startWatchdog(client.pid) : undefined;
|
|
87
|
+
function cleanupWatchdog() {
|
|
88
|
+
if (watchdog?.pid === undefined)
|
|
89
|
+
return;
|
|
90
|
+
try {
|
|
91
|
+
process.kill(watchdog.pid, 'SIGKILL');
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
// Already exited on noticing the client was gone.
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
// Resolves once the client tree is actually down, so stop() means everything
|
|
98
|
+
// is stopped rather than merely signalled.
|
|
99
|
+
function stopClient() {
|
|
100
|
+
if (client.pid === undefined || client.exitCode !== null || client.signalCode !== null) {
|
|
101
|
+
return Promise.resolve();
|
|
102
|
+
}
|
|
103
|
+
return new Promise((resolve) => {
|
|
104
|
+
const escalate = setTimeout(() => killClientTree(client, 'SIGKILL'), clientExitGraceMs);
|
|
105
|
+
client.once('exit', () => {
|
|
106
|
+
clearTimeout(escalate);
|
|
107
|
+
resolve();
|
|
108
|
+
});
|
|
109
|
+
killClientTree(client, 'SIGINT');
|
|
110
|
+
});
|
|
111
|
+
}
|
|
19
112
|
let stopping = false;
|
|
20
113
|
async function stop() {
|
|
21
114
|
if (stopping)
|
|
22
115
|
return;
|
|
23
116
|
stopping = true;
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
await server.stop();
|
|
117
|
+
removeSignalHandlers();
|
|
118
|
+
cleanupWatchdog();
|
|
119
|
+
await Promise.all([stopClient(), server.stop()]);
|
|
27
120
|
}
|
|
28
121
|
const clientExited = new Promise((resolve) => {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
server.stop().then(finish, finish);
|
|
122
|
+
const settle = (code) => {
|
|
123
|
+
if (!tieLifetimes) {
|
|
124
|
+
resolve(code);
|
|
125
|
+
return;
|
|
34
126
|
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
127
|
+
stopping = true;
|
|
128
|
+
removeSignalHandlers();
|
|
129
|
+
cleanupWatchdog();
|
|
130
|
+
const finish = () => resolve(code);
|
|
131
|
+
server.stop().then(finish, finish);
|
|
132
|
+
};
|
|
133
|
+
client.once('exit', (code) => settle(code));
|
|
39
134
|
client.once('error', (error) => {
|
|
40
135
|
console.error('[mock-server] Failed to spawn client command:', error);
|
|
41
|
-
|
|
42
|
-
if (tieLifetimes) {
|
|
43
|
-
stopping = true;
|
|
44
|
-
server.stop().then(finish, finish);
|
|
45
|
-
}
|
|
46
|
-
else {
|
|
47
|
-
finish();
|
|
48
|
-
}
|
|
136
|
+
settle(null);
|
|
49
137
|
});
|
|
50
138
|
});
|
|
139
|
+
// Every path this process can still observe tears the client group down.
|
|
140
|
+
// SIGHUP matters for a closing terminal; 'exit' catches a plain return or an
|
|
141
|
+
// uncaught throw. (A SIGKILL of this process runs none of them — that is
|
|
142
|
+
// what the watchdog above is for.)
|
|
143
|
+
const onSignal = () => {
|
|
144
|
+
void stop();
|
|
145
|
+
};
|
|
146
|
+
const onExit = () => {
|
|
147
|
+
// Synchronous only: no async work runs during 'exit'.
|
|
148
|
+
cleanupWatchdog();
|
|
149
|
+
killClientTree(client, 'SIGKILL');
|
|
150
|
+
};
|
|
151
|
+
function removeSignalHandlers() {
|
|
152
|
+
process.off('SIGINT', onSignal);
|
|
153
|
+
process.off('SIGTERM', onSignal);
|
|
154
|
+
process.off('SIGHUP', onSignal);
|
|
155
|
+
process.off('exit', onExit);
|
|
156
|
+
}
|
|
51
157
|
if (tieLifetimes) {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
process.
|
|
56
|
-
process.once('SIGTERM', onSignal);
|
|
158
|
+
process.on('SIGINT', onSignal);
|
|
159
|
+
process.on('SIGTERM', onSignal);
|
|
160
|
+
process.on('SIGHUP', onSignal);
|
|
161
|
+
process.on('exit', onExit);
|
|
57
162
|
}
|
|
58
163
|
return { server, port: boundPort, client, clientExited, stop };
|
|
59
164
|
}
|
|
@@ -11,6 +11,7 @@ export declare class Connection {
|
|
|
11
11
|
readonly id: `${string}-${string}-${string}-${string}-${string}`;
|
|
12
12
|
authenticated: boolean;
|
|
13
13
|
sessionAuthToken: string | undefined;
|
|
14
|
+
refreshAuthToken: string | undefined;
|
|
14
15
|
sessionId: string | undefined;
|
|
15
16
|
userName: string | undefined;
|
|
16
17
|
profile: string[];
|
package/dist/protocol/router.js
CHANGED
|
@@ -78,7 +78,7 @@ export function routeMessage(message, connection, config, store, ctx, tokens = n
|
|
|
78
78
|
case MESSAGE_TYPE.EVENT_LOGIN_AUTH:
|
|
79
79
|
return handleLogin(message, connection, config, tokens);
|
|
80
80
|
case MESSAGE_TYPE.EVENT_LOGOUT:
|
|
81
|
-
return handleLogout(message, connection);
|
|
81
|
+
return handleLogout(message, connection, tokens);
|
|
82
82
|
case MESSAGE_TYPE.HEARTBEAT_PING:
|
|
83
83
|
return handleHeartbeat(message, connection, config);
|
|
84
84
|
case MESSAGE_TYPE.DATA_LOGON:
|