@genesislcap/mock-server 15.65.1-alpha-358eaead70.0 → 15.67.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 (51) hide show
  1. package/README.md +120 -4
  2. package/dist/handlers/auth.d.ts +24 -5
  3. package/dist/handlers/auth.js +196 -43
  4. package/dist/handlers/heartbeat.d.ts +2 -1
  5. package/dist/handlers/heartbeat.js +26 -3
  6. package/dist/handlers/http.d.ts +6 -3
  7. package/dist/handlers/http.js +266 -91
  8. package/dist/handlers/resources.d.ts +2 -1
  9. package/dist/handlers/resources.js +18 -2
  10. package/dist/index.d.ts +1 -1
  11. package/dist/presets/csv.d.ts +2 -0
  12. package/dist/presets/csv.js +52 -0
  13. package/dist/presets/index.d.ts +3 -0
  14. package/dist/presets/index.js +3 -0
  15. package/dist/presets/merge.d.ts +15 -0
  16. package/dist/presets/merge.js +76 -0
  17. package/dist/presets/platform/default-user.json +30 -0
  18. package/dist/presets/platform/profile-rights.json +242 -0
  19. package/dist/presets/platform/profiles.json +62 -0
  20. package/dist/presets/platform/resources.json +710 -0
  21. package/dist/presets/platform/rights.json +238 -0
  22. package/dist/presets/platform.d.ts +27 -0
  23. package/dist/presets/platform.js +410 -0
  24. package/dist/protocol/connection.d.ts +10 -2
  25. package/dist/protocol/connection.js +69 -3
  26. package/dist/protocol/msgNack.d.ts +2 -0
  27. package/dist/protocol/msgNack.js +18 -0
  28. package/dist/protocol/router.d.ts +2 -2
  29. package/dist/protocol/router.js +24 -7
  30. package/dist/server.js +30 -12
  31. package/dist/types.d.ts +18 -0
  32. package/package.json +8 -2
  33. package/src/handlers/auth.ts +232 -44
  34. package/src/handlers/heartbeat.ts +38 -4
  35. package/src/handlers/http.ts +317 -103
  36. package/src/handlers/resources.ts +19 -2
  37. package/src/index.ts +2 -0
  38. package/src/presets/csv.ts +50 -0
  39. package/src/presets/index.ts +8 -0
  40. package/src/presets/merge.ts +79 -0
  41. package/src/presets/platform/default-user.json +30 -0
  42. package/src/presets/platform/profile-rights.json +242 -0
  43. package/src/presets/platform/profiles.json +62 -0
  44. package/src/presets/platform/resources.json +710 -0
  45. package/src/presets/platform/rights.json +238 -0
  46. package/src/presets/platform.ts +503 -0
  47. package/src/protocol/connection.ts +77 -3
  48. package/src/protocol/msgNack.ts +25 -0
  49. package/src/protocol/router.ts +31 -8
  50. package/src/server.ts +35 -12
  51. package/src/types.ts +69 -3
@@ -1,17 +1,37 @@
1
1
  import crypto from 'node:crypto';
2
2
  import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import { isLegacyFidelity } from '../protocol/fidelity.ts';
3
4
  import { MESSAGE_TYPE } from '../protocol/messageTypes.ts';
4
- import type { MockServerConfig } from '../types.ts';
5
+ import { notLoggedInNack } from '../protocol/msgNack.ts';
6
+ import type { AuthUser, CookieAuthenticationOptions, MockServerConfig, Row } from '../types.ts';
5
7
  import {
6
8
  buildLoginAckBody,
9
+ buildLoginNackBody,
10
+ buildLogoutAckBody,
7
11
  capRegistry,
12
+ closeSession,
13
+ createAuthState,
8
14
  findUser,
9
15
  findUserByCredentials,
10
- registerAckTokens,
11
- type TokenRegistry,
16
+ openSession,
17
+ refreshTokenExpirationMins,
18
+ sessionByRefreshToken,
19
+ sessionTimeoutMins,
20
+ type AuthSession,
21
+ type AuthState,
12
22
  } from './auth.ts';
13
23
 
