@genesislcap/mock-server 15.7.3-alpha-277c463.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.
Files changed (71) hide show
  1. package/README.md +237 -52
  2. package/dist/db/criteria.d.ts +5 -0
  3. package/dist/db/criteria.js +304 -0
  4. package/dist/db/metadata.d.ts +3 -0
  5. package/dist/db/metadata.js +35 -0
  6. package/dist/db/store.d.ts +27 -0
  7. package/dist/db/store.js +226 -0
  8. package/dist/handlers/auth.d.ts +9 -0
  9. package/dist/handlers/auth.js +99 -0
  10. package/dist/handlers/commitEvent.d.ts +8 -0
  11. package/dist/handlers/commitEvent.js +40 -0
  12. package/dist/handlers/dataLogon.d.ts +5 -0
  13. package/dist/handlers/dataLogon.js +46 -0
  14. package/dist/handlers/heartbeat.d.ts +3 -0
  15. package/dist/handlers/heartbeat.js +16 -0
  16. package/dist/handlers/http.d.ts +4 -0
  17. package/dist/handlers/http.js +165 -0
  18. package/dist/handlers/jsonSchema.d.ts +5 -0
  19. package/dist/handlers/jsonSchema.js +77 -0
  20. package/dist/handlers/meta.d.ts +4 -0
  21. package/dist/handlers/meta.js +42 -0
  22. package/dist/handlers/requestReply.d.ts +4 -0
  23. package/dist/handlers/requestReply.js +68 -0
  24. package/dist/handlers/resourceAuth.d.ts +5 -0
  25. package/dist/handlers/resourceAuth.js +27 -0
  26. package/dist/handlers/resources.d.ts +3 -0
  27. package/dist/handlers/resources.js +34 -0
  28. package/dist/index.d.ts +6 -0
  29. package/dist/index.js +5 -0
  30. package/dist/launch.d.ts +19 -0
  31. package/dist/launch.js +59 -0
  32. package/dist/protocol/connection.d.ts +24 -0
  33. package/dist/protocol/connection.js +35 -0
  34. package/dist/protocol/errors.d.ts +17 -0
  35. package/dist/protocol/errors.js +16 -0
  36. package/dist/protocol/messageTypes.d.ts +28 -0
  37. package/dist/protocol/messageTypes.js +42 -0
  38. package/dist/protocol/router.d.ts +6 -0
  39. package/dist/protocol/router.js +101 -0
  40. package/dist/protocol/rowUpdate.d.ts +4 -0
  41. package/dist/protocol/rowUpdate.js +17 -0
  42. package/dist/server.d.ts +23 -0
  43. package/dist/server.js +274 -0
  44. package/dist/types.d.ts +142 -0
  45. package/dist/types.js +4 -0
  46. package/package.json +16 -6
  47. package/src/db/criteria.ts +53 -21
  48. package/src/db/store.ts +100 -27
  49. package/src/handlers/commitEvent.ts +13 -5
  50. package/src/handlers/dataLogon.ts +11 -4
  51. package/src/handlers/heartbeat.ts +16 -3
  52. package/src/handlers/http.ts +27 -0
  53. package/src/handlers/jsonSchema.ts +3 -3
  54. package/src/handlers/meta.ts +11 -3
  55. package/src/handlers/requestReply.ts +22 -8
  56. package/src/handlers/resourceAuth.ts +37 -0
  57. package/src/handlers/resources.ts +8 -1
  58. package/src/index.ts +9 -0
  59. package/src/launch.ts +95 -0
  60. package/src/protocol/connection.ts +3 -1
  61. package/src/protocol/messageTypes.ts +9 -0
  62. package/src/protocol/router.ts +19 -12
  63. package/src/protocol/rowUpdate.ts +5 -4
  64. package/src/server.ts +73 -8
  65. package/src/types.ts +132 -8
  66. package/test/criteria.test.ts +0 -174
  67. package/test/jsonSchema.test.ts +0 -38
  68. package/test/metadata.test.ts +0 -49
  69. package/test/server.test.ts +0 -289
  70. package/test/store.test.ts +0 -181
  71. package/tsconfig.json +0 -18
