@genesislcap/mock-server 15.7.3-alpha-94532c4.0 → 15.7.3-alpha-e7d4aa5.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 +212 -37
- package/dist/db/criteria.d.ts +5 -0
- package/dist/db/criteria.js +304 -0
- package/dist/db/metadata.d.ts +3 -0
- package/dist/db/metadata.js +35 -0
- package/dist/db/store.d.ts +27 -0
- package/dist/db/store.js +226 -0
- package/dist/handlers/auth.d.ts +9 -0
- package/dist/handlers/auth.js +99 -0
- package/dist/handlers/commitEvent.d.ts +8 -0
- package/dist/handlers/commitEvent.js +40 -0
- package/dist/handlers/dataLogon.d.ts +5 -0
- package/dist/handlers/dataLogon.js +46 -0
- package/dist/handlers/heartbeat.d.ts +3 -0
- package/dist/handlers/heartbeat.js +16 -0
- package/dist/handlers/http.d.ts +4 -0
- package/dist/handlers/http.js +165 -0
- package/dist/handlers/jsonSchema.d.ts +5 -0
- package/dist/handlers/jsonSchema.js +77 -0
- package/dist/handlers/meta.d.ts +4 -0
- package/dist/handlers/meta.js +42 -0
- package/dist/handlers/requestReply.d.ts +4 -0
- package/dist/handlers/requestReply.js +68 -0
- package/dist/handlers/resourceAuth.d.ts +5 -0
- package/dist/handlers/resourceAuth.js +27 -0
- package/dist/handlers/resources.d.ts +3 -0
- package/dist/handlers/resources.js +34 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/launch.d.ts +19 -0
- package/dist/launch.js +59 -0
- package/dist/protocol/connection.d.ts +24 -0
- package/dist/protocol/connection.js +35 -0
- package/dist/protocol/errors.d.ts +17 -0
- package/dist/protocol/errors.js +16 -0
- package/dist/protocol/messageTypes.d.ts +28 -0
- package/dist/protocol/messageTypes.js +42 -0
- package/dist/protocol/router.d.ts +6 -0
- package/dist/protocol/router.js +101 -0
- package/dist/protocol/rowUpdate.d.ts +4 -0
- package/dist/protocol/rowUpdate.js +17 -0
- package/dist/server.d.ts +23 -0
- package/dist/server.js +274 -0
- package/dist/types.d.ts +142 -0
- package/dist/types.js +4 -0
- package/package.json +16 -6
- package/src/db/criteria.ts +53 -21
- package/src/db/store.ts +100 -27
- package/src/handlers/commitEvent.ts +4 -1
- package/src/handlers/dataLogon.ts +11 -4
- package/src/handlers/heartbeat.ts +16 -3
- package/src/handlers/http.ts +27 -0
- package/src/handlers/jsonSchema.ts +3 -3
- package/src/handlers/meta.ts +11 -3
- package/src/handlers/requestReply.ts +22 -8
- package/src/handlers/resourceAuth.ts +37 -0
- package/src/handlers/resources.ts +8 -1
- package/src/index.ts +9 -0
- package/src/launch.ts +95 -0
- package/src/protocol/connection.ts +3 -1
- package/src/protocol/router.ts +1 -1
- package/src/protocol/rowUpdate.ts +5 -4
- package/src/server.ts +73 -8
- package/src/types.ts +124 -3
- package/test/criteria.test.ts +0 -174
- package/test/jsonSchema.test.ts +0 -38
- package/test/metadata.test.ts +0 -49
- package/test/server.test.ts +0 -308
- package/test/store.test.ts +0 -181
- package/tsconfig.json +0 -18
package/dist/db/store.js
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// In-memory tables + views + sequence generation. No persistence, no external deps.
|
|
2
|
+
// This is the "database" — disposable and rebuilt from seed data on every server start.
|
|
3
|
+
// Composite keys join the pk fields' values with '|' (so values must not
|
|
4
|
+
// contain '|'). Single-field keys stay the raw value, preserving
|
|
5
|
+
// getRow('TABLE', 'TR001')-style lookups.
|
|
6
|
+
const COMPOSITE_KEY_SEPARATOR = '|';
|
|
7
|
+
function normalizePkFields(pkField) {
|
|
8
|
+
return Array.isArray(pkField) ? pkField : [pkField];
|
|
9
|
+
}
|
|
10
|
+
function keyFor(pkFields, row) {
|
|
11
|
+
if (pkFields.length === 1)
|
|
12
|
+
return row[pkFields[0]];
|
|
13
|
+
return pkFields.map((field) => String(row[field])).join(COMPOSITE_KEY_SEPARATOR);
|
|
14
|
+
}
|
|
15
|
+
export class Store {
|
|
16
|
+
tables = new Map();
|
|
17
|
+
tableConfig = new Map();
|
|
18
|
+
sequenceCounters = new Map();
|
|
19
|
+
// Immutable snapshot of each table's rows as registered, used only for field
|
|
20
|
+
// metadata derivation (see getMetadataRows) so deleting every live row can't
|
|
21
|
+
// collapse a resource's schema to zero fields.
|
|
22
|
+
seedRows = new Map();
|
|
23
|
+
views = new Map();
|
|
24
|
+
registerTable(tableName, { pkField, sequencePrefix, sequenceWidth = 3, rows = [] }) {
|
|
25
|
+
const pkFields = normalizePkFields(pkField);
|
|
26
|
+
const table = new Map();
|
|
27
|
+
for (const row of rows) {
|
|
28
|
+
table.set(keyFor(pkFields, row), { ...row });
|
|
29
|
+
}
|
|
30
|
+
this.tables.set(tableName, table);
|
|
31
|
+
this.tableConfig.set(tableName, { pkFields, sequencePrefix, sequenceWidth });
|
|
32
|
+
this.seedRows.set(tableName, rows.map((row) => ({ ...row })));
|
|
33
|
+
// Sequence generation only makes sense for a single-field pk.
|
|
34
|
+
if (sequencePrefix && pkFields.length === 1) {
|
|
35
|
+
let maxN = 0;
|
|
36
|
+
for (const row of rows) {
|
|
37
|
+
const pk = String(row[pkFields[0]] ?? '');
|
|
38
|
+
if (pk.startsWith(sequencePrefix)) {
|
|
39
|
+
const n = parseInt(pk.slice(sequencePrefix.length), 10);
|
|
40
|
+
if (Number.isFinite(n))
|
|
41
|
+
maxN = Math.max(maxN, n);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
this.sequenceCounters.set(sequencePrefix, maxN + 1);
|
|
45
|
+
}
|
|
46
|
+
return this;
|
|
47
|
+
}
|
|
48
|
+
registerView(viewName, definition) {
|
|
49
|
+
this.views.set(viewName, definition);
|
|
50
|
+
return this;
|
|
51
|
+
}
|
|
52
|
+
nextSequenceValue(sequencePrefix, width) {
|
|
53
|
+
const n = this.sequenceCounters.get(sequencePrefix) ?? 1;
|
|
54
|
+
this.sequenceCounters.set(sequencePrefix, n + 1);
|
|
55
|
+
return `${sequencePrefix}${String(n).padStart(width, '0')}`;
|
|
56
|
+
}
|
|
57
|
+
getAllRows(tableName) {
|
|
58
|
+
const table = this.tables.get(tableName);
|
|
59
|
+
if (!table)
|
|
60
|
+
return [];
|
|
61
|
+
return Array.from(table.values());
|
|
62
|
+
}
|
|
63
|
+
getRow(tableName, pk) {
|
|
64
|
+
return this.tables.get(tableName)?.get(pk);
|
|
65
|
+
}
|
|
66
|
+
// The storage/broadcast key for a row: the pk field's value, or for
|
|
67
|
+
// composite-keyed tables the pk fields' values joined with '|'. Event
|
|
68
|
+
// handlers on composite tables pass this to broadcastTableChange.
|
|
69
|
+
rowKey(tableName, row) {
|
|
70
|
+
const config = this.tableConfig.get(tableName);
|
|
71
|
+
if (!config)
|
|
72
|
+
throw new Error(`Unknown table: ${tableName}`);
|
|
73
|
+
return keyFor(config.pkFields, row);
|
|
74
|
+
}
|
|
75
|
+
// Fallback matching for tables where the caller doesn't have the full key:
|
|
76
|
+
// try the pk field(s) first, then any single field that uniquely identifies
|
|
77
|
+
// one row, then the full combination of provided fields.
|
|
78
|
+
findRow(tableName, criteria) {
|
|
79
|
+
const table = this.tables.get(tableName);
|
|
80
|
+
if (!table)
|
|
81
|
+
return undefined;
|
|
82
|
+
const { pkFields } = this.tableConfig.get(tableName) ?? { pkFields: [] };
|
|
83
|
+
if (pkFields.length > 0 && pkFields.every((field) => criteria[field] !== undefined)) {
|
|
84
|
+
const byKey = table.get(keyFor(pkFields, criteria));
|
|
85
|
+
if (byKey)
|
|
86
|
+
return byKey;
|
|
87
|
+
}
|
|
88
|
+
const rows = Array.from(table.values());
|
|
89
|
+
const matchesAllCriteria = (row) => Object.entries(criteria).every(([field, value]) => row[field] === value);
|
|
90
|
+
for (const [field, value] of Object.entries(criteria)) {
|
|
91
|
+
const matches = rows.filter((row) => row[field] === value);
|
|
92
|
+
if (matches.length === 1 && matchesAllCriteria(matches[0]))
|
|
93
|
+
return matches[0];
|
|
94
|
+
}
|
|
95
|
+
return rows.find(matchesAllCriteria);
|
|
96
|
+
}
|
|
97
|
+
insertRow(tableName, record) {
|
|
98
|
+
const table = this.tables.get(tableName);
|
|
99
|
+
const config = this.tableConfig.get(tableName);
|
|
100
|
+
if (!table || !config)
|
|
101
|
+
throw new Error(`Unknown table: ${tableName}`);
|
|
102
|
+
const row = { ...record };
|
|
103
|
+
if (config.pkFields.length === 1 &&
|
|
104
|
+
row[config.pkFields[0]] === undefined &&
|
|
105
|
+
config.sequencePrefix) {
|
|
106
|
+
row[config.pkFields[0]] = this.nextSequenceValue(config.sequencePrefix, config.sequenceWidth);
|
|
107
|
+
}
|
|
108
|
+
const missing = config.pkFields.filter((field) => row[field] === undefined);
|
|
109
|
+
if (missing.length > 0) {
|
|
110
|
+
throw new Error(`Primary key field(s) '${missing.join("', '")}' are required for inserting into table '${tableName}'`);
|
|
111
|
+
}
|
|
112
|
+
table.set(keyFor(config.pkFields, row), row);
|
|
113
|
+
return row;
|
|
114
|
+
}
|
|
115
|
+
updateRow(tableName, pk, patch) {
|
|
116
|
+
const table = this.tables.get(tableName);
|
|
117
|
+
if (!table || !table.has(pk))
|
|
118
|
+
return undefined;
|
|
119
|
+
const updated = { ...table.get(pk), ...patch };
|
|
120
|
+
table.set(pk, updated);
|
|
121
|
+
return updated;
|
|
122
|
+
}
|
|
123
|
+
deleteRow(tableName, pk) {
|
|
124
|
+
const table = this.tables.get(tableName);
|
|
125
|
+
if (!table)
|
|
126
|
+
return false;
|
|
127
|
+
return table.delete(pk);
|
|
128
|
+
}
|
|
129
|
+
// Materializes a view: base table left-joined to related tables (optionally
|
|
130
|
+
// narrowed by per-join `where` predicates), minus anti-joined rows, plus
|
|
131
|
+
// derived fields.
|
|
132
|
+
getViewRows(viewName) {
|
|
133
|
+
const view = this.views.get(viewName);
|
|
134
|
+
if (!view)
|
|
135
|
+
throw new Error(`Unknown view: ${viewName}`);
|
|
136
|
+
return this.materializeView(view, (tableName) => this.getAllRows(tableName));
|
|
137
|
+
}
|
|
138
|
+
materializeView(view, getRows) {
|
|
139
|
+
let rows = getRows(view.base).map((row) => ({ ...row }));
|
|
140
|
+
for (const antiJoin of view.antiJoins ?? []) {
|
|
141
|
+
const joinRows = getRows(antiJoin.table);
|
|
142
|
+
rows = rows.filter((row) => !joinRows.some((joinRow) => joinRow[antiJoin.on[1]] === row[antiJoin.on[0]] &&
|
|
143
|
+
(antiJoin.where?.(joinRow, row) ?? true)));
|
|
144
|
+
}
|
|
145
|
+
for (const join of view.joins ?? []) {
|
|
146
|
+
const joinRows = getRows(join.table);
|
|
147
|
+
// A `where` predicate sees the base row, so an index keyed on the `on`
|
|
148
|
+
// field alone can't answer it — scan per base row instead.
|
|
149
|
+
const joinIndex = join.where ? undefined : new Map();
|
|
150
|
+
if (joinIndex) {
|
|
151
|
+
for (const row of joinRows) {
|
|
152
|
+
joinIndex.set(row[join.on[1]], row);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
rows = rows.map((row) => {
|
|
156
|
+
const match = joinIndex
|
|
157
|
+
? joinIndex.get(row[join.on[0]])
|
|
158
|
+
: joinRows.find((joinRow) => joinRow[join.on[1]] === row[join.on[0]] && join.where(joinRow, row));
|
|
159
|
+
const merged = { ...row };
|
|
160
|
+
for (const [alias, sourceField] of Object.entries(join.select ?? {})) {
|
|
161
|
+
merged[alias] = match?.[sourceField];
|
|
162
|
+
}
|
|
163
|
+
return merged;
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
if (view.derived) {
|
|
167
|
+
rows = rows.map((row) => {
|
|
168
|
+
const merged = { ...row };
|
|
169
|
+
for (const [field, compute] of Object.entries(view.derived)) {
|
|
170
|
+
merged[field] = compute(row);
|
|
171
|
+
}
|
|
172
|
+
return merged;
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
return rows;
|
|
176
|
+
}
|
|
177
|
+
// Resolves a queryable resource (table or view) by name to its current rows.
|
|
178
|
+
getResourceRows(resourceName) {
|
|
179
|
+
if (this.views.has(resourceName))
|
|
180
|
+
return this.getViewRows(resourceName);
|
|
181
|
+
return this.getAllRows(resourceName);
|
|
182
|
+
}
|
|
183
|
+
// Rows to derive META_REQUEST/JSON_SCHEMA_REQUEST field metadata from:
|
|
184
|
+
// current rows when there are any, else the registration-time seed rows
|
|
185
|
+
// (re-joined through the view definition for views). Without this fallback,
|
|
186
|
+
// deleting a table's last row would make the next metadata reply say the
|
|
187
|
+
// resource has zero fields — which entity-management renders as a form with
|
|
188
|
+
// no inputs and a delete button that can't build a payload, silently.
|
|
189
|
+
getMetadataRows(resourceName) {
|
|
190
|
+
const live = this.getResourceRows(resourceName);
|
|
191
|
+
if (live.length > 0)
|
|
192
|
+
return live;
|
|
193
|
+
const view = this.views.get(resourceName);
|
|
194
|
+
if (view)
|
|
195
|
+
return this.materializeView(view, (tableName) => this.seedRows.get(tableName) ?? []);
|
|
196
|
+
return this.seedRows.get(resourceName) ?? [];
|
|
197
|
+
}
|
|
198
|
+
// Row-identity fields for a table or view; empty when unknown.
|
|
199
|
+
getPkFields(resourceName) {
|
|
200
|
+
const view = this.views.get(resourceName);
|
|
201
|
+
if (view) {
|
|
202
|
+
if (view.pkField)
|
|
203
|
+
return normalizePkFields(view.pkField);
|
|
204
|
+
return this.tableConfig.get(view.base)?.pkFields ?? [];
|
|
205
|
+
}
|
|
206
|
+
return this.tableConfig.get(resourceName)?.pkFields ?? [];
|
|
207
|
+
}
|
|
208
|
+
// The DETAILS.ROW_REF value stamped on QUERY_UPDATE rows (see
|
|
209
|
+
// protocol/rowUpdate.ts): the pk field's value, or the composite key. The
|
|
210
|
+
// client's dataServerResultFilter keys inserts/amends/deletes off this.
|
|
211
|
+
getRowRef(resourceName, row) {
|
|
212
|
+
const pkFields = this.getPkFields(resourceName);
|
|
213
|
+
if (pkFields.length === 0)
|
|
214
|
+
return undefined;
|
|
215
|
+
return keyFor(pkFields, row);
|
|
216
|
+
}
|
|
217
|
+
// Rebuilds a DELETE stub row carrying the pk field(s) from a stored key, so
|
|
218
|
+
// subscribers can be told which row to drop after it's already gone.
|
|
219
|
+
rowStubFromKey(resourceName, key) {
|
|
220
|
+
const pkFields = this.getPkFields(resourceName);
|
|
221
|
+
if (pkFields.length <= 1)
|
|
222
|
+
return pkFields.length ? { [pkFields[0]]: key } : {};
|
|
223
|
+
const parts = String(key).split(COMPOSITE_KEY_SEPARATOR);
|
|
224
|
+
return Object.fromEntries(pkFields.map((field, i) => [field, parts[i]]));
|
|
225
|
+
}
|
|
226
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Connection } from '../protocol/connection.ts';
|
|
2
|
+
import type { AuthUser, GenesisMessage, MockServerConfig, Row } from '../types.ts';
|
|
3
|
+
export type TokenRegistry = Map<string, string>;
|
|
4
|
+
export declare function capRegistry(registry: Map<string, string>): void;
|
|
5
|
+
export declare function registerAckTokens(ack: Row, username: string, tokens: TokenRegistry): void;
|
|
6
|
+
export declare function buildLoginAckBody(user: AuthUser, config: MockServerConfig, messageType?: string): Row;
|
|
7
|
+
export declare function findUser(config: MockServerConfig, username?: string, password?: string): AuthUser | undefined;
|
|
8
|
+
export declare function handleLogin(message: GenesisMessage, connection: Connection, config: MockServerConfig, tokens: TokenRegistry): void;
|
|
9
|
+
export declare function handleLogout(message: GenesisMessage, connection: Connection): void;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { MESSAGE_TYPE, ERROR_CODE } from "../protocol/messageTypes.js";
|
|
3
|
+
const DEFAULT_HEARTBEAT_INTERVAL_SECS = 30;
|
|
4
|
+
// Both transports mint tokens on every login/silent-login, so a long-lived
|
|
5
|
+
// dev/CI server would otherwise grow these maps one entry per page load.
|
|
6
|
+
// Maps iterate in insertion order, so dropping from the front evicts the
|
|
7
|
+
// oldest sessions/tokens first.
|
|
8
|
+
const MAX_REGISTRY_ENTRIES = 1000;
|
|
9
|
+
export function capRegistry(registry) {
|
|
10
|
+
while (registry.size > MAX_REGISTRY_ENTRIES) {
|
|
11
|
+
const oldest = registry.keys().next().value;
|
|
12
|
+
if (oldest === undefined)
|
|
13
|
+
return;
|
|
14
|
+
registry.delete(oldest);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export function registerAckTokens(ack, username, tokens) {
|
|
18
|
+
tokens.set(ack.SESSION_AUTH_TOKEN, username);
|
|
19
|
+
tokens.set(ack.REFRESH_AUTH_TOKEN, username);
|
|
20
|
+
capRegistry(tokens);
|
|
21
|
+
}
|
|
22
|
+
// Shared by the WS EVENT_LOGIN_AUTH handler and the HTTP login handlers
|
|
23
|
+
// (handlers/http.ts) — EVENT_LOGIN_DETAILS_ACK is byte-for-byte the same shape
|
|
24
|
+
// as EVENT_LOGIN_AUTH_ACK, just under a different MESSAGE_TYPE (see
|
|
25
|
+
// foundation-auth's EVENT_LOGIN_DETAILS_ACK.ts, which literally extends it).
|
|
26
|
+
export function buildLoginAckBody(user, config, messageType = MESSAGE_TYPE.EVENT_LOGIN_AUTH_ACK) {
|
|
27
|
+
return {
|
|
28
|
+
MESSAGE_TYPE: messageType,
|
|
29
|
+
SESSION_AUTH_TOKEN: crypto.randomUUID(),
|
|
30
|
+
REFRESH_AUTH_TOKEN: crypto.randomUUID(),
|
|
31
|
+
SESSION_ID: crypto.randomUUID(),
|
|
32
|
+
USER_NAME: user.username,
|
|
33
|
+
UPDATE_QUEUE: 'MOCK',
|
|
34
|
+
ZERO_MQ_PROXY_MODE_ENABLED: false,
|
|
35
|
+
ZERO_MQ_PROXY_INBOUND_PORT: 0,
|
|
36
|
+
ZERO_MQ_PROXY_OUTBOUND_PORT: 0,
|
|
37
|
+
USER: user.user ?? {},
|
|
38
|
+
DETAILS: {
|
|
39
|
+
SYSTEM: { DATE: new Date().toISOString() },
|
|
40
|
+
HEARTBEAT_INTERVAL_SECS: config.auth?.heartbeatIntervalSecs ?? DEFAULT_HEARTBEAT_INTERVAL_SECS,
|
|
41
|
+
FAILED_LOGIN_ATTEMPTS: 0,
|
|
42
|
+
REJECTED_LOGIN_ATTEMPTS: 0,
|
|
43
|
+
LAST_LOGIN_DATETIME: 0,
|
|
44
|
+
DAYS_TO_PASSWORD_EXPIRY: -1,
|
|
45
|
+
PRODUCT: [{ NAME: config.productName ?? 'mock-server', VERSION: '0.1.0' }],
|
|
46
|
+
},
|
|
47
|
+
PERMISSION: user.permission ?? [],
|
|
48
|
+
PROFILE: user.profile ?? [],
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export function findUser(config, username, password) {
|
|
52
|
+
const users = config.auth?.users ?? [];
|
|
53
|
+
if (password === undefined)
|
|
54
|
+
return users.find((u) => u.username === username);
|
|
55
|
+
return users.find((u) => u.username === username && u.password === password);
|
|
56
|
+
}
|
|
57
|
+
export function handleLogin(message, connection, config, tokens) {
|
|
58
|
+
const details = message.DETAILS ?? {};
|
|
59
|
+
// Two login shapes share EVENT_LOGIN_AUTH: credentials ({USER_NAME,
|
|
60
|
+
// PASSWORD}) and token refresh — foundation-comms' createRefreshTokenMessage
|
|
61
|
+
// sends only DETAILS.REFRESH_AUTH_TOKEN (plus the stored SESSION_AUTH_TOKEN
|
|
62
|
+
// at the top level), no username at all.
|
|
63
|
+
const tokenUsername = details.USER_NAME === undefined
|
|
64
|
+
? (tokens.get(details.REFRESH_AUTH_TOKEN) ??
|
|
65
|
+
tokens.get(details.SESSION_AUTH_TOKEN) ??
|
|
66
|
+
tokens.get(message.SESSION_AUTH_TOKEN))
|
|
67
|
+
: undefined;
|
|
68
|
+
const user = details.USER_NAME !== undefined
|
|
69
|
+
? findUser(config, details.USER_NAME, details.PASSWORD)
|
|
70
|
+
: findUser(config, tokenUsername);
|
|
71
|
+
if (!user) {
|
|
72
|
+
connection.reply(message, {
|
|
73
|
+
MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
|
|
74
|
+
ERROR: [
|
|
75
|
+
{
|
|
76
|
+
CODE: ERROR_CODE.INCORRECT_CREDENTIALS,
|
|
77
|
+
STATUS_CODE: '401',
|
|
78
|
+
TEXT: 'Incorrect username or password',
|
|
79
|
+
},
|
|
80
|
+
],
|
|
81
|
+
WARNING: [],
|
|
82
|
+
});
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
const ack = buildLoginAckBody(user, config);
|
|
86
|
+
registerAckTokens(ack, user.username, tokens);
|
|
87
|
+
connection.authenticated = true;
|
|
88
|
+
connection.userName = user.username;
|
|
89
|
+
connection.profile = user.profile ?? [];
|
|
90
|
+
connection.permission = user.permission ?? [];
|
|
91
|
+
connection.sessionAuthToken = ack.SESSION_AUTH_TOKEN;
|
|
92
|
+
connection.sessionId = ack.SESSION_ID;
|
|
93
|
+
connection.reply(message, ack);
|
|
94
|
+
}
|
|
95
|
+
export function handleLogout(message, connection) {
|
|
96
|
+
connection.authenticated = false;
|
|
97
|
+
connection.subscriptions.clear();
|
|
98
|
+
connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.LOGOUT_ACK });
|
|
99
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Store } from '../db/store.ts';
|
|
2
|
+
import type { Connection } from '../protocol/connection.ts';
|
|
3
|
+
import type { BroadcastFn, BroadcastTableChangeFn, GenesisMessage, MockServerConfig } from '../types.ts';
|
|
4
|
+
export interface CommitEventCtx {
|
|
5
|
+
broadcast: BroadcastFn;
|
|
6
|
+
broadcastTableChange: BroadcastTableChangeFn;
|
|
7
|
+
}
|
|
8
|
+
export declare function handleCommitEvent(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store, ctx: CommitEventCtx): void;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { NackError } from "../protocol/errors.js";
|
|
2
|
+
import { ERROR_CODE, MESSAGE_TYPE } from "../protocol/messageTypes.js";
|
|
3
|
+
// Commit events (EVENT_<ENTITY>_INSERT/_AMEND/_DELETE, or whatever suffix
|
|
4
|
+
// convention your project uses) are looked up by exact MESSAGE_TYPE against
|
|
5
|
+
// config.eventHandlers. A handler receives (details, ctx) and either returns
|
|
6
|
+
// { generated?: [...] } on success, or throws NackError(errors) on failure.
|
|
7
|
+
export function handleCommitEvent(message, connection, config, store, ctx) {
|
|
8
|
+
const eventName = message.MESSAGE_TYPE;
|
|
9
|
+
// defaultEventHandler catches anything unregistered — lets projects with
|
|
10
|
+
// dozens of commit events adopt incrementally (e.g. `() => ({})` to ack
|
|
11
|
+
// everything unhandled) instead of enumerating ack-only handlers.
|
|
12
|
+
const handler = config.eventHandlers?.[eventName] ?? config.defaultEventHandler;
|
|
13
|
+
// Replies use the GENERIC EVENT_ACK/EVENT_NACK — correlation is purely via
|
|
14
|
+
// SOURCE_REF. See the note on MESSAGE_TYPE in protocol/messageTypes.ts:
|
|
15
|
+
// real consumers (foundation-comms' kv.service, entity-management) match
|
|
16
|
+
// these names exactly, so a name-suffixed <EVENT>_ACK reads as failure and
|
|
17
|
+
// a <EVENT>_NACK passes as silent success.
|
|
18
|
+
if (!handler) {
|
|
19
|
+
connection.reply(message, {
|
|
20
|
+
MESSAGE_TYPE: MESSAGE_TYPE.EVENT_NACK,
|
|
21
|
+
ERROR: [
|
|
22
|
+
{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `No event handler registered for ${eventName}` },
|
|
23
|
+
],
|
|
24
|
+
});
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
try {
|
|
28
|
+
const result = handler(message.DETAILS ?? {}, { connection, store, message, ...ctx }) ?? {};
|
|
29
|
+
connection.reply(message, {
|
|
30
|
+
MESSAGE_TYPE: MESSAGE_TYPE.EVENT_ACK,
|
|
31
|
+
GENERATED: result.generated ?? [],
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
const errors = error instanceof NackError
|
|
36
|
+
? error.errors
|
|
37
|
+
: [{ CODE: ERROR_CODE.VALIDATION_ERROR, TEXT: error.message }];
|
|
38
|
+
connection.reply(message, { MESSAGE_TYPE: MESSAGE_TYPE.EVENT_NACK, ERROR: errors });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Store } from '../db/store.ts';
|
|
2
|
+
import type { Connection } from '../protocol/connection.ts';
|
|
3
|
+
import type { GenesisMessage, MockServerConfig } from '../types.ts';
|
|
4
|
+
export declare function handleDataLogon(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store): void;
|
|
5
|
+
export declare function handleDataLogoff(message: GenesisMessage, connection: Connection): void;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { compileCriteria, filterByCriteria } from "../db/criteria.js";
|
|
2
|
+
import { MESSAGE_TYPE, ERROR_CODE } from "../protocol/messageTypes.js";
|
|
3
|
+
import { stampRows } from "../protocol/rowUpdate.js";
|
|
4
|
+
import { applyResourceAuth, requestingUser } from "./resourceAuth.js";
|
|
5
|
+
// DATA_LOGON opens a persistent subscription keyed by SOURCE_REF: reply with an
|
|
6
|
+
// initial snapshot, then keep the SOURCE_REF registered so later inserts/amends/
|
|
7
|
+
// deletes on this resource can be pushed on the same channel (see server.ts
|
|
8
|
+
// broadcast()) until the client sends DATA_LOGOFF.
|
|
9
|
+
export function handleDataLogon(message, connection, config, store) {
|
|
10
|
+
const details = message.DETAILS ?? {};
|
|
11
|
+
const resourceName = details.DATASOURCE_NAME;
|
|
12
|
+
const query = config.queries?.[resourceName];
|
|
13
|
+
if (!query) {
|
|
14
|
+
connection.reply(message, {
|
|
15
|
+
MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE,
|
|
16
|
+
ERROR: [{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `Unknown datasource: ${resourceName}` }],
|
|
17
|
+
});
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
const criteria = details.CRITERIA_MATCH;
|
|
21
|
+
const user = requestingUser(connection);
|
|
22
|
+
// Order matters: the query's own filter (the where-clause equivalent) and
|
|
23
|
+
// the user's row permissioning narrow the set BEFORE the client's
|
|
24
|
+
// CRITERIA_MATCH; hidden fields are stripped last, off the final rows.
|
|
25
|
+
let rows = store.getResourceRows(query.source);
|
|
26
|
+
if (query.filter)
|
|
27
|
+
rows = rows.filter(query.filter);
|
|
28
|
+
rows = filterByCriteria(rows, criteria);
|
|
29
|
+
rows = applyResourceAuth(rows, query.auth, user);
|
|
30
|
+
connection.subscribe(message.SOURCE_REF, {
|
|
31
|
+
resourceName,
|
|
32
|
+
getRowRef: (row) => store.getRowRef(query.source, row),
|
|
33
|
+
predicate: compileCriteria(criteria),
|
|
34
|
+
sequenceId: 1,
|
|
35
|
+
});
|
|
36
|
+
connection.reply(message, {
|
|
37
|
+
MESSAGE_TYPE: MESSAGE_TYPE.QUERY_UPDATE,
|
|
38
|
+
ROW: stampRows(rows, (row) => store.getRowRef(query.source, row), 'INSERT'),
|
|
39
|
+
ROWS_COUNT: rows.length,
|
|
40
|
+
SEQUENCE_ID: 1,
|
|
41
|
+
MORE_ROWS: false,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
export function handleDataLogoff(message, connection) {
|
|
45
|
+
connection.unsubscribe(message.SOURCE_REF);
|
|
46
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
|
|
2
|
+
export function handleHeartbeat(message, connection, config) {
|
|
3
|
+
// With the auth gate off (the default), this server accepts every data
|
|
4
|
+
// message — so the pong must report IS_AUTHENTICATED: true even though the
|
|
5
|
+
// WS connection itself never "logged in". HTTP-login clients (httpAutoLogin
|
|
6
|
+
// included) send no SESSION_AUTH_TOKEN on WS messages, so
|
|
7
|
+
// connection.authenticated stays false forever on their connections; report
|
|
8
|
+
// that raw flag and the client treats the session as dead and tears it
|
|
9
|
+
// down, defeating httpAutoLogin entirely. Only when a project opts into
|
|
10
|
+
// auth.requireAuth does the flag reflect real connection auth state.
|
|
11
|
+
const requireAuth = config.auth?.requireAuth ?? false;
|
|
12
|
+
connection.reply(message, {
|
|
13
|
+
MESSAGE_TYPE: MESSAGE_TYPE.HEARTBEAT_PONG,
|
|
14
|
+
IS_AUTHENTICATED: connection.authenticated || !requireAuth,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import type { MockServerConfig } from '../types.ts';
|
|
3
|
+
import { type TokenRegistry } from './auth.ts';
|
|
4
|
+
export declare function createHttpRequestListener(config: MockServerConfig, sessions: Map<string, string>, tokens?: TokenRegistry): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
|
|
3
|
+
import { buildLoginAckBody, capRegistry, findUser, registerAckTokens, } from "./auth.js";
|
|
4
|
+
const SESSION_COOKIE = 'MOCK_SESSION_ID';
|
|
5
|
+
const HTTP_STATUS = {
|
|
6
|
+
OK: 200,
|
|
7
|
+
UNAUTHORIZED: 401,
|
|
8
|
+
NOT_FOUND: 404,
|
|
9
|
+
INTERNAL_SERVER_ERROR: 500,
|
|
10
|
+
};
|
|
11
|
+
// foundation-auth's login UI (client-app-login) doesn't use the WebSocket
|
|
12
|
+
// EVENT_LOGIN_AUTH flow at all — it POSTs credentials over plain HTTP to
|
|
13
|
+
// gwf/event-login-auth, and separately GETs gwf/event-login-details on every
|
|
14
|
+
// app load (cookie-based silent login: foundation-comms/src/connect/
|
|
15
|
+
// sessionRefresh.ts's isAuthenticated()). Both expect the exact same ACK body
|
|
16
|
+
// shape as the WS login (EVENT_LOGIN_DETAILS_ACK literally extends
|
|
17
|
+
// EVENT_LOGIN_AUTH_ACK), just reached over HTTP with a session cookie instead
|
|
18
|
+
// of SOURCE_REF correlation. This is a *separate* transport from the WS
|
|
19
|
+
// protocol in server.ts — a client-app can use either, or (as here) both.
|
|
20
|
+
function parseCookies(header) {
|
|
21
|
+
const cookies = {};
|
|
22
|
+
for (const part of (header ?? '').split(';')) {
|
|
23
|
+
const [key, ...rest] = part.trim().split('=');
|
|
24
|
+
if (key)
|
|
25
|
+
cookies[key] = decodeURIComponent(rest.join('='));
|
|
26
|
+
}
|
|
27
|
+
return cookies;
|
|
28
|
+
}
|
|
29
|
+
function setSessionCookie(res, sessionId) {
|
|
30
|
+
res.setHeader('Set-Cookie', `${SESSION_COOKIE}=${sessionId}; Path=/; SameSite=Lax`);
|
|
31
|
+
}
|
|
32
|
+
function sendJson(res, status, body) {
|
|
33
|
+
res.writeHead(status, { 'Content-Type': 'application/json' });
|
|
34
|
+
res.end(JSON.stringify(body));
|
|
35
|
+
}
|
|
36
|
+
const BYTES_PER_KB = 1024;
|
|
37
|
+
const MAX_BODY_KB = 1024;
|
|
38
|
+
const MAX_BODY_BYTES = MAX_BODY_KB * BYTES_PER_KB; // 1MB — logins/commits carry small payloads, this only guards against abuse
|
|
39
|
+
async function readJsonBody(req) {
|
|
40
|
+
const chunks = [];
|
|
41
|
+
let bytesRead = 0;
|
|
42
|
+
for await (const chunk of req) {
|
|
43
|
+
bytesRead += chunk.length;
|
|
44
|
+
if (bytesRead > MAX_BODY_BYTES) {
|
|
45
|
+
throw new Error('Request body size limit exceeded');
|
|
46
|
+
}
|
|
47
|
+
chunks.push(chunk);
|
|
48
|
+
}
|
|
49
|
+
const raw = Buffer.concat(chunks).toString('utf8');
|
|
50
|
+
return raw ? JSON.parse(raw) : {};
|
|
51
|
+
}
|
|
52
|
+
// Reuse the request's own session when its cookie already maps to this user —
|
|
53
|
+
// otherwise every page load would mint (and leak) a fresh session entry on a
|
|
54
|
+
// long-lived dev/CI server.
|
|
55
|
+
function ensureSession(sessions, cookieSessionId, username) {
|
|
56
|
+
if (cookieSessionId && sessions.get(cookieSessionId) === username)
|
|
57
|
+
return cookieSessionId;
|
|
58
|
+
const sessionId = crypto.randomUUID();
|
|
59
|
+
sessions.set(sessionId, username);
|
|
60
|
+
capRegistry(sessions);
|
|
61
|
+
return sessionId;
|
|
62
|
+
}
|
|
63
|
+
export function createHttpRequestListener(config, sessions, tokens = new Map()) {
|
|
64
|
+
return async function requestListener(req, res) {
|
|
65
|
+
const pathname = (req.url ?? '').split('?')[0];
|
|
66
|
+
try {
|
|
67
|
+
// Project-defined routes run first (see HttpRouteDef) — endpoints the
|
|
68
|
+
// protocol doesn't cover (e.g. GET pbi/configs), or overrides of the
|
|
69
|
+
// built-ins below.
|
|
70
|
+
const route = (config.httpRoutes ?? []).find((candidate) => (!candidate.method || candidate.method.toUpperCase() === req.method) &&
|
|
71
|
+
(typeof candidate.path === 'string'
|
|
72
|
+
? pathname.endsWith(candidate.path)
|
|
73
|
+
: candidate.path.test(pathname)));
|
|
74
|
+
if (route) {
|
|
75
|
+
await route.handler(req, res);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
// foundation-auth's login screen fetches this whenever SSO is toggled
|
|
79
|
+
// on, and treats both a failed fetch and an empty IDPS list as fatal
|
|
80
|
+
// (red error, credentials form hidden). Serve the configured providers,
|
|
81
|
+
// or one non-functional placeholder so the screen still renders.
|
|
82
|
+
if (req.method === 'GET' && pathname.endsWith('sso/list')) {
|
|
83
|
+
const idps = config.auth?.ssoIdentityProviders ?? [
|
|
84
|
+
{ ID: 'mock-sso', DESCRIPTION: 'Mock SSO (placeholder, not functional)', TYPE: 'saml' },
|
|
85
|
+
];
|
|
86
|
+
sendJson(res, HTTP_STATUS.OK, { IDPS: idps });
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
// Cookie-based silent login on app load — auto-authenticates as the
|
|
90
|
+
// configured user when config.auth.httpAutoLogin is set, so the login
|
|
91
|
+
// screen never appears (matches how a real session cookie would behave
|
|
92
|
+
// once already logged in, but skips the manual login step entirely).
|
|
93
|
+
// Two different call sites hit this path with different methods:
|
|
94
|
+
// foundation-auth's fetch machine always POSTs (createFetchMachineEvent
|
|
95
|
+
// hardcodes method: 'POST') on initial silent-login; foundation-comms'
|
|
96
|
+
// sessionRefresh.ts's isAuthenticated() does a plain GET later, when
|
|
97
|
+
// checking whether an expired session can be silently renewed.
|
|
98
|
+
if ((req.method === 'GET' || req.method === 'POST') &&
|
|
99
|
+
pathname.endsWith('event-login-details')) {
|
|
100
|
+
const autoLoginUsername = config.auth?.httpAutoLogin;
|
|
101
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
102
|
+
const user = autoLoginUsername
|
|
103
|
+
? findUser(config, autoLoginUsername === true ? config.auth?.users?.[0]?.username : autoLoginUsername)
|
|
104
|
+
: findUser(config, sessions.get(cookies[SESSION_COOKIE]));
|
|
105
|
+
if (!user) {
|
|
106
|
+
sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
|
|
107
|
+
MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
|
|
108
|
+
ERROR: [
|
|
109
|
+
{ CODE: 'NOT_LOGGED_ON', STATUS_CODE: '401 Unauthorized', TEXT: 'No active session' },
|
|
110
|
+
],
|
|
111
|
+
});
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
const sessionId = ensureSession(sessions, cookies[SESSION_COOKIE], user.username);
|
|
115
|
+
setSessionCookie(res, sessionId);
|
|
116
|
+
const ack = buildLoginAckBody(user, config, 'EVENT_LOGIN_DETAILS_ACK');
|
|
117
|
+
registerAckTokens(ack, user.username, tokens);
|
|
118
|
+
sendJson(res, HTTP_STATUS.OK, ack);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (req.method === 'POST' && pathname.endsWith('event-login-auth')) {
|
|
122
|
+
const body = await readJsonBody(req);
|
|
123
|
+
const details = body.DETAILS ?? {};
|
|
124
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
125
|
+
// Empty DETAILS means a session-refresh ping (foundation-comms'
|
|
126
|
+
// sessionRefresh.performRefresh), not a fresh credentials login —
|
|
127
|
+
// honor it only if the request already carries a known session.
|
|
128
|
+
const user = details.USER_NAME !== undefined
|
|
129
|
+
? findUser(config, details.USER_NAME, details.PASSWORD)
|
|
130
|
+
: findUser(config, sessions.get(cookies[SESSION_COOKIE]));
|
|
131
|
+
if (!user) {
|
|
132
|
+
sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
|
|
133
|
+
MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
|
|
134
|
+
ERROR: [
|
|
135
|
+
{
|
|
136
|
+
CODE: 'INCORRECT_CREDENTIALS',
|
|
137
|
+
STATUS_CODE: '401 Unauthorized',
|
|
138
|
+
TEXT: 'Problem logging in',
|
|
139
|
+
},
|
|
140
|
+
],
|
|
141
|
+
WARNING: [],
|
|
142
|
+
});
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
const sessionId = ensureSession(sessions, cookies[SESSION_COOKIE], user.username);
|
|
146
|
+
setSessionCookie(res, sessionId);
|
|
147
|
+
const ack = buildLoginAckBody(user, config);
|
|
148
|
+
registerAckTokens(ack, user.username, tokens);
|
|
149
|
+
sendJson(res, HTTP_STATUS.OK, ack);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
if (req.method === 'POST' && pathname.endsWith('event-logout')) {
|
|
153
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
154
|
+
sessions.delete(cookies[SESSION_COOKIE]);
|
|
155
|
+
sendJson(res, HTTP_STATUS.OK, { MESSAGE_TYPE: 'LOGOUT_ACK' });
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
res.writeHead(HTTP_STATUS.NOT_FOUND).end();
|
|
159
|
+
}
|
|
160
|
+
catch (error) {
|
|
161
|
+
console.error('[mock-server] HTTP handler error:', error);
|
|
162
|
+
res.writeHead(HTTP_STATUS.INTERNAL_SERVER_ERROR).end();
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { Store } from '../db/store.ts';
|
|
2
|
+
import type { Connection } from '../protocol/connection.ts';
|
|
3
|
+
import type { GenesisMessage, MockServerConfig } from '../types.ts';
|
|
4
|
+
export declare function inferEventTable(eventName: string | undefined, tableNames: string[]): string | undefined;
|
|
5
|
+
export declare function handleJsonSchemaRequest(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store): void;
|