14
- const SESSION_COOKIE = 'MOCK_SESSION_ID';
24
+ // fidelity: 'legacy' without cookieAuthentication: the mock's own session
25
+ // cookie, sessionId -> username.
26
+ const LEGACY_SESSION_COOKIE = 'MOCK_SESSION_ID';
27
+ // genesis-router CookieHandler.kt:195-202 @v8.15.29.
28
+ export const SESSION_AUTH_TOKEN_COOKIE = 'sessionAuthToken';
29
+ const REFRESH_AUTH_TOKEN_COOKIE = 'refreshAuthToken';
30
+ const SESSION_ID_COOKIE = 'sessionId';
31
+ const MFA_CODE_COOKIE = 'mfaCode';
32
+
33
+ const SECONDS_PER_MINUTE = 60;
34
+ const MILLIS_PER_SECOND = 1000;
15
35
 
16
36
  const HTTP_STATUS = {
17
37
  OK: 200,
@@ -20,16 +40,35 @@ const HTTP_STATUS = {
20
40
  INTERNAL_SERVER_ERROR: 500,
21
41
  };
22
42
 
43
+ // The `cookieAuthentication { }` block GSF ships in genesis-router.kts.
44
+ const SHIPPED_COOKIE_OPTIONS: Required<Omit<CookieAuthenticationOptions, 'domain'>> = {
45
+ httpOnly: true,
46
+ secure: false,
47
+ sameSite: 'Lax',
48
+ path: '/',
49
+ sessionCookies: false,
50
+ };
51
+
52
+ export function cookieAuthentication(
53
+ config: MockServerConfig,
54
+ ): CookieAuthenticationOptions | undefined {
55
+ // On unless the config opts out, as GSF ships it; off under fidelity: 'legacy'.
56
+ const option = config.auth?.cookieAuthentication ?? !isLegacyFidelity(config);
57
+ if (!option) return undefined;
58
+ return option === true ? SHIPPED_COOKIE_OPTIONS : { ...SHIPPED_COOKIE_OPTIONS, ...option };
59
+ }
60
+
23
61
  // foundation-auth's login UI (client-app-login) doesn't use the WebSocket
24
62
  // EVENT_LOGIN_AUTH flow at all — it POSTs credentials over plain HTTP to
25
- // gwf/event-login-auth, and separately GETs gwf/event-login-details on every
26
- // app load (cookie-based silent login: foundation-comms/src/connect/
27
- // sessionRefresh.ts's isAuthenticated()). Both expect the exact same ACK body
28
- // shape as the WS login (EVENT_LOGIN_DETAILS_ACK literally extends
29
- // EVENT_LOGIN_AUTH_ACK), just reached over HTTP with a session cookie instead
30
- // of SOURCE_REF correlation. This is a *separate* transport from the WS
31
- // protocol in server.ts — a client-app can use either, or (as here) both.
32
- function parseCookies(header: string | undefined): Record<string, string> {
63
+ // gwf/event-login-auth, and separately POSTs gwf/event-login-details on every
64
+ // app load (silent login; foundation-comms/src/connect/sessionRefresh.ts's
65
+ // isAuthenticated() GETs it later). Both expect the same ACK body as the WS
66
+ // login (EVENT_LOGIN_DETAILS_ACK literally extends EVENT_LOGIN_AUTH_ACK), with
67
+ // the session named by a cookie (cookieAuthentication) or a SESSION_AUTH_TOKEN
68
+ // header instead of SOURCE_REF correlation. This is a *separate* transport
69
+ // from the WS protocol in server.ts — a client-app can use either, or (as
70
+ // here) both.
71
+ export function parseCookies(header: string | undefined): Record<string, string> {
33
72
  const cookies: Record<string, string> = {};
34
73
  for (const part of (header ?? '').split(';')) {
35
74
  const [key, ...rest] = part.trim().split('=');
@@ -38,11 +77,76 @@ function parseCookies(header: string | undefined): Record<string, string> {
38
77
  return cookies;
39
78
  }
40
79
 
41
- function setSessionCookie(res: ServerResponse, sessionId: string): void {
42
- res.setHeader('Set-Cookie', `${SESSION_COOKIE}=${sessionId}; Path=/; SameSite=Lax`);
80
+ // As Netty's ServerCookieEncoder.STRICT writes it (CookieHandler.kt:178-192
81
+ // @v8.15.29): Max-Age and Expires unless it is a session cookie, then Path,
82
+ // Domain, Secure, HTTPOnly, SameSite.
83
+ function encodeCookie(
84
+ options: CookieAuthenticationOptions,
85
+ name: string,
86
+ value: string,
87
+ maxAgeSecs: number | undefined,
88
+ ): string {
89
+ const parts = [`${name}=${value}`];
90
+ if (maxAgeSecs !== undefined) {
91
+ const expires = new Date(Date.now() + maxAgeSecs * MILLIS_PER_SECOND);
92
+ parts.push(`Max-Age=${maxAgeSecs}`, `Expires=${expires.toUTCString()}`);
93
+ }
94
+ if (options.path) parts.push(`Path=${options.path}`);
95
+ if (options.domain) parts.push(`Domain=${options.domain}`);
96
+ if (options.secure) parts.push('Secure');
97
+ if (options.httpOnly) parts.push('HTTPOnly');
98
+ if (options.sameSite) parts.push(`SameSite=${options.sameSite}`);
99
+ return parts.join('; ');
100
+ }
101
+
102
+ // The cookies GSF's router sets on an EVENT_LOGIN_AUTH_ACK
103
+ // (CookieHandler.kt:91-130): the session token lives as long as the session,
104
+ // the refresh token and session id as long as the refresh token, and the
105
+ // unused MFA code expires at once.
106
+ function loginCookies(
107
+ options: CookieAuthenticationOptions,
108
+ config: MockServerConfig,
109
+ session: AuthSession,
110
+ ): string[] {
111
+ const sessionMaxAge = options.sessionCookies
112
+ ? undefined
113
+ : sessionTimeoutMins(config) * SECONDS_PER_MINUTE;
114
+ const refreshMaxAge = options.sessionCookies
115
+ ? undefined
116
+ : refreshTokenExpirationMins(config) * SECONDS_PER_MINUTE;
117
+ return [
118
+ encodeCookie(options, SESSION_AUTH_TOKEN_COOKIE, session.sessionAuthToken, sessionMaxAge),
119
+ encodeCookie(options, REFRESH_AUTH_TOKEN_COOKIE, session.refreshAuthToken, refreshMaxAge),
120
+ encodeCookie(options, SESSION_ID_COOKIE, session.sessionId, refreshMaxAge),
121
+ encodeCookie(options, MFA_CODE_COOKIE, '', 0),
122
+ ];
43
123
  }
44
124
 
45
- function sendJson(res: ServerResponse, status: number, body: unknown): void {
125
+ // On EVENT_LOGIN_AUTH_NACK the router sets the NACK's REFRESH_AUTH_TOKEN
126
+ // (null) for its REFRESH_TOKEN_EXPIRATION_MINS (null): an empty cookie that
127
+ // expires at once (CookieHandler.kt:132-139); recorded in
128
+ // http-login-failed.json.
129
+ function loginNackCookies(options: CookieAuthenticationOptions): string[] {
130
+ return [encodeCookie(options, REFRESH_AUTH_TOKEN_COOKIE, '', 0)];
131
+ }
132
+
133
+ // LOGOUT_ACK expires all four (CookieHandler.kt:141-147).
134
+ function logoutCookies(options: CookieAuthenticationOptions): string[] {
135
+ return [
136
+ SESSION_AUTH_TOKEN_COOKIE,
137
+ REFRESH_AUTH_TOKEN_COOKIE,
138
+ SESSION_ID_COOKIE,
139
+ MFA_CODE_COOKIE,
140
+ ].map((name) => encodeCookie(options, name, '', 0));
141
+ }
142
+
143
+ function sendJson(
144
+ res: ServerResponse,
145
+ status: number,
146
+ body: unknown,
147
+ cookies: string[] = [],
148
+ ): void {
149
+ if (cookies.length > 0) res.setHeader('Set-Cookie', cookies);
46
150
  res.writeHead(status, { 'Content-Type': 'application/json' });
47
151
  res.end(JSON.stringify(body));
48
152
  }
@@ -65,36 +169,207 @@ async function readJsonBody(req: IncomingMessage): Promise<Record<string, any>>
65
169
  return raw ? JSON.parse(raw) : {};
66
170
  }
67
171
 
68
- // Drops every token this server minted for `username`. Logout has to do this,
69
- // not just forget the session: router.ts re-adopts any known SESSION_AUTH_TOKEN
70
- // on every message, so a token left in the registry logs a WS connection
71
- // straight back in on its next request.
72
- function revokeTokensFor(tokens: TokenRegistry, username: string): void {
73
- for (const [token, owner] of tokens) {
74
- if (owner === username) tokens.delete(token);
172
+ // A header the client may send as SESSION_AUTH_TOKEN or, as foundation-comms'
173
+ // createHTTPHeadersFromMessage does, SESSION-AUTH-TOKEN.
174
+ function headerValue(req: IncomingMessage, name: string): string | undefined {
175
+ const value =
176
+ req.headers[name.toLowerCase()] ?? req.headers[name.toLowerCase().replaceAll('_', '-')];
177
+ return typeof value === 'string' ? value : undefined;
178
+ }
179
+
180
+ function autoLoginUser(config: MockServerConfig): AuthUser | undefined {
181
+ const autoLogin = config.auth?.httpAutoLogin;
182
+ if (!autoLogin) return undefined;
183
+ return findUser(config, autoLogin === true ? config.auth?.users?.[0]?.username : autoLogin);
184
+ }
185
+
186
+ // Drops every token this server minted for `username` (fidelity: 'legacy',
187
+ // whose logout ends all of the user's sessions).
188
+ function revokeSessionsOf(auth: AuthState, username: string): void {
189
+ for (const session of auth.sessions.values()) {
190
+ if (session.username === username) closeSession(auth, session);
191
+ }
192
+ for (const [token, owner] of auth.tokens) {
193
+ if (owner === username) auth.tokens.delete(token);
75
194
  }
76
195
  }
77
196
 
78
- // Reuse the request's own session when its cookie already maps to this user —
79
- // otherwise every page load would mint (and leak) a fresh session entry on a
80
- // long-lived dev/CI server.
81
- function ensureSession(
82
- sessions: Map<string, string>,
197
+ // fidelity: 'legacy': reuse the request's MOCK_SESSION_ID when it already maps
198
+ // to this user — otherwise every page load would mint (and leak) a fresh
199
+ // session entry on a long-lived dev/CI server.
200
+ function ensureLegacySession(
201
+ legacySessions: Map<string, string>,
83
202
  cookieSessionId: string | undefined,
84
203
  username: string,
85
204
  ): string {
86
- if (cookieSessionId && sessions.get(cookieSessionId) === username) return cookieSessionId;
205
+ if (cookieSessionId && legacySessions.get(cookieSessionId) === username) return cookieSessionId;
87
206
  const sessionId = crypto.randomUUID();
88
- sessions.set(sessionId, username);
89
- capRegistry(sessions);
207
+ legacySessions.set(sessionId, username);
208
+ capRegistry(legacySessions);
90
209
  return sessionId;
91
210
  }
92
211
 
212
+ function legacySessionCookie(sessionId: string): string {
213
+ return `${LEGACY_SESSION_COOKIE}=${sessionId}; Path=/; SameSite=Lax`;
214
+ }
215
+
93
216
  export function createHttpRequestListener(
94
217
  config: MockServerConfig,
95
- sessions: Map<string, string>,
96
- tokens: TokenRegistry = new Map(),
218
+ legacySessions: Map<string, string>,
219
+ auth: AuthState = createAuthState(),
97
220
  ) {
221
+ // Every HTTP reply carries a SOURCE_REF: the request's, or AUTO_<uuid> as
222
+ // the router mints one (http-login.json). Not under fidelity: 'legacy'.
223
+ const withSourceRef = (body: Row, request: Row = {}): Row =>
224
+ isLegacyFidelity(config)
225
+ ? body
226
+ : { ...body, SOURCE_REF: request.SOURCE_REF ?? `AUTO_${crypto.randomUUID()}` };
227
+
228
+ // The session a request names: the sessionAuthToken cookie under
229
+ // cookieAuthentication, else (GSF) the SESSION_AUTH_TOKEN header. '' when
230
+ // the cookie is there but empty, as after a logout cleared it.
231
+ function requestToken(req: IncomingMessage, cookies: Record<string, string>): string | undefined {
232
+ if (cookieAuthentication(config)) return cookies[SESSION_AUTH_TOKEN_COOKIE];
233
+ return headerValue(req, 'SESSION_AUTH_TOKEN');
234
+ }
235
+
236
+ // The legacy-mode session cookie, or none.
237
+ function legacyCookies(cookies: Record<string, string>, username: string): string[] {
238
+ if (!isLegacyFidelity(config) || cookieAuthentication(config)) return [];
239
+ return [
240
+ legacySessionCookie(
241
+ ensureLegacySession(legacySessions, cookies[LEGACY_SESSION_COOKIE], username),
242
+ ),
243
+ ];
244
+ }
245
+
246
+ // A session opened by a login (or an httpAutoLogin): the login cookies.
247
+ function sessionCookies(cookies: Record<string, string>, session: AuthSession): string[] {
248
+ const options = cookieAuthentication(config);
249
+ return options
250
+ ? loginCookies(options, config, session)
251
+ : legacyCookies(cookies, session.username);
252
+ }
253
+
254
+ function handleLoginDetails(req: IncomingMessage, res: ServerResponse, request: Row): void {
255
+ const cookies = parseCookies(req.headers.cookie);
256
+ const legacyWithoutCookies = isLegacyFidelity(config) && !cookieAuthentication(config);
257
+ const autoLogin = autoLoginUser(config);
258
+
259
+ // fidelity: 'legacy' without cookieAuthentication: as up to 15.47, a new
260
+ // session per call, found by the MOCK_SESSION_ID cookie.
261
+ if (legacyWithoutCookies) {
262
+ const user =
263
+ autoLogin ?? findUser(config, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
264
+ if (!user) {
265
+ sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
266
+ MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
267
+ ERROR: [
268
+ { CODE: 'NOT_LOGGED_ON', STATUS_CODE: '401 Unauthorized', TEXT: 'No active session' },
269
+ ],
270
+ });
271
+ return;
272
+ }
273
+ const session = openSession(auth, user);
274
+ const body = buildLoginAckBody(user, session, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
275
+ sendJson(res, HTTP_STATUS.OK, body, legacyCookies(cookies, user.username));
276
+ return;
277
+ }
278
+
279
+ const token = requestToken(req, cookies);
280
+ const session = token === undefined ? undefined : auth.sessions.get(token);
281
+ const sessionUser = session && findUser(config, session.username);
282
+ if (session && sessionUser) {
283
+ const body = buildLoginAckBody(sessionUser, session, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
284
+ sendJson(res, HTTP_STATUS.OK, withSourceRef(body, request));
285
+ return;
286
+ }
287
+ // httpAutoLogin: a request without a live session logs the user in.
288
+ if (autoLogin) {
289
+ const opened = openSession(auth, autoLogin);
290
+ const body = buildLoginAckBody(autoLogin, opened, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
291
+ sendJson(res, HTTP_STATUS.OK, withSourceRef(body, request), sessionCookies(cookies, opened));
292
+ return;
293
+ }
294
+ sendJson(
295
+ res,
296
+ HTTP_STATUS.UNAUTHORIZED,
297
+ withSourceRef(notLoggedInNack(token !== undefined), request),
298
+ );
299
+ }
300
+
301
+ async function handleLoginAuth(req: IncomingMessage, res: ServerResponse): Promise<void> {
302
+ const body = await readJsonBody(req);
303
+ const details = body.DETAILS ?? {};
304
+ const cookies = parseCookies(req.headers.cookie);
305
+ const cookieOptions = cookieAuthentication(config);
306
+
307
+ // No USER_NAME: a token refresh (foundation-comms' sessionRefresh
308
+ // performRefresh). Its refresh token is the refreshAuthToken cookie under
309
+ // cookieAuthentication (CookieHandler.kt:62-67), else DETAILS'; under
310
+ // fidelity: 'legacy' without cookies, the MOCK_SESSION_ID session.
311
+ let user: AuthUser | undefined;
312
+ if (details.USER_NAME !== undefined) {
313
+ user = findUserByCredentials(config, details.USER_NAME, details.PASSWORD);
314
+ } else if (isLegacyFidelity(config) && !cookieOptions) {
315
+ user = findUser(config, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
316
+ } else {
317
+ const refreshToken = cookieOptions
318
+ ? cookies[REFRESH_AUTH_TOKEN_COOKIE]
319
+ : (details.REFRESH_AUTH_TOKEN ?? headerValue(req, 'REFRESH_AUTH_TOKEN'));
320
+ user = findUser(config, sessionByRefreshToken(auth, refreshToken)?.username);
321
+ }
322
+
323
+ if (!user) {
324
+ // GSF answers a failed login with HTTP 200; fidelity: 'legacy' with 401.
325
+ const status = isLegacyFidelity(config) ? HTTP_STATUS.UNAUTHORIZED : HTTP_STATUS.OK;
326
+ const nackCookies = cookieOptions ? loginNackCookies(cookieOptions) : [];
327
+ sendJson(res, status, withSourceRef(buildLoginNackBody(config, 'http'), body), nackCookies);
328
+ return;
329
+ }
330
+
331
+ const session = openSession(auth, user);
332
+ const ack = buildLoginAckBody(user, session, config, auth);
333
+ sendJson(res, HTTP_STATUS.OK, withSourceRef(ack, body), sessionCookies(cookies, session));
334
+ }
335
+
336
+ async function handleLogout(req: IncomingMessage, res: ServerResponse): Promise<void> {
337
+ const body = await readJsonBody(req).catch(() => ({}) as Record<string, any>);
338
+ const cookies = parseCookies(req.headers.cookie);
339
+ const cookieOptions = cookieAuthentication(config);
340
+
341
+ if (isLegacyFidelity(config) && !cookieOptions) {
342
+ const sessionId = cookies[LEGACY_SESSION_COOKIE];
343
+ const username = legacySessions.get(sessionId);
344
+ legacySessions.delete(sessionId);
345
+ if (username !== undefined) revokeSessionsOf(auth, username);
346
+ sendJson(res, HTTP_STATUS.OK, buildLogoutAckBody(config));
347
+ return;
348
+ }
349
+
350
+ // auth's LOGOUT ends the session SESSION_ID names (the sessionId cookie
351
+ // under cookieAuthentication, CookieHandler.kt:76-81), else the token's.
352
+ const sessionId = cookieOptions
353
+ ? cookies[SESSION_ID_COOKIE]
354
+ : (body.SESSION_ID ?? headerValue(req, 'SESSION_ID'));
355
+ const token = cookieOptions ? cookies[SESSION_AUTH_TOKEN_COOKIE] : requestToken(req, cookies);
356
+ for (const session of auth.sessions.values()) {
357
+ if (session.sessionId === sessionId || session.sessionAuthToken === token) {
358
+ closeSession(auth, session);
359
+ }
360
+ }
361
+ if (isLegacyFidelity(config)) {
362
+ sendJson(res, HTTP_STATUS.OK, buildLogoutAckBody(config), logoutCookies(cookieOptions!));
363
+ return;
364
+ }
365
+ sendJson(
366
+ res,
367
+ HTTP_STATUS.OK,
368
+ withSourceRef(buildLogoutAckBody(config), body),
369
+ cookieOptions ? logoutCookies(cookieOptions) : [],
370
+ );
371
+ }
372
+
98
373
  return async function requestListener(req: IncomingMessage, res: ServerResponse): Promise<void> {
99
374
  const pathname = (req.url ?? '').split('?')[0];
100
375
 
@@ -126,89 +401,28 @@ export function createHttpRequestListener(
126
401
  return;
127
402
  }
128
403
 
129
- // Cookie-based silent login on app load — auto-authenticates as the
130
- // configured user when config.auth.httpAutoLogin is set, so the login
131
- // screen never appears (matches how a real session cookie would behave
132
- // once already logged in, but skips the manual login step entirely).
133
- // Two different call sites hit this path with different methods:
134
- // foundation-auth's fetch machine always POSTs (createFetchMachineEvent
135
- // hardcodes method: 'POST') on initial silent-login; foundation-comms'
136
- // sessionRefresh.ts's isAuthenticated() does a plain GET later, when
137
- // checking whether an expired session can be silently renewed.
404
+ // Silent login on app load. Two call sites hit this path with
405
+ // different methods: foundation-auth's fetch machine always POSTs
406
+ // (createFetchMachineEvent hardcodes method: 'POST') on initial
407
+ // silent-login; foundation-comms' sessionRefresh.ts's isAuthenticated()
408
+ // does a plain GET later, when checking whether an expired session can
409
+ // be silently renewed.
138
410
  if (
139
411
  (req.method === 'GET' || req.method === 'POST') &&
140
412
  pathname.endsWith('event-login-details')
141
413
  ) {
142
- const autoLoginUsername = config.auth?.httpAutoLogin;
143
- const cookies = parseCookies(req.headers.cookie);
144
- const user = autoLoginUsername
145
- ? findUser(
146
- config,
147
- autoLoginUsername === true ? config.auth?.users?.[0]?.username : autoLoginUsername,
148
- )
149
- : findUser(config, sessions.get(cookies[SESSION_COOKIE]));
150
-
151
- if (!user) {
152
- sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
153
- MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
154
- ERROR: [
155
- { CODE: 'NOT_LOGGED_ON', STATUS_CODE: '401 Unauthorized', TEXT: 'No active session' },
156
- ],
157
- });
158
- return;
159
- }
160
-
161
- const sessionId = ensureSession(sessions, cookies[SESSION_COOKIE], user.username);
162
- setSessionCookie(res, sessionId);
163
- const ack = buildLoginAckBody(user, config, 'EVENT_LOGIN_DETAILS_ACK');
164
- registerAckTokens(ack, user.username, tokens);
165
- sendJson(res, HTTP_STATUS.OK, ack);
414
+ const request = req.method === 'POST' ? await readJsonBody(req) : {};
415
+ handleLoginDetails(req, res, request);
166
416
  return;
167
417
  }
168
418
 
169
419
  if (req.method === 'POST' && pathname.endsWith('event-login-auth')) {
170
- const body = await readJsonBody(req);
171
- const details = body.DETAILS ?? {};
172
- const cookies = parseCookies(req.headers.cookie);
173
-
174
- // Empty DETAILS means a session-refresh ping (foundation-comms'
175
- // sessionRefresh.performRefresh), not a fresh credentials login —
176
- // honor it only if the request already carries a known session.
177
- const user =
178
- details.USER_NAME !== undefined
179
- ? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
180
- : findUser(config, sessions.get(cookies[SESSION_COOKIE]));
181
-
182
- if (!user) {
183
- sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
184
- MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
185
- ERROR: [
186
- {
187
- CODE: 'INCORRECT_CREDENTIALS',
188
- STATUS_CODE: '401 Unauthorized',
189
- TEXT: 'Problem logging in',
190
- },
191
- ],
192
- WARNING: [],
193
- });
194
- return;
195
- }
196
-
197
- const sessionId = ensureSession(sessions, cookies[SESSION_COOKIE], user.username);
198
- setSessionCookie(res, sessionId);
199
- const ack = buildLoginAckBody(user, config);
200
- registerAckTokens(ack, user.username, tokens);
201
- sendJson(res, HTTP_STATUS.OK, ack);
420
+ await handleLoginAuth(req, res);
202
421
  return;
203
422
  }
204
423
 
205
424
  if (req.method === 'POST' && pathname.endsWith('event-logout')) {
206
- const cookies = parseCookies(req.headers.cookie);
207
- const sessionId = cookies[SESSION_COOKIE];
208
- const username = sessions.get(sessionId);
209
- sessions.delete(sessionId);
210
- if (username !== undefined) revokeTokensFor(tokens, username);
211
- sendJson(res, HTTP_STATUS.OK, { MESSAGE_TYPE: 'LOGOUT_ACK' });
425
+ await handleLogout(req, res);
212
426
  return;
213
427
  }
214
428
 
@@ -9,7 +9,8 @@ import type { GenesisMessage, MockServerConfig, ResourceItem } from '../types.ts
9
9
  // "not exist" client-side, before META_REQUEST or DATA_LOGON is ever tried.
10
10
  // Auto-derive it from config.queries/requestReplies/eventHandlers (same
11
11
  // philosophy as db/metadata.ts's field inference) so projects don't have to
12
- // hand-maintain a redundant list; set config.resources explicitly to override.
12
+ // hand-maintain a redundant list; set config.resources explicitly to override,
13
+ // or config.additionalResources to add to it.
13
14
  function deriveResources(config: MockServerConfig): ResourceItem[] {
14
15
  const resources: ResourceItem[] = [];
15
16
  for (const name of Object.keys(config.queries ?? {})) {
@@ -33,6 +34,22 @@ function deriveResources(config: MockServerConfig): ResourceItem[] {
33
34
  return resources;
34
35
  }
35
36
 
37
+ const resourceKey = (resource: ResourceItem) =>
38
+ `${resource.RESOURCE_TYPE}:${resource.RESOURCE_NAME}`;
39
+
40
+ // The derived resources, then config.additionalResources not among them.
41
+ export function listResources(config: MockServerConfig): ResourceItem[] {
42
+ if (config.resources) return config.resources;
43
+ const resources = deriveResources(config);
44
+ const listed = new Set(resources.map(resourceKey));
45
+ for (const resource of config.additionalResources ?? []) {
46
+ if (listed.has(resourceKey(resource))) continue;
47
+ listed.add(resourceKey(resource));
48
+ resources.push(resource);
49
+ }
50
+ return resources;
51
+ }
52
+
36
53
  export function handleResourcesRequest(
37
54
  message: GenesisMessage,
38
55
  connection: Connection,
@@ -40,6 +57,6 @@ export function handleResourcesRequest(
40
57
  ): void {
41
58
  connection.reply(message, {
42
59
  MESSAGE_TYPE: MESSAGE_TYPE.RESOURCES_REQUEST_ACK,
43
- RESOURCES: config.resources ?? deriveResources(config),
60
+ RESOURCES: listResources(config),
44
61
  });
45
62
  }
package/src/index.ts CHANGED
@@ -24,6 +24,7 @@ export type {
24
24
  AuthUser,
25
25
  BroadcastFn,
26
26
  BroadcastTableChangeFn,
27
+ CookieAuthenticationOptions,
27
28
  CrudEventVerb,
28
29
  EventHandler,
29
30
  EventHandlerCtx,
@@ -46,6 +47,7 @@ export type {
46
47
  MockServerConfig,
47
48
  OnMessageCtx,
48
49
  OnMessageHook,
50
+ ProductDetails,
49
51
  QueryDef,
50
52
  RequestingUser,
51
53
  RequestReplyDef,
@@ -0,0 +1,50 @@
1
+ import type { Row } from '../types.ts';
2
+
3
+ // The rows of a GSF seed CSV (an app's or a PBC's data/*.csv): a header line,
4
+ // then one record per line; a value is bare or double-quoted ("" is a quote
5
+ // inside one). Values stay strings — a table's declared fields convert them
6
+ // when the rows are stored, as GSF's loader does. An empty cell is left out of
7
+ // its row (null), since SendTable sets only the non-empty cells
8
+ // (SendTableOperation.createRecord, genesis-db, GSF v8.15.29).
9
+ export function parseSeedCsv(text: string): Row[] {
10
+ const records: string[][] = [];
11
+ let record: string[] = [];
12
+ let field = '';
13
+ let quoted = false;
14
+ const endRecord = () => {
15
+ record.push(field);
16
+ if (record.some((value) => value !== '')) records.push(record);
17
+ record = [];
18
+ field = '';
19
+ };
20
+ for (let i = 0; i < text.length; i += 1) {
21
+ const char = text[i];
22
+ if (quoted) {
23
+ if (char === '"' && text[i + 1] === '"') {
24
+ field += '"';
25
+ i += 1;
26
+ } else if (char === '"') {
27
+ quoted = false;
28
+ } else {
29
+ field += char;
30
+ }
31
+ } else if (char === '"') {
32
+ quoted = true;
33
+ } else if (char === ',') {
34
+ record.push(field);
35
+ field = '';
36
+ } else if (char === '\n' || char === '\r') {
37
+ if (char === '\r' && text[i + 1] === '\n') i += 1;
38
+ endRecord();
39
+ } else {
40
+ field += char;
41
+ }
42
+ }
43
+ endRecord();
44
+ const [header = [], ...rows] = records;
45
+ return rows.map((values) =>
46
+ Object.fromEntries(
47
+ header.flatMap((name, i) => (values[i] ? [[name.trim(), values[i]] as const] : [])),
48
+ ),
49
+ );
50
+ }
@@ -0,0 +1,8 @@
1
+ export { parseSeedCsv } from './csv.ts';
2
+ export { mergeConfigs } from './merge.ts';
3
+ export {
4
+ platformPreset,
5
+ type PlatformPresetOptions,
6
+ type PlatformSeed,
7
+ type PlatformUser,
8
+ } from './platform.ts';