@@ -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;
@@ -0,0 +1,77 @@
1
+ import { deriveFields } from "../db/metadata.js";
2
+ import { ERROR_CODE } from "../protocol/messageTypes.js";
3
+ // JSON_SCHEMA_REQUEST shares its request envelope with META_REQUEST (same
4
+ // DETAILS.FEATURE resource-name field) but its reply is a completely
5
+ // different shape: Connect.getJSONSchema doesn't read response.DETAILS at
6
+ // all — the response *is* the SchemaResponse ({ INBOUND, OUTBOUND }, each a
7
+ // draft-07 JSON Schema). @genesislcap/foundation-entity-management's
8
+ // <entity-management> calls this for every create/update form (fields come
9
+ // from INBOUND.properties.DETAILS.properties) and for delete confirmation
10
+ // (it reads Object.keys(...properties) to know which fields to copy from the
11
+ // selected row into the commit DETAILS). Route this to handleMetaRequest by
12
+ // mistake and forms silently render with zero fields, and delete can never
13
+ // build a payload — no error, just a dead button.
14
+ function jsonSchemaType(fieldType) {
15
+ switch (fieldType) {
16
+ case 'LONG':
17
+ return 'integer';
18
+ case 'DOUBLE':
19
+ return 'number';
20
+ case 'BOOLEAN':
21
+ return 'boolean';
22
+ default:
23
+ return 'string';
24
+ }
25
+ }
26
+ function buildSchema(fields, required) {
27
+ const properties = {};
28
+ for (const field of fields) {
29
+ properties[field.NAME] = { type: jsonSchemaType(field.TYPE) };
30
+ }
31
+ return {
32
+ type: 'object',
33
+ properties: {
34
+ DETAILS: { type: 'object', properties, required },
35
+ },
36
+ };
37
+ }
38
+ const DELETE_EVENT_RE = /_DELETE(_|$)/;
39
+ // Zero-config default: EVENT_<TABLE>_<VERB...> maps to <TABLE> if it's a
40
+ // registered table name (longest match wins, so e.g. a hypothetical
41
+ // COUNTERPARTY_AUTH table can't shadow COUNTERPARTY). Covers every event
42
+ // naming pattern in this codebase (INSERT, MODIFY, DELETE, plus suffixed
43
+ // variants like INSERT_WITH_APPROVAL, DEMO_INSERT, MODIFY_PRICE, INSERT_FAIL)
44
+ // without hand-maintaining a table per event. Override via
45
+ // config.eventSchemas for names that don't follow this convention.
46
+ // Exported for unit tests only.
47
+ export function inferEventTable(eventName, tableNames) {
48
+ if (!eventName?.startsWith('EVENT_'))
49
+ return undefined;
50
+ const rest = eventName.slice('EVENT_'.length);
51
+ const candidates = tableNames.filter((name) => rest === name || rest.startsWith(`${name}_`));
52
+ candidates.sort((a, b) => b.length - a.length);
53
+ return candidates[0];
54
+ }
55
+ export function handleJsonSchemaRequest(message, connection, config, store) {
56
+ const eventName = message.DETAILS?.FEATURE;
57
+ const override = eventName ? config.eventSchemas?.[eventName] : undefined;
58
+ const table = override?.table ?? inferEventTable(eventName, Object.keys(config.tables ?? {}));
59
+ if (!table) {
60
+ connection.reply(message, {
61
+ MESSAGE_TYPE: message.MESSAGE_TYPE,
62
+ ERROR: [{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `Unknown resource: ${eventName}` }],
63
+ });
64
+ return;
65
+ }
66
+ const pkOnly = override?.pkOnly ?? DELETE_EVENT_RE.test(eventName);
67
+ const pkFields = store.getPkFields(table);
68
+ let fields = deriveFields(store.getMetadataRows(table), override?.fieldTypes);
69
+ if (pkOnly)
70
+ fields = fields.filter((field) => pkFields.includes(field.NAME));
71
+ const schema = buildSchema(fields, pkOnly ? pkFields : []);
72
+ connection.reply(message, {
73
+ MESSAGE_TYPE: message.MESSAGE_TYPE,
74
+ INBOUND: schema,
75
+ OUTBOUND: schema,
76
+ });
77
+ }
@@ -0,0 +1,4 @@
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 handleMetaRequest(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store): void;
@@ -0,0 +1,42 @@
1
+ import { deriveFields } from "../db/metadata.js";
2
+ import { ERROR_CODE } from "../protocol/messageTypes.js";
3
+ import { hiddenFields, requestingUser } from "./resourceAuth.js";
4
+ // createMetaRequestMessage (foundation-comms/src/connect/message.ts) puts the
5
+ // resource name in DETAILS.FEATURE — not DATASOURCE_NAME/RESOURCE_NAME despite
6
+ // what every other message type in this protocol would suggest.
7
+ function resolveResourceName(message) {
8
+ return (message.DETAILS?.FEATURE ?? message.DETAILS?.DATASOURCE_NAME ?? message.DETAILS?.RESOURCE_NAME);
9
+ }
10
+ // Connect.getMetadata reads metaResponse.DETAILS (not the top-level message)
11
+ // and extractFieldDefinitions (metadata.utils.ts) branches on DETAILS.TYPE:
12
+ // DATASERVER resources need DETAILS.FIELD, REQUEST_SERVER ones need
13
+ // DETAILS.REPLY_FIELD. Get either wrong and every grid silently reports
14
+ // "Metadata Fetch failed" / "Unsupported resource type: undefined".
15
+ export function handleMetaRequest(message, connection, config, store) {
16
+ const resourceName = resolveResourceName(message);
17
+ const query = config.queries?.[resourceName];
18
+ const requestReply = config.requestReplies?.[resourceName];
19
+ if (!query && !requestReply) {
20
+ connection.reply(message, {
21
+ MESSAGE_TYPE: message.MESSAGE_TYPE,
22
+ ERROR: [{ CODE: ERROR_CODE.UNKNOWN_RESOURCE, TEXT: `Unknown resource: ${resourceName}` }],
23
+ });
24
+ return;
25
+ }
26
+ const resolved = (query ?? requestReply);
27
+ // Resolver-only request-replies have no backing table/view — their field
28
+ // metadata comes from the def's own metadataRows sample (plus fieldTypes).
29
+ const rows = resolved.source
30
+ ? store.getMetadataRows(resolved.source)
31
+ : (requestReply?.metadataRows ?? []);
32
+ // Hidden fields disappear from the metadata too — a column the user can't
33
+ // see must not be offered to the grid at all.
34
+ const hidden = hiddenFields(resolved.auth, requestingUser(connection));
35
+ const fields = deriveFields(rows, resolved.fieldTypes).filter((field) => !hidden.has(field.NAME));
36
+ connection.reply(message, {
37
+ MESSAGE_TYPE: message.MESSAGE_TYPE,
38
+ DETAILS: query
39
+ ? { NAME: resourceName, TYPE: 'DATASERVER', FIELD: fields, KEY: [] }
40
+ : { NAME: resourceName, TYPE: 'REQUEST_SERVER', REPLY_FIELD: fields },
41
+ });
42
+ }
@@ -0,0 +1,4 @@
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 handleRequestReply(message: GenesisMessage, connection: Connection, config: MockServerConfig, store: Store): void;
@@ -0,0 +1,68 @@
1
+ import { filterByCriteria } from "../db/criteria.js";
2
+ import { NackError } from "../protocol/errors.js";
3
+ import { ERROR_CODE } from "../protocol/messageTypes.js";
4
+ import { applyResourceAuth, requestingUser } from "./resourceAuth.js";
5
+ // Keyed lookups: foundation-comms' createRequestMessage spreads RequestParams
6
+ // onto the message, so REQUEST is a *top-level* field ({FIELD: value} pairs
7
+ // naming the request server's index fields). A real request server only
8
+ // returns rows matching them; '*' (Genesis's wildcard), null/undefined, and
9
+ // '' mean "any". Arrays match any listed value.
10
+ function matchesRequestFields(row, request) {
11
+ return Object.entries(request).every(([field, value]) => {
12
+ if (value === undefined || value === null || value === '*' || value === '')
13
+ return true;
14
+ if (Array.isArray(value))
15
+ return value.length === 0 || value.includes(row[field]);
16
+ return row[field] === value;
17
+ });
18
+ }
19
+ export function handleRequestReply(message, connection, config, store) {
20
+ const resourceName = message.MESSAGE_TYPE.replace(/^REQ_/, '');
21
+ const requestReply = config.requestReplies?.[resourceName];
22
+ if (!requestReply || (!requestReply.resolver && !requestReply.source)) {
23
+ connection.reply(message, {
24
+ MESSAGE_TYPE: `REP_${resourceName}`,
25
+ ERROR: [
26
+ {
27
+ CODE: ERROR_CODE.UNKNOWN_RESOURCE,
28
+ TEXT: `Unknown request-reply resource: ${resourceName}`,
29
+ },
30
+ ],
31
+ });
32
+ return;
33
+ }
34
+ const user = requestingUser(connection);
35
+ const request = (typeof message.REQUEST === 'object' && message.REQUEST) || message.DETAILS?.REQUEST || {};
36
+ try {
37
+ let rows;
38
+ if (requestReply.resolver) {
39
+ // Computed reply (date calcs, holiday roll, composite lookups...): the
40
+ // resolver owns REQUEST interpretation entirely — no generic REQUEST/
41
+ // CRITERIA filtering is applied on top, since a computed reply's rows
42
+ // needn't echo the request's fields at all.
43
+ rows = requestReply.resolver({ request, message, user, store });
44
+ }
45
+ else {
46
+ rows = store.getResourceRows(requestReply.source);
47
+ if (Object.keys(request).length > 0) {
48
+ rows = rows.filter((row) => matchesRequestFields(row, request));
49
+ }
50
+ const criteria = message.DETAILS?.CRITERIA_MATCH ?? message.CRITERIA_MATCH;
51
+ if (criteria)
52
+ rows = filterByCriteria(rows, criteria);
53
+ if (requestReply.filter)
54
+ rows = rows.filter(requestReply.filter);
55
+ }
56
+ rows = applyResourceAuth(rows, requestReply.auth, user);
57
+ connection.reply(message, {
58
+ MESSAGE_TYPE: `REP_${resourceName}`,
59
+ REPLY: rows,
60
+ });
61
+ }
62
+ catch (error) {
63
+ const errors = error instanceof NackError
64
+ ? error.errors
65
+ : [{ CODE: ERROR_CODE.VALIDATION_ERROR, TEXT: error.message }];
66
+ connection.reply(message, { MESSAGE_TYPE: `REP_${resourceName}`, ERROR: errors });
67
+ }
68
+ }
@@ -0,0 +1,5 @@
1
+ import type { Connection } from '../protocol/connection.ts';
2
+ import type { ResourceAuthDef, RequestingUser, Row } from '../types.ts';
3
+ export declare function requestingUser(connection: Connection): RequestingUser;
4
+ export declare function hiddenFields(auth: ResourceAuthDef | undefined, user: RequestingUser): Set<string>;
5
+ export declare function applyResourceAuth(rows: Row[], auth: ResourceAuthDef | undefined, user: RequestingUser): Row[];
@@ -0,0 +1,27 @@
1
+ // The identity a resource-level auth hook (rowFilter/hideFields) sees for the
2
+ // requesting connection. userName is undefined for unauthenticated
3
+ // connections — possible when requireAuth is off, or pre-login.
4
+ export function requestingUser(connection) {
5
+ return {
6
+ userName: connection.userName,
7
+ profile: connection.profile,
8
+ permission: connection.permission,
9
+ };
10
+ }
11
+ export function hiddenFields(auth, user) {
12
+ const fields = typeof auth?.hideFields === 'function' ? auth.hideFields(user) : auth?.hideFields;
13
+ return new Set(fields ?? []);
14
+ }
15
+ // Applies a resource's permissioning to a reply/snapshot row set: drops rows
16
+ // the user's rowFilter rejects, then strips hidden fields from what's left.
17
+ // Mirrors dataserver auth maps + hideFields on the real server.
18
+ export function applyResourceAuth(rows, auth, user) {
19
+ if (!auth)
20
+ return rows;
21
+ let result = auth.rowFilter ? rows.filter((row) => auth.rowFilter(row, user)) : rows;
22
+ const hidden = hiddenFields(auth, user);
23
+ if (hidden.size > 0) {
24
+ result = result.map((row) => Object.fromEntries(Object.entries(row).filter(([field]) => !hidden.has(field))));
25
+ }
26
+ return result;
27
+ }
@@ -0,0 +1,3 @@
1
+ import type { Connection } from '../protocol/connection.ts';
2
+ import type { GenesisMessage, MockServerConfig } from '../types.ts';
3
+ export declare function handleResourcesRequest(message: GenesisMessage, connection: Connection, config: MockServerConfig): void;
@@ -0,0 +1,34 @@
1
+ import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
2
+ // GenesisResources (foundation-comms/src/resources/genesis/genesis.ts) gates
3
+ // every datasource/request-reply/commit call on this list first — an empty
4
+ // or missing RESOURCES_REQUEST_ACK.RESOURCES makes every resource silently
5
+ // "not exist" client-side, before META_REQUEST or DATA_LOGON is ever tried.
6
+ // Auto-derive it from config.queries/requestReplies/eventHandlers (same
7
+ // philosophy as db/metadata.ts's field inference) so projects don't have to
8
+ // hand-maintain a redundant list; set config.resources explicitly to override.
9
+ function deriveResources(config) {
10
+ const resources = [];
11
+ for (const name of Object.keys(config.queries ?? {})) {
12
+ resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'DATASERVER' });
13
+ }
14
+ for (const name of Object.keys(config.requestReplies ?? {})) {
15
+ resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'REQUEST_SERVER' });
16
+ }
17
+ const eventNames = new Set([
18
+ ...Object.keys(config.eventHandlers ?? {}),
19
+ // Events served only by eventSchemas + defaultEventHandler still need to
20
+ // be discoverable, or the client-side resource gate blocks them before
21
+ // the commit is ever sent.
22
+ ...Object.keys(config.eventSchemas ?? {}),
23
+ ]);
24
+ for (const name of eventNames) {
25
+ resources.push({ RESOURCE_NAME: name, RESOURCE_TYPE: 'EVENT_HANDLER' });
26
+ }
27
+ return resources;
28
+ }
29
+ export function handleResourcesRequest(message, connection, config) {
30
+ connection.reply(message, {
31
+ MESSAGE_TYPE: MESSAGE_TYPE.RESOURCES_REQUEST_ACK,
32
+ RESOURCES: config.resources ?? deriveResources(config),
33
+ });
34
+ }
@@ -0,0 +1,6 @@
1
+ export { createMockServer, type MockServer } from './server.ts';
2
+ export { launchStack, type LaunchStackOptions, type LaunchedStack } from './launch.ts';
3
+ export { Store } from './db/store.ts';
4
+ export { NackError, type NackErrorInput, type NackErrorEntry } from './protocol/errors.ts';
5
+ export { compileCriteria, filterByCriteria, type Predicate } from './db/criteria.ts';
6
+ export type { AntiJoinDef, AuthConfig, AuthUser, BroadcastFn, BroadcastTableChangeFn, EventHandler, EventHandlerCtx, EventHandlerResult, EventSchemaOverride, FieldMetadata, GenesisMessage, HttpRouteDef, JoinDef, MockServerConfig, OnMessageCtx, OnMessageHook, QueryDef, RequestingUser, RequestReplyDef, RequestReplyResolverCtx, ResourceAuthDef, ResourceItem, Row, SocketLike, SsoIdentityProvider, TableDef, ViewDef, } from './types.ts';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { createMockServer } from "./server.js";
2
+ export { launchStack } from "./launch.js";
3
+ export { Store } from "./db/store.js";
4
+ export { NackError } from "./protocol/errors.js";
5
+ export { compileCriteria, filterByCriteria } from "./db/criteria.js";
@@ -0,0 +1,19 @@
1
+ import { type ChildProcess } from 'node:child_process';
2
+ import { type MockServer } from './server.ts';
3
+ import type { MockServerConfig } from './types.ts';
4
+ export interface LaunchStackOptions {
5
+ config: MockServerConfig;
6
+ clientCommand: string | string[];
7
+ port?: number;
8
+ cwd?: string;
9
+ clientEnv?: (port: number) => Record<string, string>;
10
+ tieLifetimes?: boolean;
11
+ }
12
+ export interface LaunchedStack {
13
+ server: MockServer;
14
+ port: number;
15
+ client: ChildProcess;
16
+ clientExited: Promise<number | null>;
17
+ stop(): Promise<void>;
18
+ }
19
+ export declare function launchStack(options: LaunchStackOptions): Promise<LaunchedStack>;
package/dist/launch.js ADDED
@@ -0,0 +1,59 @@
1
+ // One-command dev stack: boot a mock server (ephemeral port by default) and
2
+ // spawn the client dev command pointed at it, with tied lifetimes — so
3
+ // several server+client pairs can run on one machine without hand-assigning
4
+ // ports or orphaning processes.
5
+ import { spawn } from 'node:child_process';
6
+ import { createMockServer } from "./server.js";
7
+ export async function launchStack(options) {
8
+ const { config, clientCommand, port = 0, cwd, clientEnv, tieLifetimes = true } = options;
9
+ const server = createMockServer(config);
10
+ const boundPort = await server.listen(port);
11
+ const env = {
12
+ ...process.env,
13
+ API_HOST: `ws://localhost:${boundPort}`,
14
+ ...clientEnv?.(boundPort),
15
+ };
16
+ const client = Array.isArray(clientCommand)
17
+ ? spawn(clientCommand[0], clientCommand.slice(1), { cwd, env, stdio: 'inherit' })
18
+ : spawn(clientCommand, { cwd, env, stdio: 'inherit', shell: true });
19
+ let stopping = false;
20
+ async function stop() {
21
+ if (stopping)
22
+ return;
23
+ stopping = true;
24
+ if (client.exitCode === null && !client.killed)
25
+ client.kill('SIGINT');
26
+ await server.stop();
27
+ }
28
+ const clientExited = new Promise((resolve) => {
29
+ client.once('exit', (code) => {
30
+ const finish = () => resolve(code);
31
+ if (tieLifetimes) {
32
+ stopping = true;
33
+ server.stop().then(finish, finish);
34
+ }
35
+ else {
36
+ finish();
37
+ }
38
+ });
39
+ client.once('error', (error) => {
40
+ console.error('[mock-server] Failed to spawn client command:', error);
41
+ const finish = () => resolve(null);
42
+ if (tieLifetimes) {
43
+ stopping = true;
44
+ server.stop().then(finish, finish);
45
+ }
46
+ else {
47
+ finish();
48
+ }
49
+ });
50
+ });
51
+ if (tieLifetimes) {
52
+ const onSignal = () => {
53
+ void stop();
54
+ };
55
+ process.once('SIGINT', onSignal);
56
+ process.once('SIGTERM', onSignal);
57
+ }
58
+ return { server, port: boundPort, client, clientExited, stop };
59
+ }
@@ -0,0 +1,24 @@
1
+ import type { Predicate } from '../db/criteria.ts';
2
+ import type { GenesisMessage, Row, SocketLike } from '../types.ts';
3
+ export interface Subscription {
4
+ resourceName: string;
5
+ getRowRef: (row: Row) => unknown;
6
+ predicate: Predicate;
7
+ sequenceId: number;
8
+ }
9
+ export declare class Connection {
10
+ readonly ws: SocketLike;
11
+ readonly id: `${string}-${string}-${string}-${string}-${string}`;
12
+ authenticated: boolean;
13
+ sessionAuthToken: string | undefined;
14
+ sessionId: string | undefined;
15
+ userName: string | undefined;
16
+ profile: string[];
17
+ permission: string[];
18
+ readonly subscriptions: Map<string, Subscription>;
19
+ constructor(ws: SocketLike);
20
+ send(payload: Row): void;
21
+ reply(requestMessage: GenesisMessage, payload: Row): void;
22
+ subscribe(sourceRef: string, subscription: Subscription): void;
23
+ unsubscribe(sourceRef: string): void;
24
+ }
@@ -0,0 +1,35 @@
1
+ import crypto from 'node:crypto';
2
+ const WS_OPEN = 1;
3
+ // Wraps one WebSocket client connection: auth state and its live DATA_LOGON
4
+ // subscriptions (keyed by SOURCE_REF, since that's the client's sole correlation
5
+ // key — see README pitfall #1).
6
+ export class Connection {
7
+ ws;
8
+ id = crypto.randomUUID();
9
+ authenticated = false;
10
+ sessionAuthToken;
11
+ sessionId;
12
+ userName;
13
+ profile = [];
14
+ permission = [];
15
+ subscriptions = new Map();
16
+ constructor(ws) {
17
+ this.ws = ws;
18
+ }
19
+ // Every response must echo the request's SOURCE_REF verbatim, or the client's
20
+ // pending promise for that call never resolves (silent hang, no error).
21
+ send(payload) {
22
+ if (this.ws.readyState !== WS_OPEN)
23
+ return;
24
+ this.ws.send(JSON.stringify(payload));
25
+ }
26
+ reply(requestMessage, payload) {
27
+ this.send({ ...payload, SOURCE_REF: requestMessage.SOURCE_REF });
28
+ }
29
+ subscribe(sourceRef, subscription) {
30
+ this.subscriptions.set(sourceRef, subscription);
31
+ }
32
+ unsubscribe(sourceRef) {
33
+ this.subscriptions.delete(sourceRef);
34
+ }
35
+ }
@@ -0,0 +1,17 @@
1
+ export interface NackErrorInput {
2
+ CODE?: string;
3
+ code?: string;
4
+ TEXT?: string;
5
+ text?: string;
6
+ FIELD?: string;
7
+ field?: string;
8
+ }
9
+ export interface NackErrorEntry {
10
+ CODE: string;
11
+ TEXT: string;
12
+ FIELD?: string;
13
+ }
14
+ export declare class NackError extends Error {
15
+ readonly errors: NackErrorEntry[];
16
+ constructor(errors: NackErrorInput | NackErrorInput[]);
17
+ }
@@ -0,0 +1,16 @@
1
+ // Throw this from an event handler / request-reply resolver to produce a
2
+ // protocol-correct *_NACK with ERROR as an array of {CODE, TEXT, FIELD?} —
3
+ // never {error, details} (lowercase, non-array), which crashes real clients
4
+ // calling .forEach on the wrong shape.
5
+ export class NackError extends Error {
6
+ errors;
7
+ constructor(errors) {
8
+ const list = Array.isArray(errors) ? errors : [errors];
9
+ super(list.map((e) => e.TEXT ?? e.text ?? 'Unknown error').join(', '));
10
+ this.errors = list.map((e) => ({
11
+ CODE: e.CODE ?? e.code ?? 'VALIDATION_ERROR',
12
+ TEXT: e.TEXT ?? e.text ?? 'Unknown error',
13
+ ...(e.FIELD || e.field ? { FIELD: e.FIELD ?? e.field } : {}),
14
+ }));
15
+ }
16
+ }