@genesislcap/mock-server 15.74.0 → 15.76.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 +296 -58
- package/dist/db/schema.d.ts +9 -1
- package/dist/db/schema.js +40 -11
- package/dist/db/store.d.ts +1 -0
- package/dist/db/store.js +4 -0
- package/dist/handlers/auth.d.ts +15 -6
- package/dist/handlers/auth.js +152 -33
- package/dist/handlers/commitEvent.js +43 -20
- package/dist/handlers/crudEvents.d.ts +3 -1
- package/dist/handlers/crudEvents.js +3 -2
- package/dist/handlers/eventValidation.js +6 -3
- package/dist/handlers/http.d.ts +2 -2
- package/dist/handlers/http.js +66 -43
- package/dist/handlers/jsonSchema.d.ts +1 -0
- package/dist/handlers/jsonSchema.js +72 -21
- package/dist/handlers/meta.d.ts +1 -1
- package/dist/handlers/meta.js +59 -10
- package/dist/handlers/requestReply.js +36 -9
- package/dist/index.d.ts +1 -1
- package/dist/presets/auth.d.ts +25 -0
- package/dist/presets/auth.js +855 -0
- package/dist/presets/cronExpression.d.ts +1 -0
- package/dist/presets/cronExpression.js +429 -0
- package/dist/presets/fileServer.d.ts +13 -0
- package/dist/presets/fileServer.js +399 -0
- package/dist/presets/gsf.d.ts +24 -0
- package/dist/presets/gsf.js +450 -0
- package/dist/presets/index.d.ts +1 -0
- package/dist/presets/index.js +1 -0
- package/dist/presets/javaTime.d.ts +7 -0
- package/dist/presets/javaTime.js +322 -0
- package/dist/presets/multipart.d.ts +14 -0
- package/dist/presets/multipart.js +91 -0
- package/dist/presets/notify.d.ts +27 -0
- package/dist/presets/notify.js +250 -0
- package/dist/presets/notifyDispatch.d.ts +28 -0
- package/dist/presets/notifyDispatch.js +570 -0
- package/dist/presets/notifyRules.d.ts +9 -0
- package/dist/presets/notifyRules.js +754 -0
- package/dist/presets/platform/backing.json +8058 -217
- package/dist/presets/platform/criteria-model.json +362 -0
- package/dist/presets/platform/time-zones.json +608 -0
- package/dist/presets/platform.d.ts +7 -0
- package/dist/presets/platform.js +145 -103
- package/dist/presets/products.d.ts +9 -7
- package/dist/presets/products.js +89 -21
- package/dist/presets/reconciliation.d.ts +18 -0
- package/dist/presets/reconciliation.js +721 -0
- package/dist/presets/reporting.d.ts +14 -0
- package/dist/presets/reporting.js +862 -0
- package/dist/protocol/connection.d.ts +2 -0
- package/dist/protocol/connection.js +4 -0
- package/dist/protocol/dtoTypes.d.ts +30 -0
- package/dist/protocol/dtoTypes.js +250 -0
- package/dist/protocol/errors.d.ts +3 -1
- package/dist/protocol/errors.js +2 -0
- package/dist/protocol/fieldTypes.js +5 -0
- package/dist/protocol/router.d.ts +1 -0
- package/dist/protocol/router.js +3 -3
- package/dist/protocol/schemaValidation.d.ts +1 -1
- package/dist/protocol/schemaValidation.js +53 -8
- package/dist/server.js +34 -2
- package/dist/types.d.ts +50 -2
- package/package.json +1 -1
- package/src/db/schema.ts +56 -13
- package/src/db/store.ts +5 -0
- package/src/handlers/auth.ts +211 -37
- package/src/handlers/commitEvent.ts +44 -19
- package/src/handlers/crudEvents.ts +9 -2
- package/src/handlers/eventValidation.ts +6 -3
- package/src/handlers/http.ts +83 -42
- package/src/handlers/jsonSchema.ts +86 -23
- package/src/handlers/meta.ts +77 -9
- package/src/handlers/requestReply.ts +42 -6
- package/src/index.ts +7 -0
- package/src/presets/auth.ts +961 -0
- package/src/presets/cronExpression.ts +445 -0
- package/src/presets/fileServer.ts +475 -0
- package/src/presets/gsf.ts +475 -0
- package/src/presets/index.ts +5 -0
- package/src/presets/javaTime.ts +354 -0
- package/src/presets/multipart.ts +110 -0
- package/src/presets/notify.ts +312 -0
- package/src/presets/notifyDispatch.ts +685 -0
- package/src/presets/notifyRules.ts +866 -0
- package/src/presets/platform/backing.json +8058 -217
- package/src/presets/platform/criteria-model.json +362 -0
- package/src/presets/platform/time-zones.json +608 -0
- package/src/presets/platform.ts +204 -115
- package/src/presets/products.ts +125 -19
- package/src/presets/reconciliation.ts +824 -0
- package/src/presets/reporting.ts +953 -0
- package/src/protocol/connection.ts +4 -0
- package/src/protocol/dtoTypes.ts +310 -0
- package/src/protocol/errors.ts +13 -1
- package/src/protocol/fieldTypes.ts +5 -0
- package/src/protocol/router.ts +3 -3
- package/src/protocol/schemaValidation.ts +61 -8
- package/src/server.ts +38 -2
- package/src/types.ts +147 -3
|
@@ -0,0 +1,961 @@
|
|
|
1
|
+
// auth's user, profile, password and MFA event handlers, the request servers
|
|
2
|
+
// its scripts compute, and the logins it runs over the same tables, as the
|
|
3
|
+
// product does (auth v8.15.5, scripts/platform-preset/seeds/auth@8.15.5/
|
|
4
|
+
// scripts: auth-user-eventhandler.kts as UEH, auth-profile-eventhandler.kts
|
|
5
|
+
// as PEH, auth-password-eventhandler.kts as PWD, auth-mfa-eventhandler.kts as
|
|
6
|
+
// MFA, auth-reqrep.kts as RR). Each DTO's fields come from the product's
|
|
7
|
+
// messages jar (global.genesis.auth.messages.event.*) and, for a user's own
|
|
8
|
+
// columns, the generated UserInsertView and UserAmendView. The handlers write
|
|
9
|
+
// through the event's audited transaction, so USER_AUDIT,
|
|
10
|
+
// USER_ATTRIBUTES_AUDIT, PROFILE_AUDIT, PROFILE_USER_AUDIT and
|
|
11
|
+
// PROFILE_RIGHT_AUDIT fill as GSF's do, and keep RIGHT_SUMMARY inside the
|
|
12
|
+
// event as auth's UserProfileConsolidationService does. Not modelled, as
|
|
13
|
+
// elsewhere in the preset: permission codes and the USER_VISIBILITY auth map;
|
|
14
|
+
// nor password strength rules (the auth-preferences Create and the showcase
|
|
15
|
+
// ship set none), nor MFA at login.
|
|
16
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
17
|
+
import type { ServerResponse } from 'node:http';
|
|
18
|
+
import { primaryKeyIndexName } from '../db/schema.ts';
|
|
19
|
+
import type { Store } from '../db/store.ts';
|
|
20
|
+
import { checkUnique } from '../handlers/crudEvents.ts';
|
|
21
|
+
import { NackError, type NackErrorInput } from '../protocol/errors.ts';
|
|
22
|
+
import type {
|
|
23
|
+
AuthDirectory,
|
|
24
|
+
AuthUser,
|
|
25
|
+
EventHandler,
|
|
26
|
+
EventHandlerCtx,
|
|
27
|
+
EventSchemaOverride,
|
|
28
|
+
FieldDef,
|
|
29
|
+
HttpRouteDef,
|
|
30
|
+
LoginCtx,
|
|
31
|
+
LoginFailure,
|
|
32
|
+
RequestReplyDef,
|
|
33
|
+
Row,
|
|
34
|
+
ViewDef,
|
|
35
|
+
} from '../types.ts';
|
|
36
|
+
import { BodyTooLarge, readBody } from './multipart.ts';
|
|
37
|
+
import { dto, ENUMS, nullable, stringSet } from './notify.ts';
|
|
38
|
+
|
|
39
|
+
const EVENT_CLASS = 'global.genesis.auth.messages.event';
|
|
40
|
+
|
|
41
|
+
const ENABLED = 'ENABLED';
|
|
42
|
+
const DISABLED = 'DISABLED';
|
|
43
|
+
const PASSWORD_EXPIRED = 'PASSWORD_EXPIRED';
|
|
44
|
+
// The statuses that ask for a new password (UserStatus): a login answers
|
|
45
|
+
// PASSWORD_EXPIRED, and a password change re-enables the user
|
|
46
|
+
// (PasswordService.performPasswordChange).
|
|
47
|
+
const NEEDS_NEW_PASSWORD = new Set([PASSWORD_EXPIRED, 'PASSWORD_RESET']);
|
|
48
|
+
|
|
49
|
+
// A password as auth keeps it (PasswordService.hashPassword, with the empty
|
|
50
|
+
// salt of an auth-preferences without passwordValidation): never as given.
|
|
51
|
+
const passwordHash = (user: string, password: string) =>
|
|
52
|
+
createHash('sha512').update(`${user}${password}`).digest('hex');
|
|
53
|
+
|
|
54
|
+
// The users' passwords, hashed, beside each server's store: USER.PASSWORD on
|
|
55
|
+
// the real server, which the preset leaves out of USER, as a row's every
|
|
56
|
+
// column can reach a client (fidelity: 'legacy' sends rows whole) and GSF
|
|
57
|
+
// masks this one. An event changes them once it commits, so one that NACKs
|
|
58
|
+
// keeps the old.
|
|
59
|
+
interface Credentials {
|
|
60
|
+
has(store: Store, user: string): boolean;
|
|
61
|
+
matches(store: Store, user: string, password: string): boolean;
|
|
62
|
+
set(ctx: EventHandlerCtx, user: string, password: string): void;
|
|
63
|
+
remove(ctx: EventHandlerCtx, user: string): void;
|
|
64
|
+
}
|
|
65
|
+
function credentials(passwords: Map<string, string>): Credentials {
|
|
66
|
+
const byStore = new WeakMap<Store, Map<string, string>>();
|
|
67
|
+
const of = (store: Store) => {
|
|
68
|
+
let hashes = byStore.get(store);
|
|
69
|
+
if (!hashes) {
|
|
70
|
+
hashes = new Map(
|
|
71
|
+
[...passwords].map(([user, password]) => [user, passwordHash(user, password)]),
|
|
72
|
+
);
|
|
73
|
+
byStore.set(store, hashes);
|
|
74
|
+
}
|
|
75
|
+
return hashes;
|
|
76
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
has: (store, user) => of(store).has(user),
|
|
79
|
+
matches: (store, user, password) => of(store).get(user) === passwordHash(user, password),
|
|
80
|
+
set: (ctx, user, password) => {
|
|
81
|
+
const hash = passwordHash(user, password);
|
|
82
|
+
ctx.afterCommit(() => of(ctx.store).set(user, hash));
|
|
83
|
+
},
|
|
84
|
+
remove: (ctx, user) => ctx.afterCommit(() => of(ctx.store).delete(user)),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// A script's StandardError("CODE", text): 500 whatever the code
|
|
89
|
+
// (GenesisError.kt:22-26), which NackError.standard would map by the code.
|
|
90
|
+
const scriptError = (CODE: string, TEXT: string): NackErrorInput => ({
|
|
91
|
+
'@type': 'StandardError',
|
|
92
|
+
CODE,
|
|
93
|
+
TEXT,
|
|
94
|
+
STATUS_CODE: '500 Internal Server Error',
|
|
95
|
+
});
|
|
96
|
+
const notAuthorised = (user: string) =>
|
|
97
|
+
new NackError(scriptError('NOT_AUTHORISED', `User ${user} lacks sufficient permissions`));
|
|
98
|
+
|
|
99
|
+
// --- DTOs ----------------------------------------------------------------------------
|
|
100
|
+
|
|
101
|
+
const userOperation: EventSchemaOverride = {
|
|
102
|
+
className: `${EVENT_CLASS}.UserOperation`,
|
|
103
|
+
fields: [dto('USER_NAME', 'STRING')],
|
|
104
|
+
};
|
|
105
|
+
const profiles = (name: string, more: Partial<FieldDef> = nullable) =>
|
|
106
|
+
dto(name, 'ARRAY', { ...stringSet, ...more });
|
|
107
|
+
|
|
108
|
+
// UserInsertView / UserAmendView (auth-view-dictionary.kts.json
|
|
109
|
+
// USER_INSERT_VIEW, USER_AMEND_VIEW), in the generated view's order: USER's
|
|
110
|
+
// columns, then USER_ATTRIBUTES' (ADDRESS_LINEn as ADDRESS_LINE_n, the wire
|
|
111
|
+
// name a view property's camelCase gives). Every one but USER_NAME nullable
|
|
112
|
+
// and defaulted to null. InsertUser and AmendUser unwrap the view
|
|
113
|
+
// (@JsonUnwrapped), so its fields sit in DETAILS beside USER_PROFILES.
|
|
114
|
+
const viewField = (name: string, type: FieldDef['type'] = 'STRING', more: Partial<FieldDef> = {}) =>
|
|
115
|
+
dto(name, type, { ...nullable, ...more });
|
|
116
|
+
const ADDRESS_LINES = [
|
|
117
|
+
['ADDRESS_LINE_1', 'ADDRESS_LINE1'],
|
|
118
|
+
['ADDRESS_LINE_2', 'ADDRESS_LINE2'],
|
|
119
|
+
['ADDRESS_LINE_3', 'ADDRESS_LINE3'],
|
|
120
|
+
['ADDRESS_LINE_4', 'ADDRESS_LINE4'],
|
|
121
|
+
];
|
|
122
|
+
const USER_VIEW_COLUMNS = [
|
|
123
|
+
'LAST_NAME',
|
|
124
|
+
'FIRST_NAME',
|
|
125
|
+
'COMPANY_NAME',
|
|
126
|
+
'EMAIL_ADDRESS',
|
|
127
|
+
'COMPANY_ID',
|
|
128
|
+
'DOMAIN',
|
|
129
|
+
];
|
|
130
|
+
const ATTRIBUTE_VIEW_COLUMNS = [
|
|
131
|
+
'CITY',
|
|
132
|
+
'REGION',
|
|
133
|
+
'POSTAL_CODE',
|
|
134
|
+
'COUNTRY',
|
|
135
|
+
'TITLE',
|
|
136
|
+
'WEBSITE',
|
|
137
|
+
'MOBILE_NUMBER',
|
|
138
|
+
'TELEPHONE_NUMBER_DIRECT',
|
|
139
|
+
'TELEPHONE_NUMBER_OFFICE',
|
|
140
|
+
];
|
|
141
|
+
const userViewFields = (insert: boolean): FieldDef[] => [
|
|
142
|
+
dto('USER_NAME', 'STRING', { maxSize: 255 }),
|
|
143
|
+
...(insert ? [viewField('ONE_TIME_PASSWORD', 'STRING', { maxSize: 255 })] : []),
|
|
144
|
+
viewField('LAST_LOGIN', 'DATE'),
|
|
145
|
+
...USER_VIEW_COLUMNS.map((name) => viewField(name)),
|
|
146
|
+
viewField('USER_TYPE', 'ENUM', {
|
|
147
|
+
values: ['USER', 'ADVISOR', 'CLIENT', 'SYSTEM', 'API'],
|
|
148
|
+
enumClass: `${ENUMS}.UserType`,
|
|
149
|
+
}),
|
|
150
|
+
viewField('ACCESS_TYPE', 'ENUM', {
|
|
151
|
+
values: ['ALL', 'ENTITY', 'MULTI_ENTITY'],
|
|
152
|
+
enumClass: `${ENUMS}.AccessType`,
|
|
153
|
+
}),
|
|
154
|
+
...ADDRESS_LINES.map(([name]) => viewField(name, 'STRING', { maxSize: 400 })),
|
|
155
|
+
...ATTRIBUTE_VIEW_COLUMNS.map((name) => viewField(name)),
|
|
156
|
+
];
|
|
157
|
+
|
|
158
|
+
const profileFields: FieldDef[] = [
|
|
159
|
+
dto('NAME', 'STRING'),
|
|
160
|
+
dto('DESCRIPTION', 'STRING', { nullable: true }),
|
|
161
|
+
dto('STATUS', 'STRING', { nullable: true }),
|
|
162
|
+
profiles('RIGHT_CODES'),
|
|
163
|
+
profiles('USER_NAMES'),
|
|
164
|
+
];
|
|
165
|
+
|
|
166
|
+
const EVENT_SCHEMAS: Record<string, EventSchemaOverride> = {
|
|
167
|
+
EVENT_INSERT_USER: {
|
|
168
|
+
className: `${EVENT_CLASS}.InsertUser`,
|
|
169
|
+
fields: [profiles('USER_PROFILES'), ...userViewFields(true)],
|
|
170
|
+
},
|
|
171
|
+
EVENT_AMEND_USER: {
|
|
172
|
+
className: `${EVENT_CLASS}.AmendUser`,
|
|
173
|
+
fields: [profiles('USER_PROFILES'), ...userViewFields(false)],
|
|
174
|
+
},
|
|
175
|
+
EVENT_DELETE_USER: userOperation,
|
|
176
|
+
EVENT_ENABLE_USER: userOperation,
|
|
177
|
+
EVENT_DISABLE_USER: userOperation,
|
|
178
|
+
EVENT_USER_PROFILE_AMEND: {
|
|
179
|
+
className: `${EVENT_CLASS}.UserProfileAmend`,
|
|
180
|
+
fields: [dto('USER_NAME', 'STRING'), profiles('USER_PROFILES', { optional: true })],
|
|
181
|
+
},
|
|
182
|
+
EVENT_INSERT_PROFILE: { className: `${EVENT_CLASS}.InsertAmendProfile`, fields: profileFields },
|
|
183
|
+
EVENT_AMEND_PROFILE: { className: `${EVENT_CLASS}.InsertAmendProfile`, fields: profileFields },
|
|
184
|
+
EVENT_DELETE_PROFILE: {
|
|
185
|
+
className: `${EVENT_CLASS}.DeleteProfile`,
|
|
186
|
+
fields: [dto('NAME', 'STRING')],
|
|
187
|
+
},
|
|
188
|
+
EVENT_CHANGE_USER_PASSWORD: {
|
|
189
|
+
className: `${EVENT_CLASS}.ChangePassword`,
|
|
190
|
+
fields: [
|
|
191
|
+
dto('OLD_PASSWORD', 'STRING'),
|
|
192
|
+
dto('NEW_PASSWORD', 'STRING'),
|
|
193
|
+
dto('USER_NAME', 'STRING', nullable),
|
|
194
|
+
],
|
|
195
|
+
},
|
|
196
|
+
EVENT_EXPIRE_USER_PASSWORD: {
|
|
197
|
+
className: `${EVENT_CLASS}.ExpirePassword`,
|
|
198
|
+
fields: [dto('USER_NAME', 'STRING'), dto('PASSWORD', 'STRING', { nullable: true })],
|
|
199
|
+
},
|
|
200
|
+
EVENT_MFA_CREATE_SECRET: { fields: [], className: 'kotlin.Unit' },
|
|
201
|
+
EVENT_MFA_CONFIRM_SECRET: {
|
|
202
|
+
className: `${EVENT_CLASS}.ConfirmMfaSecret`,
|
|
203
|
+
fields: [dto('MFA_CODE', 'STRING')],
|
|
204
|
+
},
|
|
205
|
+
EVENT_ENABLE_MFA_FOR_USER: userOperation,
|
|
206
|
+
EVENT_DISABLE_MFA_FOR_USER: userOperation,
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
// --- writes --------------------------------------------------------------------------
|
|
210
|
+
|
|
211
|
+
// entityDb's writes: unique indexes checked (DUPLICATE_KEY), a missing row
|
|
212
|
+
// RECORD_NOT_FOUND, each change pushed live.
|
|
213
|
+
function insert(ctx: EventHandlerCtx, table: string, row: Row): Row {
|
|
214
|
+
checkUnique(table, ctx.config.tables![table], row, ctx.store);
|
|
215
|
+
const written = ctx.store.insertRow(table, row);
|
|
216
|
+
ctx.broadcastTableChange(table, 'INSERT', ctx.store.rowKey(table, written));
|
|
217
|
+
return written;
|
|
218
|
+
}
|
|
219
|
+
function modify(ctx: EventHandlerCtx, table: string, key: string, patch: Row): Row {
|
|
220
|
+
const def = ctx.config.tables![table];
|
|
221
|
+
const existing = ctx.store.getRow(table, key);
|
|
222
|
+
if (!existing) throw NackError.recordNotFound(table, primaryKeyIndexName(table, def));
|
|
223
|
+
const written = ctx.store.updateRow(table, key, patch)!;
|
|
224
|
+
ctx.broadcastTableChange(table, 'MODIFY', key);
|
|
225
|
+
return written;
|
|
226
|
+
}
|
|
227
|
+
function remove(ctx: EventHandlerCtx, table: string, key: string): void {
|
|
228
|
+
if (!ctx.store.deleteRow(table, key)) throw NackError.recordNotFound(table);
|
|
229
|
+
ctx.broadcastTableChange(table, 'DELETE', key);
|
|
230
|
+
}
|
|
231
|
+
const removeRow = (ctx: EventHandlerCtx, table: string, row: Row) =>
|
|
232
|
+
remove(ctx, table, ctx.store.rowKey(table, row));
|
|
233
|
+
|
|
234
|
+
const rowsWhere = (store: Store, table: string, column: string, value: unknown) =>
|
|
235
|
+
store.getAllRows(table).filter((row) => row[column] === value);
|
|
236
|
+
const sorted = (values: Iterable<string>) => [...values].sort();
|
|
237
|
+
// `a - b`, as Kotlin's Set minus: a's order.
|
|
238
|
+
const minus = (a: Iterable<string>, b: Iterable<string>) => {
|
|
239
|
+
const without = new Set(b);
|
|
240
|
+
return [...new Set(a)].filter((value) => !without.has(value));
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
// A user's profiles (PROFILE_USER.byUserNameProfileName) and rights
|
|
244
|
+
// (RIGHT_SUMMARY), in index order.
|
|
245
|
+
const profilesOf = (store: Store, user: string) =>
|
|
246
|
+
sorted(rowsWhere(store, 'PROFILE_USER', 'USER_NAME', user).map((row) => row.PROFILE_NAME));
|
|
247
|
+
const rightsOf = (store: Store, user: string) =>
|
|
248
|
+
sorted(rowsWhere(store, 'RIGHT_SUMMARY', 'USER_NAME', user).map((row) => row.RIGHT_CODE));
|
|
249
|
+
const usersOf = (store: Store, profile: string) =>
|
|
250
|
+
sorted(rowsWhere(store, 'PROFILE_USER', 'PROFILE_NAME', profile).map((row) => row.USER_NAME));
|
|
251
|
+
const profileRightsOf = (store: Store, profile: string) =>
|
|
252
|
+
sorted(rowsWhere(store, 'PROFILE_RIGHT', 'PROFILE_NAME', profile).map((row) => row.RIGHT_CODE));
|
|
253
|
+
|
|
254
|
+
export const hasRight = (store: Store, user: string, code: string) =>
|
|
255
|
+
rightsOf(store, user).includes(code);
|
|
256
|
+
|
|
257
|
+
// The rights the preset gives a user whatever their profiles
|
|
258
|
+
// (PlatformUser.permission), by user name.
|
|
259
|
+
type FixedRights = ReadonlyMap<string, readonly string[]>;
|
|
260
|
+
|
|
261
|
+
// UserProfileConsolidationService.consolidateRightsForUser: the user's
|
|
262
|
+
// RIGHT_SUMMARY becomes their profiles' PROFILE_RIGHT codes (none without a
|
|
263
|
+
// profile). Neither PROFILE.STATUS nor RIGHT is consulted. A user with fixed
|
|
264
|
+
// rights keeps them for as long as they exist.
|
|
265
|
+
function consolidate(
|
|
266
|
+
ctx: EventHandlerCtx,
|
|
267
|
+
user: string,
|
|
268
|
+
profileNames: Iterable<string>,
|
|
269
|
+
fixed: FixedRights,
|
|
270
|
+
): void {
|
|
271
|
+
const current = rightsOf(ctx.store, user);
|
|
272
|
+
const own = ctx.store.getRow('USER', user) ? fixed.get(user) : undefined;
|
|
273
|
+
const wanted = new Set(
|
|
274
|
+
own ?? [...profileNames].flatMap((name) => profileRightsOf(ctx.store, name)),
|
|
275
|
+
);
|
|
276
|
+
for (const code of minus(wanted, current)) {
|
|
277
|
+
insert(ctx, 'RIGHT_SUMMARY', { USER_NAME: user, RIGHT_CODE: code });
|
|
278
|
+
}
|
|
279
|
+
for (const code of minus(current, wanted)) {
|
|
280
|
+
removeRow(ctx, 'RIGHT_SUMMARY', { USER_NAME: user, RIGHT_CODE: code });
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
// consolidateRightsForUsers: each user's own PROFILE_USER rows.
|
|
284
|
+
function consolidateUsers(ctx: EventHandlerCtx, users: Iterable<string>, fixed: FixedRights): void {
|
|
285
|
+
for (const user of new Set(users)) consolidate(ctx, user, profilesOf(ctx.store, user), fixed);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const profileUser = (PROFILE_NAME: string, USER_NAME: string) => ({ PROFILE_NAME, USER_NAME });
|
|
289
|
+
const profileRight = (PROFILE_NAME: string, RIGHT_CODE: string) => ({ RIGHT_CODE, PROFILE_NAME });
|
|
290
|
+
|
|
291
|
+
// UEH :22-38 validateProfiles: one INVALID_PARAMETER per profile that isn't
|
|
292
|
+
// there, all in one NACK.
|
|
293
|
+
function checkProfiles(store: Store, names: string[]): void {
|
|
294
|
+
const missing = names.filter((name) => !store.getRow('PROFILE', name));
|
|
295
|
+
if (missing.length > 0) {
|
|
296
|
+
throw new NackError(
|
|
297
|
+
missing.map((name) => scriptError('INVALID_PARAMETER', `Profile ${name} not found`)),
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// User.fromGenesisSet and UserAttributes.fromGenesisSet of the view's fields
|
|
303
|
+
// (UEH :79-82, :190-193): every column the view has, null when DETAILS leaves
|
|
304
|
+
// it out, and the entity's own defaults for the rest. entityDb.modify(entity)
|
|
305
|
+
// writes the whole entity (the field-list modify ENABLE_USER uses is the one
|
|
306
|
+
// that writes some), so an amend sets every one of them.
|
|
307
|
+
const userEntity = (details: Row): Row => ({
|
|
308
|
+
USER_NAME: details.USER_NAME,
|
|
309
|
+
LAST_LOGIN: details.LAST_LOGIN ?? null,
|
|
310
|
+
...Object.fromEntries(USER_VIEW_COLUMNS.map((name) => [name, details[name] ?? null])),
|
|
311
|
+
PASSWORD_EXPIRY_DATETIME: null,
|
|
312
|
+
});
|
|
313
|
+
const attributesEntity = (details: Row): Row => ({
|
|
314
|
+
USER_NAME: details.USER_NAME,
|
|
315
|
+
USER_TYPE: details.USER_TYPE ?? 'USER',
|
|
316
|
+
ACCESS_TYPE: details.ACCESS_TYPE ?? 'ALL',
|
|
317
|
+
...Object.fromEntries(ADDRESS_LINES.map(([wire, column]) => [column, details[wire] ?? null])),
|
|
318
|
+
...Object.fromEntries(ATTRIBUTE_VIEW_COLUMNS.map((name) => [name, details[name] ?? null])),
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
// --- the events ----------------------------------------------------------------------
|
|
322
|
+
|
|
323
|
+
export interface AuthBackingOptions {
|
|
324
|
+
// Who an event runs as: its connection's login, else the session user.
|
|
325
|
+
userOf(ctx: EventHandlerCtx): string;
|
|
326
|
+
// The users' passwords at the start, by user name.
|
|
327
|
+
passwords: Map<string, string>;
|
|
328
|
+
// The rights some users keep whatever their profiles, by user name.
|
|
329
|
+
fixedRights?: FixedRights;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// A base64 PNG for CREATE_MFA_SECRET_ACK's QR_IMAGE: one transparent pixel,
|
|
333
|
+
// as the mock makes no TOTP secret to draw.
|
|
334
|
+
const QR_IMAGE =
|
|
335
|
+
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
|
|
336
|
+
|
|
337
|
+
function userEvents(passwords: Credentials, fixed: FixedRights): Record<string, EventHandler> {
|
|
338
|
+
// UEH :254-308, ENABLE_USER and DISABLE_USER: STATUS alone.
|
|
339
|
+
const setStatus =
|
|
340
|
+
(status: string): EventHandler =>
|
|
341
|
+
(details, ctx) => {
|
|
342
|
+
const user = ctx.store.getRow('USER', details.USER_NAME);
|
|
343
|
+
if (!user || !ctx.store.getRow('USER_ATTRIBUTES', details.USER_NAME)) {
|
|
344
|
+
throw NackError.nack('User does not exist');
|
|
345
|
+
}
|
|
346
|
+
if (user.STATUS === status) {
|
|
347
|
+
throw NackError.nack(`User ${user.USER_NAME} is already ${status}`);
|
|
348
|
+
}
|
|
349
|
+
if (ctx.validate) return {};
|
|
350
|
+
modify(ctx, 'USER', details.USER_NAME, { STATUS: status });
|
|
351
|
+
return {};
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
return {
|
|
355
|
+
// UEH :73. A new user's STATUS is auth-preferences' userStatusOnCreation,
|
|
356
|
+
// PASSWORD_EXPIRED by default: their first login asks for a new password.
|
|
357
|
+
EVENT_INSERT_USER: (details, ctx) => {
|
|
358
|
+
const name = details.USER_NAME as string;
|
|
359
|
+
const userProfiles = details.USER_PROFILES as string[] | null | undefined;
|
|
360
|
+
if (userProfiles != null) checkProfiles(ctx.store, userProfiles);
|
|
361
|
+
if (details.ONE_TIME_PASSWORD == null) {
|
|
362
|
+
throw new NackError(
|
|
363
|
+
scriptError('INVALID_PASSWORD', 'A valid password is required to insert a new user'),
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
if (ctx.store.getRow('USER', name)) {
|
|
367
|
+
throw new NackError(scriptError('DUPLICATE_KEY', `User ${name} already exists`));
|
|
368
|
+
}
|
|
369
|
+
if (ctx.validate) return {};
|
|
370
|
+
insert(ctx, 'USER', { ...userEntity(details), ONLINE: false, STATUS: PASSWORD_EXPIRED });
|
|
371
|
+
insert(ctx, 'USER_ATTRIBUTES', attributesEntity(details));
|
|
372
|
+
// PasswordService.processHistory keeps no USER_PASSWORD_HISTORY rows
|
|
373
|
+
// under the default reuse count (none): it inserts the password, then
|
|
374
|
+
// deletes the user's every row.
|
|
375
|
+
passwords.set(ctx, name, details.ONE_TIME_PASSWORD);
|
|
376
|
+
if (userProfiles != null) {
|
|
377
|
+
for (const profile of new Set(userProfiles)) {
|
|
378
|
+
insert(ctx, 'PROFILE_USER', profileUser(profile, name));
|
|
379
|
+
}
|
|
380
|
+
consolidate(ctx, name, userProfiles, fixed);
|
|
381
|
+
}
|
|
382
|
+
return {};
|
|
383
|
+
},
|
|
384
|
+
// UEH :161. STATUS and PASSWORD stay the stored ones (:196-197); a missing
|
|
385
|
+
// USER_ATTRIBUTES row fails the modify. Profiles change only when
|
|
386
|
+
// USER_PROFILES is sent.
|
|
387
|
+
EVENT_AMEND_USER: (details, ctx) => {
|
|
388
|
+
const name = details.USER_NAME as string;
|
|
389
|
+
const userProfiles = details.USER_PROFILES as string[] | null | undefined;
|
|
390
|
+
if (userProfiles != null) checkProfiles(ctx.store, userProfiles);
|
|
391
|
+
const stored = ctx.store.getRow('USER', name);
|
|
392
|
+
if (!stored) throw NackError.nack('User does not exist');
|
|
393
|
+
if (ctx.validate) return {};
|
|
394
|
+
// ONLINE as stored: the entity's false, which GSF's session listener
|
|
395
|
+
// (UserSessionTableListener) puts back within ten seconds.
|
|
396
|
+
modify(ctx, 'USER', name, {
|
|
397
|
+
...userEntity(details),
|
|
398
|
+
ONLINE: stored.ONLINE ?? false,
|
|
399
|
+
STATUS: stored.STATUS ?? null,
|
|
400
|
+
});
|
|
401
|
+
modify(ctx, 'USER_ATTRIBUTES', name, attributesEntity(details));
|
|
402
|
+
if (userProfiles != null) {
|
|
403
|
+
const current = profilesOf(ctx.store, name);
|
|
404
|
+
for (const profile of minus(userProfiles, current)) {
|
|
405
|
+
insert(ctx, 'PROFILE_USER', profileUser(profile, name));
|
|
406
|
+
}
|
|
407
|
+
for (const profile of minus(current, userProfiles)) {
|
|
408
|
+
removeRow(ctx, 'PROFILE_USER', profileUser(profile, name));
|
|
409
|
+
}
|
|
410
|
+
consolidate(ctx, name, userProfiles, fixed);
|
|
411
|
+
}
|
|
412
|
+
return {};
|
|
413
|
+
},
|
|
414
|
+
// UEH :229: no onValidate, so VALIDATE acks whoever it names.
|
|
415
|
+
EVENT_DELETE_USER: (details, ctx) => {
|
|
416
|
+
const name = details.USER_NAME as string;
|
|
417
|
+
if (ctx.validate) return {};
|
|
418
|
+
remove(ctx, 'USER', name);
|
|
419
|
+
passwords.remove(ctx, name);
|
|
420
|
+
remove(ctx, 'USER_ATTRIBUTES', name);
|
|
421
|
+
for (const row of rowsWhere(ctx.store, 'PROFILE_USER', 'USER_NAME', name)) {
|
|
422
|
+
removeRow(ctx, 'PROFILE_USER', row);
|
|
423
|
+
}
|
|
424
|
+
consolidate(ctx, name, [], fixed);
|
|
425
|
+
return {};
|
|
426
|
+
},
|
|
427
|
+
EVENT_ENABLE_USER: setStatus(ENABLED),
|
|
428
|
+
EVENT_DISABLE_USER: setStatus(DISABLED),
|
|
429
|
+
// UEH :310. It doesn't check the user is there, and consolidates over the
|
|
430
|
+
// profiles the user had plus the new ones (:337-341): a removed profile's
|
|
431
|
+
// rights stay in RIGHT_SUMMARY until something consolidates the user
|
|
432
|
+
// again.
|
|
433
|
+
EVENT_USER_PROFILE_AMEND: (details, ctx) => {
|
|
434
|
+
const name = details.USER_NAME as string;
|
|
435
|
+
const wanted = (details.USER_PROFILES ?? []) as string[];
|
|
436
|
+
checkProfiles(ctx.store, wanted);
|
|
437
|
+
if (ctx.validate) return {};
|
|
438
|
+
const current = profilesOf(ctx.store, name);
|
|
439
|
+
const added = minus(wanted, current);
|
|
440
|
+
for (const profile of added) insert(ctx, 'PROFILE_USER', profileUser(profile, name));
|
|
441
|
+
for (const profile of minus(current, wanted)) {
|
|
442
|
+
removeRow(ctx, 'PROFILE_USER', profileUser(profile, name));
|
|
443
|
+
}
|
|
444
|
+
consolidate(ctx, name, [...current, ...added], fixed);
|
|
445
|
+
return {};
|
|
446
|
+
},
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function profileEvents(fixed: FixedRights): Record<string, EventHandler> {
|
|
451
|
+
// PROFILE as InsertAmendProfile builds it: STATUS "ACTIVE" unless sent
|
|
452
|
+
// (the platform's seeded profiles say ENABLED), IS_PRIMARY its default.
|
|
453
|
+
const profileEntity = (details: Row): Row => ({
|
|
454
|
+
NAME: details.NAME,
|
|
455
|
+
DESCRIPTION: details.DESCRIPTION ?? null,
|
|
456
|
+
STATUS: details.STATUS ?? 'ACTIVE',
|
|
457
|
+
IS_PRIMARY: true,
|
|
458
|
+
});
|
|
459
|
+
return {
|
|
460
|
+
// PEH :10: no onValidate. Rights and user names aren't checked against
|
|
461
|
+
// RIGHT and USER.
|
|
462
|
+
EVENT_INSERT_PROFILE: (details, ctx) => {
|
|
463
|
+
const name = details.NAME as string;
|
|
464
|
+
if (ctx.validate) return {};
|
|
465
|
+
insert(ctx, 'PROFILE', profileEntity(details));
|
|
466
|
+
const rights = minus(details.RIGHT_CODES ?? [], profileRightsOf(ctx.store, name));
|
|
467
|
+
for (const code of rights) insert(ctx, 'PROFILE_RIGHT', profileRight(name, code));
|
|
468
|
+
const users = minus(details.USER_NAMES ?? [], usersOf(ctx.store, name));
|
|
469
|
+
for (const user of users) insert(ctx, 'PROFILE_USER', profileUser(name, user));
|
|
470
|
+
consolidateUsers(ctx, users, fixed);
|
|
471
|
+
return {};
|
|
472
|
+
},
|
|
473
|
+
// PEH :74. A list left out empties the profile (:94, :101): an amend
|
|
474
|
+
// sends both in full.
|
|
475
|
+
EVENT_AMEND_PROFILE: (details, ctx) => {
|
|
476
|
+
const name = details.NAME as string;
|
|
477
|
+
if (!ctx.store.getRow('PROFILE', name)) {
|
|
478
|
+
throw NackError.nack(`Profile ${name} does not exist`);
|
|
479
|
+
}
|
|
480
|
+
if (ctx.validate) return {};
|
|
481
|
+
const currentUsers = usersOf(ctx.store, name);
|
|
482
|
+
const wantedUsers = (details.USER_NAMES ?? []) as string[];
|
|
483
|
+
const currentRights = profileRightsOf(ctx.store, name);
|
|
484
|
+
const wantedRights = (details.RIGHT_CODES ?? []) as string[];
|
|
485
|
+
const [usersToAdd, usersToDelete] = [
|
|
486
|
+
minus(wantedUsers, currentUsers),
|
|
487
|
+
minus(currentUsers, wantedUsers),
|
|
488
|
+
];
|
|
489
|
+
const [rightsToAdd, rightsToDelete] = [
|
|
490
|
+
minus(wantedRights, currentRights),
|
|
491
|
+
minus(currentRights, wantedRights),
|
|
492
|
+
];
|
|
493
|
+
modify(ctx, 'PROFILE', name, profileEntity(details));
|
|
494
|
+
for (const user of usersToAdd) insert(ctx, 'PROFILE_USER', profileUser(name, user));
|
|
495
|
+
for (const code of rightsToAdd) insert(ctx, 'PROFILE_RIGHT', profileRight(name, code));
|
|
496
|
+
for (const user of usersToDelete) removeRow(ctx, 'PROFILE_USER', profileUser(name, user));
|
|
497
|
+
for (const code of rightsToDelete) {
|
|
498
|
+
removeRow(ctx, 'PROFILE_RIGHT', profileRight(name, code));
|
|
499
|
+
}
|
|
500
|
+
// :118-122: every user of the profile when its rights changed.
|
|
501
|
+
const rightsChanged = rightsToAdd.length > 0 || rightsToDelete.length > 0;
|
|
502
|
+
consolidateUsers(
|
|
503
|
+
ctx,
|
|
504
|
+
[...(rightsChanged ? currentUsers : []), ...usersToDelete, ...usersToAdd],
|
|
505
|
+
fixed,
|
|
506
|
+
);
|
|
507
|
+
return {};
|
|
508
|
+
},
|
|
509
|
+
// PEH :56. The users it consolidates are read off `profileUsers`, a cold
|
|
510
|
+
// Flow (getRange) collected again after deleteAll removed its rows
|
|
511
|
+
// (:63-68): none, so the profile's users keep its rights in RIGHT_SUMMARY
|
|
512
|
+
// until something consolidates them again.
|
|
513
|
+
EVENT_DELETE_PROFILE: (details, ctx) => {
|
|
514
|
+
const name = details.NAME as string;
|
|
515
|
+
if (ctx.validate) return {};
|
|
516
|
+
remove(ctx, 'PROFILE', name);
|
|
517
|
+
for (const row of rowsWhere(ctx.store, 'PROFILE_USER', 'PROFILE_NAME', name)) {
|
|
518
|
+
removeRow(ctx, 'PROFILE_USER', row);
|
|
519
|
+
}
|
|
520
|
+
for (const row of rowsWhere(ctx.store, 'PROFILE_RIGHT', 'PROFILE_NAME', name)) {
|
|
521
|
+
removeRow(ctx, 'PROFILE_RIGHT', row);
|
|
522
|
+
}
|
|
523
|
+
return {};
|
|
524
|
+
},
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
function passwordEvents(
|
|
529
|
+
userOf: AuthBackingOptions['userOf'],
|
|
530
|
+
passwords: Credentials,
|
|
531
|
+
): Record<string, EventHandler> {
|
|
532
|
+
// ScriptUtils.checkSelfAccess: one's own account, or the right to act on
|
|
533
|
+
// anyone's.
|
|
534
|
+
const checkSelfAccess = (store: Store, requester: string, target: string, right: string) => {
|
|
535
|
+
if (requester !== target && !hasRight(store, requester, right)) {
|
|
536
|
+
throw notAuthorised(requester);
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
return {
|
|
540
|
+
// PWD :21: no permission codes, and the router lets it through logged
|
|
541
|
+
// out too (MsgType.kt:51-53): the expired-password screen sends it before
|
|
542
|
+
// its user can log in (see the change-password route).
|
|
543
|
+
EVENT_CHANGE_USER_PASSWORD: (details, ctx) => {
|
|
544
|
+
const requester = userOf(ctx);
|
|
545
|
+
const target = (details.USER_NAME as string | null | undefined) ?? requester;
|
|
546
|
+
checkSelfAccess(ctx.store, requester, target, 'CHANGE_PWD');
|
|
547
|
+
if (ctx.validate) return {};
|
|
548
|
+
// PasswordService.changeUserPassword: the target's old password, even
|
|
549
|
+
// for an admin (a user without one, and a blank old one, pass); no
|
|
550
|
+
// strength rules; no history to check under the default reuse count.
|
|
551
|
+
const user = ctx.store.getRow('USER', target);
|
|
552
|
+
const old = details.OLD_PASSWORD as string;
|
|
553
|
+
const oldIsValid = passwords.has(ctx.store, target)
|
|
554
|
+
? passwords.matches(ctx.store, target, old)
|
|
555
|
+
: old.trim() === '';
|
|
556
|
+
if (!user || !oldIsValid) throw new NackError(INCORRECT_CREDENTIALS);
|
|
557
|
+
modify(ctx, 'USER', target, NEEDS_NEW_PASSWORD.has(user.STATUS) ? { STATUS: ENABLED } : {});
|
|
558
|
+
passwords.set(ctx, target, details.NEW_PASSWORD);
|
|
559
|
+
// :48-52, as part of the self-service flow.
|
|
560
|
+
const attempt = { USER_NAME: target, LOGIN_ATTEMPTS: 0, LOGIN_LAST_ATTEMPT_TIME: Date.now() };
|
|
561
|
+
if (ctx.store.getRow('USER_LOGIN_ATTEMPT', target)) {
|
|
562
|
+
modify(ctx, 'USER_LOGIN_ATTEMPT', target, attempt);
|
|
563
|
+
} else {
|
|
564
|
+
insert(ctx, 'USER_LOGIN_ATTEMPT', attempt);
|
|
565
|
+
}
|
|
566
|
+
return {};
|
|
567
|
+
},
|
|
568
|
+
// PWD :63, PasswordService.expireUserPassword: a new password when one's
|
|
569
|
+
// given, and PASSWORD_EXPIRED either way.
|
|
570
|
+
EVENT_EXPIRE_USER_PASSWORD: (details, ctx) => {
|
|
571
|
+
const target = details.USER_NAME as string;
|
|
572
|
+
checkSelfAccess(ctx.store, userOf(ctx), target, 'EXPIRE_PWD');
|
|
573
|
+
if (ctx.validate) return {};
|
|
574
|
+
if (!ctx.store.getRow('USER', target)) throw new Error(`Failed to find user ${target}`);
|
|
575
|
+
const password = details.PASSWORD as string | null | undefined;
|
|
576
|
+
if (password) passwords.set(ctx, target, password);
|
|
577
|
+
modify(ctx, 'USER', target, { STATUS: PASSWORD_EXPIRED });
|
|
578
|
+
return {};
|
|
579
|
+
},
|
|
580
|
+
};
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
// PasswordService.genericPasswordValidationFailure, which the script NACKs
|
|
584
|
+
// with as it is: a missing user and a wrong old password alike.
|
|
585
|
+
const INCORRECT_CREDENTIALS: NackErrorInput = {
|
|
586
|
+
'@type': 'PasswordValidationError',
|
|
587
|
+
CODE: 'INCORRECT_CREDENTIALS',
|
|
588
|
+
TEXT: 'Incorrect credentials',
|
|
589
|
+
STATUS_CODE: '401 Unauthorized',
|
|
590
|
+
};
|
|
591
|
+
|
|
592
|
+
// MFA: a secret waits in memory for its confirmation (MfaSecretService), and
|
|
593
|
+
// MFA_SECRET isn't kept, as no login here asks for a code.
|
|
594
|
+
function mfaEvents(userOf: AuthBackingOptions['userOf']): Record<string, EventHandler> {
|
|
595
|
+
// The users whose secret waits for a confirmation, per server.
|
|
596
|
+
const waiting = new WeakMap<Store, Set<string>>();
|
|
597
|
+
const pendingOf = (store: Store) => {
|
|
598
|
+
let users = waiting.get(store);
|
|
599
|
+
if (!users) {
|
|
600
|
+
users = new Set();
|
|
601
|
+
waiting.set(store, users);
|
|
602
|
+
}
|
|
603
|
+
return users;
|
|
604
|
+
};
|
|
605
|
+
return {
|
|
606
|
+
// MFA :16, eventHandler<Unit, CreateMfaSecretReply>: replies of its own.
|
|
607
|
+
EVENT_MFA_CREATE_SECRET: (_details, ctx) => {
|
|
608
|
+
const user = userOf(ctx);
|
|
609
|
+
if (!ctx.store.getRow('USER', user) || !ctx.store.getRow('USER_ATTRIBUTES', user)) {
|
|
610
|
+
throw new NackError(scriptError('UNKNOWN_ACCOUNT', 'User does not exist'), {
|
|
611
|
+
messageType: 'CREATE_MFA_SECRET_NACK',
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
if (ctx.validate) return { reply: { MESSAGE_TYPE: 'CREATE_MFA_SECRET_VALIDATE_ACK' } };
|
|
615
|
+
ctx.afterCommit(() => pendingOf(ctx.store).add(user));
|
|
616
|
+
return { reply: { MESSAGE_TYPE: 'CREATE_MFA_SECRET_ACK', QR_IMAGE } };
|
|
617
|
+
},
|
|
618
|
+
// MFA :35: any code confirms the user's waiting secret.
|
|
619
|
+
EVENT_MFA_CONFIRM_SECRET: (_details, ctx) => {
|
|
620
|
+
if (ctx.validate) return {};
|
|
621
|
+
const user = userOf(ctx);
|
|
622
|
+
if (!pendingOf(ctx.store).has(user)) {
|
|
623
|
+
throw NackError.nack('Secret is Unavailable, probably User took too long to Confirm');
|
|
624
|
+
}
|
|
625
|
+
ctx.afterCommit(() => pendingOf(ctx.store).delete(user));
|
|
626
|
+
return {};
|
|
627
|
+
},
|
|
628
|
+
// MFA :48, :64: on the real server they need MFA_ENABLE and MFA_DISABLE,
|
|
629
|
+
// rights no platform profile holds.
|
|
630
|
+
EVENT_ENABLE_MFA_FOR_USER: () => ({}),
|
|
631
|
+
EVENT_DISABLE_MFA_FOR_USER: () => ({}),
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
// --- request servers -----------------------------------------------------------------
|
|
636
|
+
|
|
637
|
+
// RR :173 requestReply("USER_PROFILES", USER_PROFILE_DETAILS_VIEW) { request
|
|
638
|
+
// { USER_NAME } reply { PROFILE_NAME withAlias "NAME", DESCRIPTION } }: in
|
|
639
|
+
// PROFILE_USER's key order, so by profile.
|
|
640
|
+
const USER_PROFILE_NAMES: ViewDef = {
|
|
641
|
+
base: 'PROFILE_USER',
|
|
642
|
+
joins: [
|
|
643
|
+
{ table: 'USER', on: ['USER_NAME', 'USER_NAME'], type: 'INNER', backwardsJoin: true },
|
|
644
|
+
{
|
|
645
|
+
table: 'PROFILE',
|
|
646
|
+
on: ['PROFILE_NAME', 'NAME'],
|
|
647
|
+
type: 'INNER',
|
|
648
|
+
backwardsJoin: true,
|
|
649
|
+
select: { DESCRIPTION: 'DESCRIPTION' },
|
|
650
|
+
},
|
|
651
|
+
],
|
|
652
|
+
select: { NAME: 'PROFILE_NAME' },
|
|
653
|
+
fields: ['USER_NAME', 'NAME', 'DESCRIPTION'],
|
|
654
|
+
};
|
|
655
|
+
|
|
656
|
+
// RR :137 requestReply("USER_ATTRIBUTES_AUDIT", USER_AUDIT_VIEW): its reply
|
|
657
|
+
// block names USER_ATTRIBUTES_AUDIT's columns, which the view doesn't have
|
|
658
|
+
// under those names, and a real server sends the view's whole row instead
|
|
659
|
+
// (captured META: REPLY_FIELD is USER_AUDIT_VIEW's fields, then RECORD_ID and
|
|
660
|
+
// TIMESTAMP). The view's USER_ATTRIBUTES_AUDIT join (USER_AUDIT_ID =
|
|
661
|
+
// USER_ATTRIBUTES_AUDIT_ID, ids of two sequences) never matches, so the
|
|
662
|
+
// attributes' columns are null.
|
|
663
|
+
function requestReplies(): Record<string, RequestReplyDef> {
|
|
664
|
+
return {
|
|
665
|
+
USER_PROFILES: {
|
|
666
|
+
source: 'USER_PROFILE_NAMES',
|
|
667
|
+
requestFields: ['USER_NAME'],
|
|
668
|
+
fields: ['NAME', 'DESCRIPTION'],
|
|
669
|
+
},
|
|
670
|
+
USER_ATTRIBUTES_AUDIT: { source: 'USER_AUDIT_VIEW', requestFields: ['USER_AUDIT_ID'] },
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// --- logins --------------------------------------------------------------------------
|
|
675
|
+
|
|
676
|
+
// The login ack's USER_DETAILS source (AuthUser.user).
|
|
677
|
+
const LOGIN_USER_FIELDS = ['FIRST_NAME', 'LAST_NAME', 'EMAIL_ADDRESS', 'COMPANY_NAME'];
|
|
678
|
+
|
|
679
|
+
// auth's retry defaults (RetryOptionsDefinition): three failed attempts lock
|
|
680
|
+
// the name they named out for five minutes, a right password included.
|
|
681
|
+
const MAX_ATTEMPTS = 3;
|
|
682
|
+
const LOCKOUT_MS = 300_000;
|
|
683
|
+
|
|
684
|
+
// USER.LAST_LOGIN, a DATE: today.
|
|
685
|
+
const today = () => {
|
|
686
|
+
const now = new Date();
|
|
687
|
+
return Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
|
|
688
|
+
};
|
|
689
|
+
|
|
690
|
+
// The writes of one login or logout, which runs in no event: a transaction
|
|
691
|
+
// of its own, audited as the message (USER's ONLINE and LAST_LOGIN add
|
|
692
|
+
// USER_AUDIT rows), kept whatever the login answers, as auth returns its
|
|
693
|
+
// failures rather than throwing them, and pushed live once committed.
|
|
694
|
+
interface LoginWrites {
|
|
695
|
+
put(table: string, row: Row): void;
|
|
696
|
+
// A USER_LOGIN_AUDIT row (LoginAuditController.processAuthAuditUpdate).
|
|
697
|
+
audit(user: string, action: string, reason: string): void;
|
|
698
|
+
}
|
|
699
|
+
function inLoginTransaction<T>(
|
|
700
|
+
ctx: LoginCtx,
|
|
701
|
+
eventType: string,
|
|
702
|
+
auditUser: string,
|
|
703
|
+
write: (writes: LoginWrites) => T,
|
|
704
|
+
): T {
|
|
705
|
+
const { store } = ctx;
|
|
706
|
+
const changes: Array<[string, 'INSERT' | 'MODIFY', string]> = [];
|
|
707
|
+
const put = (table: string, row: Row) => {
|
|
708
|
+
const key = store.rowKey(table, row);
|
|
709
|
+
if (store.getRow(table, key)) {
|
|
710
|
+
store.updateRow(table, key, row);
|
|
711
|
+
changes.push([table, 'MODIFY', key]);
|
|
712
|
+
} else {
|
|
713
|
+
changes.push([table, 'INSERT', store.rowKey(table, store.insertRow(table, row))]);
|
|
714
|
+
}
|
|
715
|
+
};
|
|
716
|
+
const writes: LoginWrites = {
|
|
717
|
+
put,
|
|
718
|
+
audit: (user, action, reason) =>
|
|
719
|
+
put('USER_LOGIN_AUDIT', {
|
|
720
|
+
USER_NAME: user,
|
|
721
|
+
AUTH_ACTION: action,
|
|
722
|
+
IP_ADDRESS: ctx.hostname,
|
|
723
|
+
REASON: reason,
|
|
724
|
+
}),
|
|
725
|
+
};
|
|
726
|
+
store.begin({ eventType, user: auditUser, text: null });
|
|
727
|
+
let result: T;
|
|
728
|
+
try {
|
|
729
|
+
result = write(writes);
|
|
730
|
+
} catch (error) {
|
|
731
|
+
store.rollback();
|
|
732
|
+
throw error;
|
|
733
|
+
}
|
|
734
|
+
const audits = store.takeAuditWrites();
|
|
735
|
+
store.commit();
|
|
736
|
+
// Committed whatever a push does: one that fails is logged, and the login
|
|
737
|
+
// still answers.
|
|
738
|
+
const pushes: Array<[string, 'INSERT' | 'MODIFY', string]> = [
|
|
739
|
+
...changes,
|
|
740
|
+
...audits.map(({ tableName, key }): [string, 'INSERT', string] => [tableName, 'INSERT', key]),
|
|
741
|
+
];
|
|
742
|
+
for (const [table, operation, key] of pushes) {
|
|
743
|
+
try {
|
|
744
|
+
ctx.broadcastTableChange(table, operation, key);
|
|
745
|
+
} catch (error) {
|
|
746
|
+
console.error('[mock-server] Error pushing a login change:', error);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
return result;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
// Logins over the USER, PROFILE_USER and RIGHT_SUMMARY tables, as auth's
|
|
753
|
+
// authenticators and LoginProcessor run them (auth v8.15.5's bytecode): the
|
|
754
|
+
// checks in GenesisDbAuthenticator's order, the lockout
|
|
755
|
+
// LoginAttemptCounterService keeps in USER_LOGIN_ATTEMPT, a USER_LOGIN_AUDIT
|
|
756
|
+
// row for each login, failed login and logout, and USER's ONLINE and
|
|
757
|
+
// LAST_LOGIN. The ack's PROFILE and PERMISSION are the user's rows now. Not
|
|
758
|
+
// modelled: USER_SESSION and USER_LOGIN (no resource reads them; the
|
|
759
|
+
// sessions are the engine's), PASSWORD_EXPIRY_DATETIME (nothing here sets
|
|
760
|
+
// one), the expiry sweep that clears ONLINE.
|
|
761
|
+
function authDirectory(passwords: Credentials): AuthDirectory {
|
|
762
|
+
function user(username: string, store: Store): AuthUser | undefined {
|
|
763
|
+
const row = store.getRow('USER', username);
|
|
764
|
+
if (!row) return undefined;
|
|
765
|
+
return {
|
|
766
|
+
username,
|
|
767
|
+
status: String(row.STATUS ?? ''),
|
|
768
|
+
profile: profilesOf(store, username),
|
|
769
|
+
permission: rightsOf(store, username),
|
|
770
|
+
user: Object.fromEntries(LOGIN_USER_FIELDS.map((name) => [name, row[name] ?? null])),
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// GenesisDbAuthenticator: an unknown or DISABLED user fails as a wrong
|
|
775
|
+
// password does, and a status that asks for a new password answers so,
|
|
776
|
+
// both before the password is looked at; a right password with any other
|
|
777
|
+
// status but ENABLED (null too) is LOCKED_ACCOUNT.
|
|
778
|
+
function authenticate(store: Store, username: string, password: string) {
|
|
779
|
+
const row = store.getRow('USER', username);
|
|
780
|
+
if (!row || row.STATUS === DISABLED) return 'INCORRECT_CREDENTIALS';
|
|
781
|
+
if (NEEDS_NEW_PASSWORD.has(row.STATUS)) return 'PASSWORD_EXPIRED';
|
|
782
|
+
if (!passwords.matches(store, username, password)) return 'INCORRECT_CREDENTIALS';
|
|
783
|
+
return row.STATUS === ENABLED ? undefined : 'LOCKED_ACCOUNT';
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// AuthenticationService.login after the authenticator: the attempt
|
|
787
|
+
// counter for the name the login named (known or not), and what
|
|
788
|
+
// LoginProcessor writes. A locked-out name fails MAX_TRIES_REACHED whatever
|
|
789
|
+
// the answer, recorded under its name and under UNKNOWN (the AuthException
|
|
790
|
+
// that carries it names no one), without counting.
|
|
791
|
+
function settle(
|
|
792
|
+
writes: LoginWrites,
|
|
793
|
+
store: Store,
|
|
794
|
+
username: string,
|
|
795
|
+
failure: LoginFailure | undefined,
|
|
796
|
+
): AuthUser | LoginFailure {
|
|
797
|
+
const now = Date.now();
|
|
798
|
+
const counter = store.getRow('USER_LOGIN_ATTEMPT', username);
|
|
799
|
+
let attempts = (counter?.LOGIN_ATTEMPTS as number | undefined) ?? 0;
|
|
800
|
+
const lastAttempt = (counter?.LOGIN_LAST_ATTEMPT_TIME as number | undefined) ?? now;
|
|
801
|
+
if (attempts >= MAX_ATTEMPTS) {
|
|
802
|
+
if (now - lastAttempt <= LOCKOUT_MS) {
|
|
803
|
+
writes.audit(username, 'FAILED_LOGIN', 'MAX_TRIES_REACHED');
|
|
804
|
+
writes.audit('UNKNOWN', 'FAILED_LOGIN', 'MAX_TRIES_REACHED');
|
|
805
|
+
return 'MAX_TRIES_REACHED';
|
|
806
|
+
}
|
|
807
|
+
attempts = 0;
|
|
808
|
+
}
|
|
809
|
+
if (failure) {
|
|
810
|
+
attempts += 1;
|
|
811
|
+
writes.put('USER_LOGIN_ATTEMPT', {
|
|
812
|
+
USER_NAME: username,
|
|
813
|
+
LOGIN_ATTEMPTS: attempts,
|
|
814
|
+
LOGIN_LAST_ATTEMPT_TIME: attempts >= MAX_ATTEMPTS ? now : lastAttempt,
|
|
815
|
+
});
|
|
816
|
+
writes.audit(username, 'FAILED_LOGIN', failure);
|
|
817
|
+
return failure;
|
|
818
|
+
}
|
|
819
|
+
writes.put('USER_LOGIN_ATTEMPT', {
|
|
820
|
+
USER_NAME: username,
|
|
821
|
+
LOGIN_ATTEMPTS: 0,
|
|
822
|
+
LOGIN_LAST_ATTEMPT_TIME: now,
|
|
823
|
+
});
|
|
824
|
+
// SessionManager.updateUserStatus and LoginProcessor: always a write,
|
|
825
|
+
// as LAST_LOGIN is now.
|
|
826
|
+
writes.put('USER', { USER_NAME: username, ONLINE: true, LAST_LOGIN: today() });
|
|
827
|
+
writes.audit(username, 'LOGIN', '');
|
|
828
|
+
return user(username, store)!;
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
// Who what a login writes is audited as: the message's own USER_NAME.
|
|
832
|
+
const loginUser = (ctx: LoginCtx) => ctx.messageUser ?? 'UNKNOWN';
|
|
833
|
+
return {
|
|
834
|
+
user,
|
|
835
|
+
login: (username, password, ctx) =>
|
|
836
|
+
inLoginTransaction(ctx, 'EVENT_LOGIN_AUTH', loginUser(ctx), (writes) => {
|
|
837
|
+
// No PASSWORD: no authenticator takes it, and no name is counted.
|
|
838
|
+
if (password === undefined) {
|
|
839
|
+
writes.audit('UNKNOWN', 'FAILED_LOGIN', 'NO_COMPATIBLE_PROVIDERS');
|
|
840
|
+
return 'NO_COMPATIBLE_PROVIDERS';
|
|
841
|
+
}
|
|
842
|
+
const failure = authenticate(ctx.store, username, password);
|
|
843
|
+
return settle(writes, ctx.store, username, failure);
|
|
844
|
+
}),
|
|
845
|
+
// RefreshTokenAuthenticator: the session's user re-read, and refused by
|
|
846
|
+
// their status; a refresh logs the old session out ("Session refreshed")
|
|
847
|
+
// before it logs in as a login does.
|
|
848
|
+
refresh: (username, ctx) =>
|
|
849
|
+
inLoginTransaction(ctx, 'EVENT_LOGIN_AUTH', loginUser(ctx), (writes) => {
|
|
850
|
+
if (username === undefined) {
|
|
851
|
+
writes.audit('UNKNOWN', 'FAILED_LOGIN', 'UNKNOWN_ACCOUNT');
|
|
852
|
+
return 'UNKNOWN_ACCOUNT';
|
|
853
|
+
}
|
|
854
|
+
const row = ctx.store.getRow('USER', username);
|
|
855
|
+
let failure: LoginFailure | undefined;
|
|
856
|
+
if (!row) failure = 'UNKNOWN_ACCOUNT';
|
|
857
|
+
else if (NEEDS_NEW_PASSWORD.has(row.STATUS)) failure = 'PASSWORD_EXPIRED';
|
|
858
|
+
else if (row.STATUS !== ENABLED) failure = 'LOCKED_ACCOUNT';
|
|
859
|
+
else writes.audit(username, 'LOGOUT', 'Session refreshed');
|
|
860
|
+
return settle(writes, ctx.store, username, failure);
|
|
861
|
+
}),
|
|
862
|
+
// The logout handler (auth-login-eventhandler.kts:50-80): ONLINE as the
|
|
863
|
+
// user's other sessions say, written only when it changes.
|
|
864
|
+
logout: (username, online, ctx) =>
|
|
865
|
+
inLoginTransaction(ctx, 'EVENT_LOGOUT', username, (writes) => {
|
|
866
|
+
const row = ctx.store.getRow('USER', username);
|
|
867
|
+
if (row && row.ONLINE !== online) {
|
|
868
|
+
writes.put('USER', { USER_NAME: username, ONLINE: online });
|
|
869
|
+
}
|
|
870
|
+
writes.audit(username, 'LOGOUT', '');
|
|
871
|
+
}),
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
const HTTP_OK = 200;
|
|
876
|
+
const HTTP_BAD_REQUEST = 400;
|
|
877
|
+
const HTTP_TOO_LARGE = 413;
|
|
878
|
+
// HttpObjectAggregatorDefinition.kt:4 @v8.15.29: the most a router endpoint
|
|
879
|
+
// reads of a body.
|
|
880
|
+
const MAX_CONTENT_LENGTH = 262_144;
|
|
881
|
+
|
|
882
|
+
// The router's refusal of a body it can't make a message of
|
|
883
|
+
// (HttpHandler.kt:184-188 @v8.15.29).
|
|
884
|
+
function undecodable(res: ServerResponse, sourceRef: string): void {
|
|
885
|
+
const text = 'Unable to deserialize message payload';
|
|
886
|
+
const STATUS_CODE = '400 Bad Request';
|
|
887
|
+
res.writeHead(HTTP_BAD_REQUEST, { 'Content-Type': 'application/json' });
|
|
888
|
+
res.end(
|
|
889
|
+
JSON.stringify({
|
|
890
|
+
MESSAGE_TYPE: 'MSG_NACK',
|
|
891
|
+
SOURCE_REF: sourceRef,
|
|
892
|
+
ERROR: [{ CODE: HTTP_BAD_REQUEST, TEXT: text, STATUS_CODE }],
|
|
893
|
+
DETAILS: { ERROR: text, STATUS_CODE },
|
|
894
|
+
}),
|
|
895
|
+
);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
// POST gwf/event-change-user-password: foundation-auth's change of password
|
|
899
|
+
// (passwordManagementMapper.ts), which the expired-password screen sends
|
|
900
|
+
// before its user can log in. GSF's router takes it logged in or out
|
|
901
|
+
// (ChangeUserPassword is MUST_BE_LOGGED_IN_OR_OUT, MsgType.kt:51-53): the
|
|
902
|
+
// session's user runs it, else the message's USER_NAME, else no one (whose
|
|
903
|
+
// rights reach no one else's password), with the SOURCE_REF the router mints
|
|
904
|
+
// for a request without one. The answer is the event's reply, with HTTP 200
|
|
905
|
+
// for a NACK too, as a router without strictHttpStatusCode sends (Utils.kt
|
|
906
|
+
// getHttpResponseStatus). A body over the router's aggregator limit is its
|
|
907
|
+
// empty 413, and one that isn't a JSON object its 400.
|
|
908
|
+
export const changePasswordRoute: HttpRouteDef = {
|
|
909
|
+
method: 'POST',
|
|
910
|
+
path: /\/event-change-user-password\/?$/,
|
|
911
|
+
handler: async (req, res, ctx) => {
|
|
912
|
+
const sourceRef = `AUTO_${randomUUID()}`;
|
|
913
|
+
let message: unknown;
|
|
914
|
+
try {
|
|
915
|
+
const raw = (await readBody(req, MAX_CONTENT_LENGTH)).toString('utf8');
|
|
916
|
+
message = raw ? JSON.parse(raw) : {};
|
|
917
|
+
} catch (error) {
|
|
918
|
+
if (error instanceof BodyTooLarge) {
|
|
919
|
+
res.writeHead(HTTP_TOO_LARGE, { 'Content-Length': 0, Connection: 'close' });
|
|
920
|
+
res.end();
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
923
|
+
message = undefined;
|
|
924
|
+
}
|
|
925
|
+
if (typeof message !== 'object' || message === null || Array.isArray(message)) {
|
|
926
|
+
undecodable(res, sourceRef);
|
|
927
|
+
return;
|
|
928
|
+
}
|
|
929
|
+
const request = message as Row;
|
|
930
|
+
const named = typeof request.USER_NAME === 'string' ? request.USER_NAME : '';
|
|
931
|
+
const reply = ctx.commitEvent(
|
|
932
|
+
{
|
|
933
|
+
...request,
|
|
934
|
+
SOURCE_REF: request.SOURCE_REF ?? sourceRef,
|
|
935
|
+
MESSAGE_TYPE: 'EVENT_CHANGE_USER_PASSWORD',
|
|
936
|
+
},
|
|
937
|
+
ctx.userName ?? named,
|
|
938
|
+
);
|
|
939
|
+
res.writeHead(HTTP_OK, { 'Content-Type': 'application/json' });
|
|
940
|
+
res.end(JSON.stringify(reply));
|
|
941
|
+
},
|
|
942
|
+
};
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* auth's events, request servers and views, for the platform preset to merge.
|
|
946
|
+
*/
|
|
947
|
+
export function authBacking({ userOf, passwords, fixedRights = new Map() }: AuthBackingOptions) {
|
|
948
|
+
const kept = credentials(passwords);
|
|
949
|
+
return {
|
|
950
|
+
eventHandlers: {
|
|
951
|
+
...userEvents(kept, fixedRights),
|
|
952
|
+
...profileEvents(fixedRights),
|
|
953
|
+
...passwordEvents(userOf, kept),
|
|
954
|
+
...mfaEvents(userOf),
|
|
955
|
+
},
|
|
956
|
+
eventSchemas: EVENT_SCHEMAS,
|
|
957
|
+
requestReplies: requestReplies(),
|
|
958
|
+
views: { USER_PROFILE_NAMES },
|
|
959
|
+
directory: authDirectory(kept),
|
|
960
|
+
};
|
|
961
|
+
}
|