@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.
- package/README.md +120 -4
- package/dist/handlers/auth.d.ts +24 -5
- package/dist/handlers/auth.js +196 -43
- package/dist/handlers/heartbeat.d.ts +2 -1
- package/dist/handlers/heartbeat.js +26 -3
- package/dist/handlers/http.d.ts +6 -3
- package/dist/handlers/http.js +266 -91
- package/dist/handlers/resources.d.ts +2 -1
- package/dist/handlers/resources.js +18 -2
- package/dist/index.d.ts +1 -1
- package/dist/presets/csv.d.ts +2 -0
- package/dist/presets/csv.js +52 -0
- package/dist/presets/index.d.ts +3 -0
- package/dist/presets/index.js +3 -0
- package/dist/presets/merge.d.ts +15 -0
- package/dist/presets/merge.js +76 -0
- package/dist/presets/platform/default-user.json +30 -0
- package/dist/presets/platform/profile-rights.json +242 -0
- package/dist/presets/platform/profiles.json +62 -0
- package/dist/presets/platform/resources.json +710 -0
- package/dist/presets/platform/rights.json +238 -0
- package/dist/presets/platform.d.ts +27 -0
- package/dist/presets/platform.js +410 -0
- package/dist/protocol/connection.d.ts +10 -2
- package/dist/protocol/connection.js +69 -3
- package/dist/protocol/msgNack.d.ts +2 -0
- package/dist/protocol/msgNack.js +18 -0
- package/dist/protocol/router.d.ts +2 -2
- package/dist/protocol/router.js +24 -7
- package/dist/server.js +30 -12
- package/dist/types.d.ts +18 -0
- package/package.json +8 -2
- package/src/handlers/auth.ts +232 -44
- package/src/handlers/heartbeat.ts +38 -4
- package/src/handlers/http.ts +317 -103
- package/src/handlers/resources.ts +19 -2
- package/src/index.ts +2 -0
- package/src/presets/csv.ts +50 -0
- package/src/presets/index.ts +8 -0
- package/src/presets/merge.ts +79 -0
- package/src/presets/platform/default-user.json +30 -0
- package/src/presets/platform/profile-rights.json +242 -0
- package/src/presets/platform/profiles.json +62 -0
- package/src/presets/platform/resources.json +710 -0
- package/src/presets/platform/rights.json +238 -0
- package/src/presets/platform.ts +503 -0
- package/src/protocol/connection.ts +77 -3
- package/src/protocol/msgNack.ts +25 -0
- package/src/protocol/router.ts +31 -8
- package/src/server.ts +35 -12
- package/src/types.ts +69 -3
package/dist/handlers/http.js
CHANGED
|
@@ -1,23 +1,50 @@
|
|
|
1
1
|
import crypto from 'node:crypto';
|
|
2
|
+
import { isLegacyFidelity } from "../protocol/fidelity.js";
|
|
2
3
|
import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
|
|
3
|
-
import {
|
|
4
|
-
|
|
4
|
+
import { notLoggedInNack } from "../protocol/msgNack.js";
|
|
5
|
+
import { buildLoginAckBody, buildLoginNackBody, buildLogoutAckBody, capRegistry, closeSession, createAuthState, findUser, findUserByCredentials, openSession, refreshTokenExpirationMins, sessionByRefreshToken, sessionTimeoutMins, } from "./auth.js";
|
|
6
|
+
// fidelity: 'legacy' without cookieAuthentication: the mock's own session
|
|
7
|
+
// cookie, sessionId -> username.
|
|
8
|
+
const LEGACY_SESSION_COOKIE = 'MOCK_SESSION_ID';
|
|
9
|
+
// genesis-router CookieHandler.kt:195-202 @v8.15.29.
|
|
10
|
+
export const SESSION_AUTH_TOKEN_COOKIE = 'sessionAuthToken';
|
|
11
|
+
const REFRESH_AUTH_TOKEN_COOKIE = 'refreshAuthToken';
|
|
12
|
+
const SESSION_ID_COOKIE = 'sessionId';
|
|
13
|
+
const MFA_CODE_COOKIE = 'mfaCode';
|
|
14
|
+
const SECONDS_PER_MINUTE = 60;
|
|
15
|
+
const MILLIS_PER_SECOND = 1000;
|
|
5
16
|
const HTTP_STATUS = {
|
|
6
17
|
OK: 200,
|
|
7
18
|
UNAUTHORIZED: 401,
|
|
8
19
|
NOT_FOUND: 404,
|
|
9
20
|
INTERNAL_SERVER_ERROR: 500,
|
|
10
21
|
};
|
|
22
|
+
// The `cookieAuthentication { }` block GSF ships in genesis-router.kts.
|
|
23
|
+
const SHIPPED_COOKIE_OPTIONS = {
|
|
24
|
+
httpOnly: true,
|
|
25
|
+
secure: false,
|
|
26
|
+
sameSite: 'Lax',
|
|
27
|
+
path: '/',
|
|
28
|
+
sessionCookies: false,
|
|
29
|
+
};
|
|
30
|
+
export function cookieAuthentication(config) {
|
|
31
|
+
// On unless the config opts out, as GSF ships it; off under fidelity: 'legacy'.
|
|
32
|
+
const option = config.auth?.cookieAuthentication ?? !isLegacyFidelity(config);
|
|
33
|
+
if (!option)
|
|
34
|
+
return undefined;
|
|
35
|
+
return option === true ? SHIPPED_COOKIE_OPTIONS : { ...SHIPPED_COOKIE_OPTIONS, ...option };
|
|
36
|
+
}
|
|
11
37
|
// foundation-auth's login UI (client-app-login) doesn't use the WebSocket
|
|
12
38
|
// EVENT_LOGIN_AUTH flow at all — it POSTs credentials over plain HTTP to
|
|
13
|
-
// gwf/event-login-auth, and separately
|
|
14
|
-
// app load (
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
// of SOURCE_REF correlation. This is a *separate* transport
|
|
19
|
-
// protocol in server.ts — a client-app can use either, or (as
|
|
20
|
-
|
|
39
|
+
// gwf/event-login-auth, and separately POSTs gwf/event-login-details on every
|
|
40
|
+
// app load (silent login; foundation-comms/src/connect/sessionRefresh.ts's
|
|
41
|
+
// isAuthenticated() GETs it later). Both expect the same ACK body as the WS
|
|
42
|
+
// login (EVENT_LOGIN_DETAILS_ACK literally extends EVENT_LOGIN_AUTH_ACK), with
|
|
43
|
+
// the session named by a cookie (cookieAuthentication) or a SESSION_AUTH_TOKEN
|
|
44
|
+
// header instead of SOURCE_REF correlation. This is a *separate* transport
|
|
45
|
+
// from the WS protocol in server.ts — a client-app can use either, or (as
|
|
46
|
+
// here) both.
|
|
47
|
+
export function parseCookies(header) {
|
|
21
48
|
const cookies = {};
|
|
22
49
|
for (const part of (header ?? '').split(';')) {
|
|
23
50
|
const [key, ...rest] = part.trim().split('=');
|
|
@@ -26,10 +53,64 @@ function parseCookies(header) {
|
|
|
26
53
|
}
|
|
27
54
|
return cookies;
|
|
28
55
|
}
|
|
29
|
-
|
|
30
|
-
|
|
56
|
+
// As Netty's ServerCookieEncoder.STRICT writes it (CookieHandler.kt:178-192
|
|
57
|
+
// @v8.15.29): Max-Age and Expires unless it is a session cookie, then Path,
|
|
58
|
+
// Domain, Secure, HTTPOnly, SameSite.
|
|
59
|
+
function encodeCookie(options, name, value, maxAgeSecs) {
|
|
60
|
+
const parts = [`${name}=${value}`];
|
|
61
|
+
if (maxAgeSecs !== undefined) {
|
|
62
|
+
const expires = new Date(Date.now() + maxAgeSecs * MILLIS_PER_SECOND);
|
|
63
|
+
parts.push(`Max-Age=${maxAgeSecs}`, `Expires=${expires.toUTCString()}`);
|
|
64
|
+
}
|
|
65
|
+
if (options.path)
|
|
66
|
+
parts.push(`Path=${options.path}`);
|
|
67
|
+
if (options.domain)
|
|
68
|
+
parts.push(`Domain=${options.domain}`);
|
|
69
|
+
if (options.secure)
|
|
70
|
+
parts.push('Secure');
|
|
71
|
+
if (options.httpOnly)
|
|
72
|
+
parts.push('HTTPOnly');
|
|
73
|
+
if (options.sameSite)
|
|
74
|
+
parts.push(`SameSite=${options.sameSite}`);
|
|
75
|
+
return parts.join('; ');
|
|
76
|
+
}
|
|
77
|
+
// The cookies GSF's router sets on an EVENT_LOGIN_AUTH_ACK
|
|
78
|
+
// (CookieHandler.kt:91-130): the session token lives as long as the session,
|
|
79
|
+
// the refresh token and session id as long as the refresh token, and the
|
|
80
|
+
// unused MFA code expires at once.
|
|
81
|
+
function loginCookies(options, config, session) {
|
|
82
|
+
const sessionMaxAge = options.sessionCookies
|
|
83
|
+
? undefined
|
|
84
|
+
: sessionTimeoutMins(config) * SECONDS_PER_MINUTE;
|
|
85
|
+
const refreshMaxAge = options.sessionCookies
|
|
86
|
+
? undefined
|
|
87
|
+
: refreshTokenExpirationMins(config) * SECONDS_PER_MINUTE;
|
|
88
|
+
return [
|
|
89
|
+
encodeCookie(options, SESSION_AUTH_TOKEN_COOKIE, session.sessionAuthToken, sessionMaxAge),
|
|
90
|
+
encodeCookie(options, REFRESH_AUTH_TOKEN_COOKIE, session.refreshAuthToken, refreshMaxAge),
|
|
91
|
+
encodeCookie(options, SESSION_ID_COOKIE, session.sessionId, refreshMaxAge),
|
|
92
|
+
encodeCookie(options, MFA_CODE_COOKIE, '', 0),
|
|
93
|
+
];
|
|
31
94
|
}
|
|
32
|
-
|
|
95
|
+
// On EVENT_LOGIN_AUTH_NACK the router sets the NACK's REFRESH_AUTH_TOKEN
|
|
96
|
+
// (null) for its REFRESH_TOKEN_EXPIRATION_MINS (null): an empty cookie that
|
|
97
|
+
// expires at once (CookieHandler.kt:132-139); recorded in
|
|
98
|
+
// http-login-failed.json.
|
|
99
|
+
function loginNackCookies(options) {
|
|
100
|
+
return [encodeCookie(options, REFRESH_AUTH_TOKEN_COOKIE, '', 0)];
|
|
101
|
+
}
|
|
102
|
+
// LOGOUT_ACK expires all four (CookieHandler.kt:141-147).
|
|
103
|
+
function logoutCookies(options) {
|
|
104
|
+
return [
|
|
105
|
+
SESSION_AUTH_TOKEN_COOKIE,
|
|
106
|
+
REFRESH_AUTH_TOKEN_COOKIE,
|
|
107
|
+
SESSION_ID_COOKIE,
|
|
108
|
+
MFA_CODE_COOKIE,
|
|
109
|
+
].map((name) => encodeCookie(options, name, '', 0));
|
|
110
|
+
}
|
|
111
|
+
function sendJson(res, status, body, cookies = []) {
|
|
112
|
+
if (cookies.length > 0)
|
|
113
|
+
res.setHeader('Set-Cookie', cookies);
|
|
33
114
|
res.writeHead(status, { 'Content-Type': 'application/json' });
|
|
34
115
|
res.end(JSON.stringify(body));
|
|
35
116
|
}
|
|
@@ -49,28 +130,175 @@ async function readJsonBody(req) {
|
|
|
49
130
|
const raw = Buffer.concat(chunks).toString('utf8');
|
|
50
131
|
return raw ? JSON.parse(raw) : {};
|
|
51
132
|
}
|
|
52
|
-
//
|
|
53
|
-
//
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
133
|
+
// A header the client may send as SESSION_AUTH_TOKEN or, as foundation-comms'
|
|
134
|
+
// createHTTPHeadersFromMessage does, SESSION-AUTH-TOKEN.
|
|
135
|
+
function headerValue(req, name) {
|
|
136
|
+
const value = req.headers[name.toLowerCase()] ?? req.headers[name.toLowerCase().replaceAll('_', '-')];
|
|
137
|
+
return typeof value === 'string' ? value : undefined;
|
|
138
|
+
}
|
|
139
|
+
function autoLoginUser(config) {
|
|
140
|
+
const autoLogin = config.auth?.httpAutoLogin;
|
|
141
|
+
if (!autoLogin)
|
|
142
|
+
return undefined;
|
|
143
|
+
return findUser(config, autoLogin === true ? config.auth?.users?.[0]?.username : autoLogin);
|
|
144
|
+
}
|
|
145
|
+
// Drops every token this server minted for `username` (fidelity: 'legacy',
|
|
146
|
+
// whose logout ends all of the user's sessions).
|
|
147
|
+
function revokeSessionsOf(auth, username) {
|
|
148
|
+
for (const session of auth.sessions.values()) {
|
|
149
|
+
if (session.username === username)
|
|
150
|
+
closeSession(auth, session);
|
|
151
|
+
}
|
|
152
|
+
for (const [token, owner] of auth.tokens) {
|
|
58
153
|
if (owner === username)
|
|
59
|
-
tokens.delete(token);
|
|
154
|
+
auth.tokens.delete(token);
|
|
60
155
|
}
|
|
61
156
|
}
|
|
62
|
-
//
|
|
63
|
-
// otherwise every page load would mint (and leak) a fresh
|
|
64
|
-
// long-lived dev/CI server.
|
|
65
|
-
function
|
|
66
|
-
if (cookieSessionId &&
|
|
157
|
+
// fidelity: 'legacy': reuse the request's MOCK_SESSION_ID when it already maps
|
|
158
|
+
// to this user — otherwise every page load would mint (and leak) a fresh
|
|
159
|
+
// session entry on a long-lived dev/CI server.
|
|
160
|
+
function ensureLegacySession(legacySessions, cookieSessionId, username) {
|
|
161
|
+
if (cookieSessionId && legacySessions.get(cookieSessionId) === username)
|
|
67
162
|
return cookieSessionId;
|
|
68
163
|
const sessionId = crypto.randomUUID();
|
|
69
|
-
|
|
70
|
-
capRegistry(
|
|
164
|
+
legacySessions.set(sessionId, username);
|
|
165
|
+
capRegistry(legacySessions);
|
|
71
166
|
return sessionId;
|
|
72
167
|
}
|
|
73
|
-
|
|
168
|
+
function legacySessionCookie(sessionId) {
|
|
169
|
+
return `${LEGACY_SESSION_COOKIE}=${sessionId}; Path=/; SameSite=Lax`;
|
|
170
|
+
}
|
|
171
|
+
export function createHttpRequestListener(config, legacySessions, auth = createAuthState()) {
|
|
172
|
+
// Every HTTP reply carries a SOURCE_REF: the request's, or AUTO_<uuid> as
|
|
173
|
+
// the router mints one (http-login.json). Not under fidelity: 'legacy'.
|
|
174
|
+
const withSourceRef = (body, request = {}) => isLegacyFidelity(config)
|
|
175
|
+
? body
|
|
176
|
+
: { ...body, SOURCE_REF: request.SOURCE_REF ?? `AUTO_${crypto.randomUUID()}` };
|
|
177
|
+
// The session a request names: the sessionAuthToken cookie under
|
|
178
|
+
// cookieAuthentication, else (GSF) the SESSION_AUTH_TOKEN header. '' when
|
|
179
|
+
// the cookie is there but empty, as after a logout cleared it.
|
|
180
|
+
function requestToken(req, cookies) {
|
|
181
|
+
if (cookieAuthentication(config))
|
|
182
|
+
return cookies[SESSION_AUTH_TOKEN_COOKIE];
|
|
183
|
+
return headerValue(req, 'SESSION_AUTH_TOKEN');
|
|
184
|
+
}
|
|
185
|
+
// The legacy-mode session cookie, or none.
|
|
186
|
+
function legacyCookies(cookies, username) {
|
|
187
|
+
if (!isLegacyFidelity(config) || cookieAuthentication(config))
|
|
188
|
+
return [];
|
|
189
|
+
return [
|
|
190
|
+
legacySessionCookie(ensureLegacySession(legacySessions, cookies[LEGACY_SESSION_COOKIE], username)),
|
|
191
|
+
];
|
|
192
|
+
}
|
|
193
|
+
// A session opened by a login (or an httpAutoLogin): the login cookies.
|
|
194
|
+
function sessionCookies(cookies, session) {
|
|
195
|
+
const options = cookieAuthentication(config);
|
|
196
|
+
return options
|
|
197
|
+
? loginCookies(options, config, session)
|
|
198
|
+
: legacyCookies(cookies, session.username);
|
|
199
|
+
}
|
|
200
|
+
function handleLoginDetails(req, res, request) {
|
|
201
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
202
|
+
const legacyWithoutCookies = isLegacyFidelity(config) && !cookieAuthentication(config);
|
|
203
|
+
const autoLogin = autoLoginUser(config);
|
|
204
|
+
// fidelity: 'legacy' without cookieAuthentication: as up to 15.47, a new
|
|
205
|
+
// session per call, found by the MOCK_SESSION_ID cookie.
|
|
206
|
+
if (legacyWithoutCookies) {
|
|
207
|
+
const user = autoLogin ?? findUser(config, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
|
|
208
|
+
if (!user) {
|
|
209
|
+
sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
|
|
210
|
+
MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
|
|
211
|
+
ERROR: [
|
|
212
|
+
{ CODE: 'NOT_LOGGED_ON', STATUS_CODE: '401 Unauthorized', TEXT: 'No active session' },
|
|
213
|
+
],
|
|
214
|
+
});
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const session = openSession(auth, user);
|
|
218
|
+
const body = buildLoginAckBody(user, session, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
|
|
219
|
+
sendJson(res, HTTP_STATUS.OK, body, legacyCookies(cookies, user.username));
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const token = requestToken(req, cookies);
|
|
223
|
+
const session = token === undefined ? undefined : auth.sessions.get(token);
|
|
224
|
+
const sessionUser = session && findUser(config, session.username);
|
|
225
|
+
if (session && sessionUser) {
|
|
226
|
+
const body = buildLoginAckBody(sessionUser, session, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
|
|
227
|
+
sendJson(res, HTTP_STATUS.OK, withSourceRef(body, request));
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
// httpAutoLogin: a request without a live session logs the user in.
|
|
231
|
+
if (autoLogin) {
|
|
232
|
+
const opened = openSession(auth, autoLogin);
|
|
233
|
+
const body = buildLoginAckBody(autoLogin, opened, config, auth, 'EVENT_LOGIN_DETAILS_ACK');
|
|
234
|
+
sendJson(res, HTTP_STATUS.OK, withSourceRef(body, request), sessionCookies(cookies, opened));
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
sendJson(res, HTTP_STATUS.UNAUTHORIZED, withSourceRef(notLoggedInNack(token !== undefined), request));
|
|
238
|
+
}
|
|
239
|
+
async function handleLoginAuth(req, res) {
|
|
240
|
+
const body = await readJsonBody(req);
|
|
241
|
+
const details = body.DETAILS ?? {};
|
|
242
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
243
|
+
const cookieOptions = cookieAuthentication(config);
|
|
244
|
+
// No USER_NAME: a token refresh (foundation-comms' sessionRefresh
|
|
245
|
+
// performRefresh). Its refresh token is the refreshAuthToken cookie under
|
|
246
|
+
// cookieAuthentication (CookieHandler.kt:62-67), else DETAILS'; under
|
|
247
|
+
// fidelity: 'legacy' without cookies, the MOCK_SESSION_ID session.
|
|
248
|
+
let user;
|
|
249
|
+
if (details.USER_NAME !== undefined) {
|
|
250
|
+
user = findUserByCredentials(config, details.USER_NAME, details.PASSWORD);
|
|
251
|
+
}
|
|
252
|
+
else if (isLegacyFidelity(config) && !cookieOptions) {
|
|
253
|
+
user = findUser(config, legacySessions.get(cookies[LEGACY_SESSION_COOKIE]));
|
|
254
|
+
}
|
|
255
|
+
else {
|
|
256
|
+
const refreshToken = cookieOptions
|
|
257
|
+
? cookies[REFRESH_AUTH_TOKEN_COOKIE]
|
|
258
|
+
: (details.REFRESH_AUTH_TOKEN ?? headerValue(req, 'REFRESH_AUTH_TOKEN'));
|
|
259
|
+
user = findUser(config, sessionByRefreshToken(auth, refreshToken)?.username);
|
|
260
|
+
}
|
|
261
|
+
if (!user) {
|
|
262
|
+
// GSF answers a failed login with HTTP 200; fidelity: 'legacy' with 401.
|
|
263
|
+
const status = isLegacyFidelity(config) ? HTTP_STATUS.UNAUTHORIZED : HTTP_STATUS.OK;
|
|
264
|
+
const nackCookies = cookieOptions ? loginNackCookies(cookieOptions) : [];
|
|
265
|
+
sendJson(res, status, withSourceRef(buildLoginNackBody(config, 'http'), body), nackCookies);
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
const session = openSession(auth, user);
|
|
269
|
+
const ack = buildLoginAckBody(user, session, config, auth);
|
|
270
|
+
sendJson(res, HTTP_STATUS.OK, withSourceRef(ack, body), sessionCookies(cookies, session));
|
|
271
|
+
}
|
|
272
|
+
async function handleLogout(req, res) {
|
|
273
|
+
const body = await readJsonBody(req).catch(() => ({}));
|
|
274
|
+
const cookies = parseCookies(req.headers.cookie);
|
|
275
|
+
const cookieOptions = cookieAuthentication(config);
|
|
276
|
+
if (isLegacyFidelity(config) && !cookieOptions) {
|
|
277
|
+
const sessionId = cookies[LEGACY_SESSION_COOKIE];
|
|
278
|
+
const username = legacySessions.get(sessionId);
|
|
279
|
+
legacySessions.delete(sessionId);
|
|
280
|
+
if (username !== undefined)
|
|
281
|
+
revokeSessionsOf(auth, username);
|
|
282
|
+
sendJson(res, HTTP_STATUS.OK, buildLogoutAckBody(config));
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
// auth's LOGOUT ends the session SESSION_ID names (the sessionId cookie
|
|
286
|
+
// under cookieAuthentication, CookieHandler.kt:76-81), else the token's.
|
|
287
|
+
const sessionId = cookieOptions
|
|
288
|
+
? cookies[SESSION_ID_COOKIE]
|
|
289
|
+
: (body.SESSION_ID ?? headerValue(req, 'SESSION_ID'));
|
|
290
|
+
const token = cookieOptions ? cookies[SESSION_AUTH_TOKEN_COOKIE] : requestToken(req, cookies);
|
|
291
|
+
for (const session of auth.sessions.values()) {
|
|
292
|
+
if (session.sessionId === sessionId || session.sessionAuthToken === token) {
|
|
293
|
+
closeSession(auth, session);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (isLegacyFidelity(config)) {
|
|
297
|
+
sendJson(res, HTTP_STATUS.OK, buildLogoutAckBody(config), logoutCookies(cookieOptions));
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
sendJson(res, HTTP_STATUS.OK, withSourceRef(buildLogoutAckBody(config), body), cookieOptions ? logoutCookies(cookieOptions) : []);
|
|
301
|
+
}
|
|
74
302
|
return async function requestListener(req, res) {
|
|
75
303
|
const pathname = (req.url ?? '').split('?')[0];
|
|
76
304
|
try {
|
|
@@ -96,77 +324,24 @@ export function createHttpRequestListener(config, sessions, tokens = new Map())
|
|
|
96
324
|
sendJson(res, HTTP_STATUS.OK, { IDPS: idps });
|
|
97
325
|
return;
|
|
98
326
|
}
|
|
99
|
-
//
|
|
100
|
-
//
|
|
101
|
-
//
|
|
102
|
-
//
|
|
103
|
-
//
|
|
104
|
-
//
|
|
105
|
-
// hardcodes method: 'POST') on initial silent-login; foundation-comms'
|
|
106
|
-
// sessionRefresh.ts's isAuthenticated() does a plain GET later, when
|
|
107
|
-
// checking whether an expired session can be silently renewed.
|
|
327
|
+
// Silent login on app load. Two call sites hit this path with
|
|
328
|
+
// different methods: foundation-auth's fetch machine always POSTs
|
|
329
|
+
// (createFetchMachineEvent hardcodes method: 'POST') on initial
|
|
330
|
+
// silent-login; foundation-comms' sessionRefresh.ts's isAuthenticated()
|
|
331
|
+
// does a plain GET later, when checking whether an expired session can
|
|
332
|
+
// be silently renewed.
|
|
108
333
|
if ((req.method === 'GET' || req.method === 'POST') &&
|
|
109
334
|
pathname.endsWith('event-login-details')) {
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
const user = autoLoginUsername
|
|
113
|
-
? findUser(config, autoLoginUsername === true ? config.auth?.users?.[0]?.username : autoLoginUsername)
|
|
114
|
-
: findUser(config, sessions.get(cookies[SESSION_COOKIE]));
|
|
115
|
-
if (!user) {
|
|
116
|
-
sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
|
|
117
|
-
MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
|
|
118
|
-
ERROR: [
|
|
119
|
-
{ CODE: 'NOT_LOGGED_ON', STATUS_CODE: '401 Unauthorized', TEXT: 'No active session' },
|
|
120
|
-
],
|
|
121
|
-
});
|
|
122
|
-
return;
|
|
123
|
-
}
|
|
124
|
-
const sessionId = ensureSession(sessions, cookies[SESSION_COOKIE], user.username);
|
|
125
|
-
setSessionCookie(res, sessionId);
|
|
126
|
-
const ack = buildLoginAckBody(user, config, 'EVENT_LOGIN_DETAILS_ACK');
|
|
127
|
-
registerAckTokens(ack, user.username, tokens);
|
|
128
|
-
sendJson(res, HTTP_STATUS.OK, ack);
|
|
335
|
+
const request = req.method === 'POST' ? await readJsonBody(req) : {};
|
|
336
|
+
handleLoginDetails(req, res, request);
|
|
129
337
|
return;
|
|
130
338
|
}
|
|
131
339
|
if (req.method === 'POST' && pathname.endsWith('event-login-auth')) {
|
|
132
|
-
|
|
133
|
-
const details = body.DETAILS ?? {};
|
|
134
|
-
const cookies = parseCookies(req.headers.cookie);
|
|
135
|
-
// Empty DETAILS means a session-refresh ping (foundation-comms'
|
|
136
|
-
// sessionRefresh.performRefresh), not a fresh credentials login —
|
|
137
|
-
// honor it only if the request already carries a known session.
|
|
138
|
-
const user = details.USER_NAME !== undefined
|
|
139
|
-
? findUserByCredentials(config, details.USER_NAME, details.PASSWORD)
|
|
140
|
-
: findUser(config, sessions.get(cookies[SESSION_COOKIE]));
|
|
141
|
-
if (!user) {
|
|
142
|
-
sendJson(res, HTTP_STATUS.UNAUTHORIZED, {
|
|
143
|
-
MESSAGE_TYPE: MESSAGE_TYPE.EVENT_LOGIN_AUTH_NACK,
|
|
144
|
-
ERROR: [
|
|
145
|
-
{
|
|
146
|
-
CODE: 'INCORRECT_CREDENTIALS',
|
|
147
|
-
STATUS_CODE: '401 Unauthorized',
|
|
148
|
-
TEXT: 'Problem logging in',
|
|
149
|
-
},
|
|
150
|
-
],
|
|
151
|
-
WARNING: [],
|
|
152
|
-
});
|
|
153
|
-
return;
|
|
154
|
-
}
|
|
155
|
-
const sessionId = ensureSession(sessions, cookies[SESSION_COOKIE], user.username);
|
|
156
|
-
setSessionCookie(res, sessionId);
|
|
157
|
-
const ack = buildLoginAckBody(user, config);
|
|
158
|
-
registerAckTokens(ack, user.username, tokens);
|
|
159
|
-
sendJson(res, HTTP_STATUS.OK, ack);
|
|
340
|
+
await handleLoginAuth(req, res);
|
|
160
341
|
return;
|
|
161
342
|
}
|
|
162
343
|
if (req.method === 'POST' && pathname.endsWith('event-logout')) {
|
|
163
|
-
|
|
164
|
-
const sessionId = cookies[SESSION_COOKIE];
|
|
165
|
-
const username = sessions.get(sessionId);
|
|
166
|
-
sessions.delete(sessionId);
|
|
167
|
-
if (username !== undefined)
|
|
168
|
-
revokeTokensFor(tokens, username);
|
|
169
|
-
sendJson(res, HTTP_STATUS.OK, { MESSAGE_TYPE: 'LOGOUT_ACK' });
|
|
344
|
+
await handleLogout(req, res);
|
|
170
345
|
return;
|
|
171
346
|
}
|
|
172
347
|
res.writeHead(HTTP_STATUS.NOT_FOUND).end();
|
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import type { Connection } from '../protocol/connection.ts';
|
|
2
|
-
import type { GenesisMessage, MockServerConfig } from '../types.ts';
|
|
2
|
+
import type { GenesisMessage, MockServerConfig, ResourceItem } from '../types.ts';
|
|
3
|
+
export declare function listResources(config: MockServerConfig): ResourceItem[];
|
|
3
4
|
export declare function handleResourcesRequest(message: GenesisMessage, connection: Connection, config: MockServerConfig): void;
|
|
@@ -6,7 +6,8 @@ import { MESSAGE_TYPE } from "../protocol/messageTypes.js";
|
|
|
6
6
|
// "not exist" client-side, before META_REQUEST or DATA_LOGON is ever tried.
|
|
7
7
|
// Auto-derive it from config.queries/requestReplies/eventHandlers (same
|
|
8
8
|
// philosophy as db/metadata.ts's field inference) so projects don't have to
|
|
9
|
-
// hand-maintain a redundant list; set config.resources explicitly to override
|
|
9
|
+
// hand-maintain a redundant list; set config.resources explicitly to override,
|
|
10
|
+
// or config.additionalResources to add to it.
|
|
10
11
|
function deriveResources(config) {
|
|
11
12
|
const resources = [];
|
|
12
13
|
for (const name of Object.keys(config.queries ?? {})) {
|
|
@@ -29,9 +30,24 @@ function deriveResources(config) {
|
|
|
29
30
|
}
|
|
30
31
|
return resources;
|
|
31
32
|
}
|
|
33
|
+
const resourceKey = (resource) => `${resource.RESOURCE_TYPE}:${resource.RESOURCE_NAME}`;
|
|
34
|
+
// The derived resources, then config.additionalResources not among them.
|
|
35
|
+
export function listResources(config) {
|
|
36
|
+
if (config.resources)
|
|
37
|
+
return config.resources;
|
|
38
|
+
const resources = deriveResources(config);
|
|
39
|
+
const listed = new Set(resources.map(resourceKey));
|
|
40
|
+
for (const resource of config.additionalResources ?? []) {
|
|
41
|
+
if (listed.has(resourceKey(resource)))
|
|
42
|
+
continue;
|
|
43
|
+
listed.add(resourceKey(resource));
|
|
44
|
+
resources.push(resource);
|
|
45
|
+
}
|
|
46
|
+
return resources;
|
|
47
|
+
}
|
|
32
48
|
export function handleResourcesRequest(message, connection, config) {
|
|
33
49
|
connection.reply(message, {
|
|
34
50
|
MESSAGE_TYPE: MESSAGE_TYPE.RESOURCES_REQUEST_ACK,
|
|
35
|
-
RESOURCES:
|
|
51
|
+
RESOURCES: listResources(config),
|
|
36
52
|
});
|
|
37
53
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -4,4 +4,4 @@ export { Store } from './db/store.ts';
|
|
|
4
4
|
export { RECORD_FIELDS, RECORD_ID, TIMESTAMP } from './db/identity.ts';
|
|
5
5
|
export { ErrorCode, NackError, statusCodeFor, type ErrorCodeName, type GenesisErrorType, type NackErrorEntry, type NackErrorInput, type NackErrorOptions, } from './protocol/errors.ts';
|
|
6
6
|
export { compileCriteria, type CriteriaOptions, filterByCriteria, type Predicate, } from './db/criteria.ts';
|
|
7
|
-
export type { AntiJoinDef, AuthConfig, AuthUser, BroadcastFn, BroadcastTableChangeFn, CrudEventVerb, EventHandler, EventHandlerCtx, EventHandlerResult, EventSchemaOverride, FidelityMode, FieldDef, FieldMetadata, GeneratedFieldDef, GenesisFieldType, GenesisMessage, HttpRouteDef, IndexDef, JoinDef, JoinFieldLink, JoinLink, JoinType, JoinValueLink, LiveModifyMode, MockServerConfig, OnMessageCtx, OnMessageHook, QueryDef, RequestingUser, RequestReplyDef, RequestReplyResolverCtx, ResourceAuthDef, ResourceItem, Row, SequenceFormat, SocketLike, SsoIdentityProvider, TableDef, ViewDef, ViewRowSources, } from './types.ts';
|
|
7
|
+
export type { AntiJoinDef, AuthConfig, AuthUser, BroadcastFn, BroadcastTableChangeFn, CookieAuthenticationOptions, CrudEventVerb, EventHandler, EventHandlerCtx, EventHandlerResult, EventSchemaOverride, FidelityMode, FieldDef, FieldMetadata, GeneratedFieldDef, GenesisFieldType, GenesisMessage, HttpRouteDef, IndexDef, JoinDef, JoinFieldLink, JoinLink, JoinType, JoinValueLink, LiveModifyMode, MockServerConfig, OnMessageCtx, OnMessageHook, ProductDetails, QueryDef, RequestingUser, RequestReplyDef, RequestReplyResolverCtx, ResourceAuthDef, ResourceItem, Row, SequenceFormat, SocketLike, SsoIdentityProvider, TableDef, ViewDef, ViewRowSources, } from './types.ts';
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// The rows of a GSF seed CSV (an app's or a PBC's data/*.csv): a header line,
|
|
2
|
+
// then one record per line; a value is bare or double-quoted ("" is a quote
|
|
3
|
+
// inside one). Values stay strings — a table's declared fields convert them
|
|
4
|
+
// when the rows are stored, as GSF's loader does. An empty cell is left out of
|
|
5
|
+
// its row (null), since SendTable sets only the non-empty cells
|
|
6
|
+
// (SendTableOperation.createRecord, genesis-db, GSF v8.15.29).
|
|
7
|
+
export function parseSeedCsv(text) {
|
|
8
|
+
const records = [];
|
|
9
|
+
let record = [];
|
|
10
|
+
let field = '';
|
|
11
|
+
let quoted = false;
|
|
12
|
+
const endRecord = () => {
|
|
13
|
+
record.push(field);
|
|
14
|
+
if (record.some((value) => value !== ''))
|
|
15
|
+
records.push(record);
|
|
16
|
+
record = [];
|
|
17
|
+
field = '';
|
|
18
|
+
};
|
|
19
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
20
|
+
const char = text[i];
|
|
21
|
+
if (quoted) {
|
|
22
|
+
if (char === '"' && text[i + 1] === '"') {
|
|
23
|
+
field += '"';
|
|
24
|
+
i += 1;
|
|
25
|
+
}
|
|
26
|
+
else if (char === '"') {
|
|
27
|
+
quoted = false;
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
field += char;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
else if (char === '"') {
|
|
34
|
+
quoted = true;
|
|
35
|
+
}
|
|
36
|
+
else if (char === ',') {
|
|
37
|
+
record.push(field);
|
|
38
|
+
field = '';
|
|
39
|
+
}
|
|
40
|
+
else if (char === '\n' || char === '\r') {
|
|
41
|
+
if (char === '\r' && text[i + 1] === '\n')
|
|
42
|
+
i += 1;
|
|
43
|
+
endRecord();
|
|
44
|
+
}
|
|
45
|
+
else {
|
|
46
|
+
field += char;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
endRecord();
|
|
50
|
+
const [header = [], ...rows] = records;
|
|
51
|
+
return rows.map((values) => Object.fromEntries(header.flatMap((name, i) => (values[i] ? [[name.trim(), values[i]]] : []))));
|
|
52
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { MockServerConfig } from '../types.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Merges mock-server configs into one, later configs over earlier ones:
|
|
4
|
+
* `createMockServer(mergeConfigs(platformPreset(), appConfig))`.
|
|
5
|
+
*
|
|
6
|
+
* - tables, views, queries, requestReplies, eventHandlers, eventSchemas: by
|
|
7
|
+
* name, a later entry replacing an earlier one whole.
|
|
8
|
+
* - auth.users: by username, a later user replacing an earlier one; the other
|
|
9
|
+
* auth settings, setting by setting.
|
|
10
|
+
* - additionalResources: both lists, without repeats.
|
|
11
|
+
* - httpRoutes: both, the later config's tried first. onMessage: both, in order.
|
|
12
|
+
* - Anything else (resources, fidelity, defaultEventHandler, productName, ...):
|
|
13
|
+
* the later config's, when it sets one.
|
|
14
|
+
*/
|
|
15
|
+
export declare function mergeConfigs(...configs: MockServerConfig[]): MockServerConfig;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
const NAMED = [
|
|
2
|
+
'tables',
|
|
3
|
+
'views',
|
|
4
|
+
'queries',
|
|
5
|
+
'requestReplies',
|
|
6
|
+
'eventHandlers',
|
|
7
|
+
'eventSchemas',
|
|
8
|
+
];
|
|
9
|
+
function mergeUsers(a = [], b = []) {
|
|
10
|
+
const users = new Map(a.map((user) => [user.username, user]));
|
|
11
|
+
for (const user of b)
|
|
12
|
+
users.set(user.username, user);
|
|
13
|
+
return [...users.values()];
|
|
14
|
+
}
|
|
15
|
+
function mergeResources(a = [], b = []) {
|
|
16
|
+
const resources = new Map();
|
|
17
|
+
for (const resource of [...a, ...b]) {
|
|
18
|
+
resources.set(`${resource.RESOURCE_TYPE}:${resource.RESOURCE_NAME}`, resource);
|
|
19
|
+
}
|
|
20
|
+
return [...resources.values()];
|
|
21
|
+
}
|
|
22
|
+
// Both hooks, in order: the second sees what the first returned, and a
|
|
23
|
+
// message the first handled (false) goes no further.
|
|
24
|
+
function chainHooks(first, second) {
|
|
25
|
+
return (message, ctx) => {
|
|
26
|
+
const hooked = first(message, ctx);
|
|
27
|
+
if (hooked === false)
|
|
28
|
+
return false;
|
|
29
|
+
return second(hooked ?? message, ctx) ?? hooked;
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
function mergeTwo(base, over) {
|
|
33
|
+
const merged = { ...base };
|
|
34
|
+
for (const [key, value] of Object.entries(over)) {
|
|
35
|
+
if (value !== undefined)
|
|
36
|
+
merged[key] = value;
|
|
37
|
+
}
|
|
38
|
+
for (const key of NAMED) {
|
|
39
|
+
if (base[key] && over[key])
|
|
40
|
+
merged[key] = { ...base[key], ...over[key] };
|
|
41
|
+
}
|
|
42
|
+
if (base.auth && over.auth) {
|
|
43
|
+
merged.auth = {
|
|
44
|
+
...base.auth,
|
|
45
|
+
...over.auth,
|
|
46
|
+
users: mergeUsers(base.auth.users, over.auth.users),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
if (base.additionalResources && over.additionalResources) {
|
|
50
|
+
merged.additionalResources = mergeResources(base.additionalResources, over.additionalResources);
|
|
51
|
+
}
|
|
52
|
+
// The later config's routes are tried first.
|
|
53
|
+
if (base.httpRoutes && over.httpRoutes) {
|
|
54
|
+
merged.httpRoutes = [...over.httpRoutes, ...base.httpRoutes];
|
|
55
|
+
}
|
|
56
|
+
if (base.onMessage && over.onMessage) {
|
|
57
|
+
merged.onMessage = chainHooks(base.onMessage, over.onMessage);
|
|
58
|
+
}
|
|
59
|
+
return merged;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Merges mock-server configs into one, later configs over earlier ones:
|
|
63
|
+
* `createMockServer(mergeConfigs(platformPreset(), appConfig))`.
|
|
64
|
+
*
|
|
65
|
+
* - tables, views, queries, requestReplies, eventHandlers, eventSchemas: by
|
|
66
|
+
* name, a later entry replacing an earlier one whole.
|
|
67
|
+
* - auth.users: by username, a later user replacing an earlier one; the other
|
|
68
|
+
* auth settings, setting by setting.
|
|
69
|
+
* - additionalResources: both lists, without repeats.
|
|
70
|
+
* - httpRoutes: both, the later config's tried first. onMessage: both, in order.
|
|
71
|
+
* - Anything else (resources, fidelity, defaultEventHandler, productName, ...):
|
|
72
|
+
* the later config's, when it sets one.
|
|
73
|
+
*/
|
|
74
|
+
export function mergeConfigs(...configs) {
|
|
75
|
+
return configs.reduce((merged, config) => mergeTwo(merged, config), {});
|
|
76
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"USER": {
|
|
3
|
+
"USER_NAME": "admin",
|
|
4
|
+
"LAST_LOGIN": "2016-04-28",
|
|
5
|
+
"LAST_NAME": "global",
|
|
6
|
+
"FIRST_NAME": "admin",
|
|
7
|
+
"ONLINE": "false",
|
|
8
|
+
"COMPANY_NAME": "GENESIS",
|
|
9
|
+
"STATUS": "ENABLED",
|
|
10
|
+
"EMAIL_ADDRESS": "admin.global@genesis.global"
|
|
11
|
+
},
|
|
12
|
+
"USER_ATTRIBUTES": {
|
|
13
|
+
"USER_NAME": "admin",
|
|
14
|
+
"USER_TYPE": "USER",
|
|
15
|
+
"ACCESS_TYPE": "ALL"
|
|
16
|
+
},
|
|
17
|
+
"PROFILE": [
|
|
18
|
+
"FILE_STORAGE_ADMIN",
|
|
19
|
+
"FILE_STORAGE_USER",
|
|
20
|
+
"NOTIFICATION_ADMIN",
|
|
21
|
+
"NOTIFICATION_ROUTE_ADMIN",
|
|
22
|
+
"NOTIFICATION_RULE_ADMIN",
|
|
23
|
+
"NOTIFICATION_RULE_TEMPLATE_ADMIN",
|
|
24
|
+
"NOTIFICATION_RULE_USER",
|
|
25
|
+
"NOTIFICATION_USER",
|
|
26
|
+
"RECONCILIATION_USER",
|
|
27
|
+
"REPORTING_USER",
|
|
28
|
+
"USER_ADMIN"
|
|
29
|
+
]
|
|
30
|
+
}
|