@crombolo/server 0.65.1 → 0.66.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/package.json +15 -14
- package/src/adapters/blueprints.ts +19 -5
- package/src/adapters/elements.ts +49 -36
- package/src/adapters/members.ts +37 -3
- package/src/adapters/users.ts +18 -0
- package/src/approvals.ts +15 -0
- package/src/atomic-write.ts +2 -2
- package/src/background-jobs.ts +170 -0
- package/src/cli-tokens-api.ts +152 -0
- package/src/config.ts +35 -1
- package/src/content-events.ts +22 -0
- package/src/content-operations.ts +26 -1
- package/src/extension-activity.ts +121 -0
- package/src/index.ts +14 -0
- package/src/media-access.ts +30 -125
- package/src/media-library.ts +953 -0
- package/src/member-admin.ts +761 -0
- package/src/node-operations.ts +19 -2
- package/src/ports.ts +2 -0
- package/src/principal.ts +35 -0
- package/src/remote-background-jobs.ts +99 -0
- package/src/remote-credentials.ts +114 -6
- package/src/remote-extension-activity.ts +66 -0
- package/src/remote-media-library.ts +297 -0
- package/src/remote-media.ts +2 -2
- package/src/remote-members.ts +271 -0
- package/src/remote-undo.ts +234 -0
- package/src/remote-users.ts +229 -0
- package/src/remote.ts +141 -3
- package/src/seed/values.ts +82 -4
- package/src/seo.ts +81 -61
- package/src/server.ts +97 -94
- package/src/settings.ts +86 -0
- package/src/undo.ts +358 -0
- package/src/user-admin.ts +581 -0
|
@@ -0,0 +1,761 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Members, their groups and who may see a page (story 354), the same for the
|
|
3
|
+
* command line on the site's own database and for the remote protocol. Members
|
|
4
|
+
* are saved through the member port the Members section uses, and a page's
|
|
5
|
+
* public access through the content operations, so the rules are the back
|
|
6
|
+
* office's. A change is fields, not flags: story 155's import builds on it.
|
|
7
|
+
*/
|
|
8
|
+
import { resolveDeliveryApiSettings } from '@crombolo/api-delivery'
|
|
9
|
+
import {
|
|
10
|
+
type MemberGroupPort,
|
|
11
|
+
type MemberPort,
|
|
12
|
+
type MemberResponse,
|
|
13
|
+
type Principal,
|
|
14
|
+
type PublicAccessRuleBreak,
|
|
15
|
+
publicAccessRuleBreak,
|
|
16
|
+
type SaveMember,
|
|
17
|
+
} from '@crombolo/api-management/domain'
|
|
18
|
+
import { generatePassword } from '@crombolo/auth'
|
|
19
|
+
import type { Actor, DocumentOperations } from '@crombolo/content'
|
|
20
|
+
import {
|
|
21
|
+
type ContentTypeAggregate,
|
|
22
|
+
type DocumentValue,
|
|
23
|
+
hasAccessToSensitiveData,
|
|
24
|
+
normaliseUuid,
|
|
25
|
+
ObjectTypes,
|
|
26
|
+
} from '@crombolo/core'
|
|
27
|
+
import {
|
|
28
|
+
ContentTypeRepository,
|
|
29
|
+
currentSchemaState,
|
|
30
|
+
type Db,
|
|
31
|
+
looksLikeKey,
|
|
32
|
+
MemberRepository,
|
|
33
|
+
NodeRepository,
|
|
34
|
+
PublicAccessRepository,
|
|
35
|
+
} from '@crombolo/data'
|
|
36
|
+
import { createMemberGroupPort } from './adapters/member-groups.ts'
|
|
37
|
+
import { createMemberPort, type MemberPortOptions } from './adapters/members.ts'
|
|
38
|
+
import type { CromboloConfig } from './config.ts'
|
|
39
|
+
import {
|
|
40
|
+
type SchemaLookup,
|
|
41
|
+
schemaLookup,
|
|
42
|
+
siteValueRefs,
|
|
43
|
+
typedValue,
|
|
44
|
+
valueWriter,
|
|
45
|
+
} from './seed/index.ts'
|
|
46
|
+
import { namedPath, pageReader, type ShownValue } from './undo.ts'
|
|
47
|
+
|
|
48
|
+
export type MemberAdminKind = 'not_found' | 'refused' | 'usage' | 'conflict' | 'invalid'
|
|
49
|
+
|
|
50
|
+
/** Why a member, group or page access change was refused, in words for a person. */
|
|
51
|
+
export class MemberAdminError extends Error {
|
|
52
|
+
constructor(
|
|
53
|
+
readonly kind: MemberAdminKind,
|
|
54
|
+
message: string,
|
|
55
|
+
readonly details: string[] = [],
|
|
56
|
+
) {
|
|
57
|
+
super(message)
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface MemberPorts {
|
|
62
|
+
db: Db
|
|
63
|
+
members: MemberPort
|
|
64
|
+
groups: MemberGroupPort
|
|
65
|
+
lookup: SchemaLookup
|
|
66
|
+
writer: ReturnType<typeof valueWriter>
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* The member ports over a site's database, as its server makes them. A running
|
|
71
|
+
* server passes its own schema state, so a node behind the database refuses the
|
|
72
|
+
* write as its own ports do; the command line reads the database's.
|
|
73
|
+
*/
|
|
74
|
+
export async function siteMemberPorts(
|
|
75
|
+
db: Db,
|
|
76
|
+
config: CromboloConfig,
|
|
77
|
+
nodeState?: MemberPortOptions['nodeState'],
|
|
78
|
+
): Promise<MemberPorts> {
|
|
79
|
+
const lookup = schemaLookup(db)
|
|
80
|
+
const state = nodeState ?? (await currentSchemaState(db))
|
|
81
|
+
return {
|
|
82
|
+
db,
|
|
83
|
+
members: createMemberPort(db, {
|
|
84
|
+
nodeState: nodeState ?? { version: state.version, revision: state.revision },
|
|
85
|
+
nodeId: config.nodeId,
|
|
86
|
+
apiMemberUserNames: resolveDeliveryApiSettings(
|
|
87
|
+
config.deliveryApi,
|
|
88
|
+
).memberAuthorization.clientCredentialsFlow.associatedMembers.map((m) => m.userName),
|
|
89
|
+
}),
|
|
90
|
+
groups: createMemberGroupPort(db),
|
|
91
|
+
lookup,
|
|
92
|
+
writer: valueWriter(lookup, siteValueRefs(db)),
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** How a member signs in: a password, only through an identity provider, or as a Delivery API client. */
|
|
97
|
+
export type SignsIn = 'password' | 'provider' | 'api'
|
|
98
|
+
|
|
99
|
+
export interface MemberSummary {
|
|
100
|
+
key: string
|
|
101
|
+
login: string
|
|
102
|
+
email: string
|
|
103
|
+
name: string
|
|
104
|
+
type: string
|
|
105
|
+
groups: string[]
|
|
106
|
+
approved: boolean
|
|
107
|
+
locked: boolean
|
|
108
|
+
signsIn: SignsIn
|
|
109
|
+
lastSignIn: string | null
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export interface MemberDetail extends MemberSummary {
|
|
113
|
+
twoFactor: boolean
|
|
114
|
+
failedSignIns: number
|
|
115
|
+
lastLockout: string | null
|
|
116
|
+
lastPasswordChange: string | null
|
|
117
|
+
created: string | null
|
|
118
|
+
updated: string | null
|
|
119
|
+
values: ShownValue[]
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const SIGNS_IN: Record<string, SignsIn> = {
|
|
123
|
+
Api: 'api',
|
|
124
|
+
ExternalOnly: 'provider',
|
|
125
|
+
Default: 'password',
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Group names and member type aliases by key, read once for a list. */
|
|
129
|
+
async function namesOf(ports: MemberPorts) {
|
|
130
|
+
const groups = await allGroups(ports)
|
|
131
|
+
const types = await new ContentTypeRepository(ports.db, { kind: 'member' }).all()
|
|
132
|
+
return {
|
|
133
|
+
groups: new Map(groups.map((g) => [normaliseUuid(g.key), g.name])),
|
|
134
|
+
types: new Map(types.map((t) => [normaliseUuid(t.key), t.alias])),
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function summaryOf(
|
|
139
|
+
member: MemberResponse,
|
|
140
|
+
names: Awaited<ReturnType<typeof namesOf>>,
|
|
141
|
+
): MemberSummary {
|
|
142
|
+
return {
|
|
143
|
+
key: member.id,
|
|
144
|
+
login: member.username,
|
|
145
|
+
email: member.email,
|
|
146
|
+
name: member.variants[0]?.name ?? member.username,
|
|
147
|
+
type: names.types.get(normaliseUuid(member.memberType.id)) ?? member.memberType.id,
|
|
148
|
+
groups: member.groups
|
|
149
|
+
.map((key) => names.groups.get(normaliseUuid(key)))
|
|
150
|
+
.filter((name): name is string => name !== undefined)
|
|
151
|
+
.sort((a, b) => a.localeCompare(b)),
|
|
152
|
+
approved: member.isApproved,
|
|
153
|
+
locked: member.isLockedOut,
|
|
154
|
+
signsIn: SIGNS_IN[member.kind] ?? 'password',
|
|
155
|
+
lastSignIn: member.lastLoginDate ?? null,
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function detailOf(ports: MemberPorts, member: MemberResponse): Promise<MemberDetail> {
|
|
160
|
+
const type = await ports.lookup.typeByKey('member', member.memberType.id)
|
|
161
|
+
const editors = type ? await ports.lookup.editorsOf('member', type) : new Map()
|
|
162
|
+
const reader = pageReader(ports.db, ports.lookup)
|
|
163
|
+
const values: ShownValue[] = []
|
|
164
|
+
for (const v of member.values) {
|
|
165
|
+
if (v.segment) continue
|
|
166
|
+
values.push({
|
|
167
|
+
property: v.alias,
|
|
168
|
+
culture: v.culture ?? null,
|
|
169
|
+
value: await reader.shorthand(editors.get(v.alias)?.editor ?? '', v.value),
|
|
170
|
+
})
|
|
171
|
+
}
|
|
172
|
+
const variant = member.variants[0]
|
|
173
|
+
return {
|
|
174
|
+
...summaryOf(member, await namesOf(ports)),
|
|
175
|
+
twoFactor: member.isTwoFactorEnabled,
|
|
176
|
+
failedSignIns: member.failedPasswordAttempts,
|
|
177
|
+
lastLockout: member.lastLockoutDate ?? null,
|
|
178
|
+
lastPasswordChange: member.lastPasswordChangeDate ?? null,
|
|
179
|
+
created: variant?.createDate ?? null,
|
|
180
|
+
updated: variant?.updateDate ?? null,
|
|
181
|
+
values,
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The member a key, an e-mail address or a login names, whatever the casing. */
|
|
186
|
+
export async function findMember(ports: MemberPorts, ref: string): Promise<string> {
|
|
187
|
+
const wanted = ref.trim()
|
|
188
|
+
const lower = wanted.toLowerCase()
|
|
189
|
+
const rows = await ports.db.q
|
|
190
|
+
.selectFrom('member as m')
|
|
191
|
+
.innerJoin('node as n', 'n.id', 'm.node_id')
|
|
192
|
+
.select(['n.unique_id', 'm.email', 'm.login_name'])
|
|
193
|
+
.where((eb) =>
|
|
194
|
+
eb.or([
|
|
195
|
+
...(looksLikeKey(wanted) ? [eb('n.unique_id', '=', normaliseUuid(wanted))] : []),
|
|
196
|
+
eb(eb.fn('lower', ['m.email']), '=', lower),
|
|
197
|
+
eb(eb.fn('lower', ['m.login_name']), '=', lower),
|
|
198
|
+
]),
|
|
199
|
+
)
|
|
200
|
+
.execute()
|
|
201
|
+
const found =
|
|
202
|
+
rows.find((r) => normaliseUuid(String(r.unique_id)) === lower) ??
|
|
203
|
+
rows.find((r) => String(r.email).toLowerCase() === lower) ??
|
|
204
|
+
rows[0]
|
|
205
|
+
if (!found) throw new MemberAdminError('not_found', `There is no member "${wanted}".`)
|
|
206
|
+
return normaliseUuid(String(found.unique_id))
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function stored(ports: MemberPorts, key: string, viewer: Principal) {
|
|
210
|
+
const member = await ports.members.byKey(key, viewer)
|
|
211
|
+
if (!member) throw new MemberAdminError('not_found', 'The member could not be found.')
|
|
212
|
+
return member
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** A member, with what the Members section shows of them; values as the viewer may see them. */
|
|
216
|
+
export async function showMember(
|
|
217
|
+
ports: MemberPorts,
|
|
218
|
+
viewer: Principal,
|
|
219
|
+
ref: string,
|
|
220
|
+
): Promise<MemberDetail> {
|
|
221
|
+
return detailOf(ports, await stored(ports, await findMember(ports, ref), viewer))
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export interface MemberQuery {
|
|
225
|
+
group?: string
|
|
226
|
+
type?: string
|
|
227
|
+
find?: string
|
|
228
|
+
skip?: number
|
|
229
|
+
take?: number
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Members, by login, through the Members section's filter. */
|
|
233
|
+
export async function listMembers(
|
|
234
|
+
ports: MemberPorts,
|
|
235
|
+
viewer: Principal,
|
|
236
|
+
query: MemberQuery = {},
|
|
237
|
+
): Promise<{ items: MemberSummary[]; total: number }> {
|
|
238
|
+
const type = query.type ? await memberType(ports, query.type) : undefined
|
|
239
|
+
const group = query.group ? await groupNamed(ports, query.group) : undefined
|
|
240
|
+
const page = await ports.members.filter(
|
|
241
|
+
{
|
|
242
|
+
skip: query.skip ?? 0,
|
|
243
|
+
take: query.take ?? 50,
|
|
244
|
+
memberTypeKey: type?.key ?? null,
|
|
245
|
+
memberGroupName: group?.name ?? null,
|
|
246
|
+
...(query.find ? { filter: query.find } : {}),
|
|
247
|
+
},
|
|
248
|
+
viewer,
|
|
249
|
+
)
|
|
250
|
+
const names = await namesOf(ports)
|
|
251
|
+
return { total: page.total, items: page.items.map((m) => summaryOf(m, names)) }
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async function memberType(ports: MemberPorts, alias: string): Promise<ContentTypeAggregate> {
|
|
255
|
+
const type = await ports.lookup.typeOf('member', alias)
|
|
256
|
+
if (!type) throw new MemberAdminError('not_found', `There is no member type "${alias}".`)
|
|
257
|
+
return type
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Values set and unset on a member's own, each converted by its property's editor. */
|
|
261
|
+
async function withSets(
|
|
262
|
+
ports: MemberPorts,
|
|
263
|
+
principal: Principal,
|
|
264
|
+
member: { key: string; typeKey: string },
|
|
265
|
+
values: readonly DocumentValue[],
|
|
266
|
+
sets: ReadonlyArray<readonly [string, string]>,
|
|
267
|
+
unset: readonly string[],
|
|
268
|
+
): Promise<DocumentValue[]> {
|
|
269
|
+
if (sets.length === 0 && unset.length === 0) return [...values]
|
|
270
|
+
const type = await ports.lookup.typeByKey('member', member.typeKey)
|
|
271
|
+
if (!type) throw new MemberAdminError('not_found', 'The member type could not be found.')
|
|
272
|
+
const editors = await ports.lookup.editorsOf('member', type)
|
|
273
|
+
const properties = await ports.lookup.repos.member.resolveProperties(type.key)
|
|
274
|
+
const sensitive = new Set(properties.filter((p) => p.isSensitive === true).map((p) => p.alias))
|
|
275
|
+
const mayChangeSensitive = hasAccessToSensitiveData(principal.groups ?? [])
|
|
276
|
+
const editorOf = (alias: string) => {
|
|
277
|
+
const editor = editors.get(alias)
|
|
278
|
+
if (!editor)
|
|
279
|
+
throw new MemberAdminError(
|
|
280
|
+
'refused',
|
|
281
|
+
`Nothing was changed: "${type.alias}" has no property "${alias}".`,
|
|
282
|
+
)
|
|
283
|
+
if (sensitive.has(alias) && !mayChangeSensitive)
|
|
284
|
+
throw new MemberAdminError('refused', `Only the Sensitive data group can change ${alias}.`)
|
|
285
|
+
return editor
|
|
286
|
+
}
|
|
287
|
+
const out = values.map(({ alias, culture, segment, value }) => ({
|
|
288
|
+
alias,
|
|
289
|
+
culture,
|
|
290
|
+
segment,
|
|
291
|
+
value,
|
|
292
|
+
}))
|
|
293
|
+
const at = (alias: string) =>
|
|
294
|
+
out.findIndex((v) => v.alias === alias && v.culture === null && v.segment === null)
|
|
295
|
+
for (const [alias, text] of sets) {
|
|
296
|
+
const { editor } = editorOf(alias)
|
|
297
|
+
const converted = await ports.writer.convert(
|
|
298
|
+
editor,
|
|
299
|
+
typedValue(editor, text),
|
|
300
|
+
member.key,
|
|
301
|
+
alias,
|
|
302
|
+
)
|
|
303
|
+
if (!converted.ok)
|
|
304
|
+
throw new MemberAdminError('refused', `Nothing was changed: ${alias}: ${converted.message}.`)
|
|
305
|
+
const value = { alias, culture: null, segment: null, value: converted.value }
|
|
306
|
+
const index = at(alias)
|
|
307
|
+
if (index >= 0) out[index] = value
|
|
308
|
+
else out.push(value)
|
|
309
|
+
}
|
|
310
|
+
for (const alias of unset) {
|
|
311
|
+
editorOf(alias)
|
|
312
|
+
const index = at(alias)
|
|
313
|
+
if (index >= 0) out.splice(index, 1)
|
|
314
|
+
}
|
|
315
|
+
return out
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function groupKeysOf(ports: MemberPorts, names: readonly string[]): Promise<string[]> {
|
|
319
|
+
const keys: string[] = []
|
|
320
|
+
for (const name of names) keys.push((await groupNamed(ports, name)).key)
|
|
321
|
+
return keys
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const failure = (reason: string, status = 400): MemberAdminError =>
|
|
325
|
+
new MemberAdminError(
|
|
326
|
+
status === 404 ? 'not_found' : /already uses/.test(reason) ? 'conflict' : 'refused',
|
|
327
|
+
`Nothing was changed: ${reason}`,
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
async function checked(ports: MemberPorts, input: SaveMember): Promise<void> {
|
|
331
|
+
const errors = await ports.members.validate(input)
|
|
332
|
+
if (errors.length > 0)
|
|
333
|
+
throw new MemberAdminError(
|
|
334
|
+
'invalid',
|
|
335
|
+
'Nothing was changed: the member is not valid.',
|
|
336
|
+
errors.map((e) => `${e.alias}: ${e.messages.join('; ')}`),
|
|
337
|
+
)
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const looksLikeEmail = (email: string) => /^[^\s@]+@[^\s@]+$/.test(email)
|
|
341
|
+
|
|
342
|
+
export interface NewMember {
|
|
343
|
+
email: string
|
|
344
|
+
/** Their username; the e-mail address when left out. */
|
|
345
|
+
login?: string
|
|
346
|
+
name?: string
|
|
347
|
+
type: string
|
|
348
|
+
groups?: readonly string[]
|
|
349
|
+
sets?: ReadonlyArray<readonly [string, string]>
|
|
350
|
+
/** None: they sign in only through an identity provider. */
|
|
351
|
+
password?: string
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** A new member, approved, as the Members section's Create makes one. */
|
|
355
|
+
export async function newMember(
|
|
356
|
+
ports: MemberPorts,
|
|
357
|
+
principal: Principal,
|
|
358
|
+
input: NewMember,
|
|
359
|
+
): Promise<MemberDetail> {
|
|
360
|
+
const email = input.email.trim()
|
|
361
|
+
if (!looksLikeEmail(email))
|
|
362
|
+
throw new MemberAdminError('usage', `"${input.email}" is not an e-mail address.`)
|
|
363
|
+
const login = input.login?.trim() || email
|
|
364
|
+
const type = await memberType(ports, input.type)
|
|
365
|
+
const key = crypto.randomUUID()
|
|
366
|
+
const save: SaveMember = {
|
|
367
|
+
key,
|
|
368
|
+
memberTypeKey: type.key,
|
|
369
|
+
email,
|
|
370
|
+
username: login,
|
|
371
|
+
password: input.password || null,
|
|
372
|
+
isApproved: true,
|
|
373
|
+
isLockedOut: false,
|
|
374
|
+
isTwoFactorEnabled: false,
|
|
375
|
+
groupKeys: await groupKeysOf(ports, input.groups ?? []),
|
|
376
|
+
values: await withSets(ports, principal, { key, typeKey: type.key }, [], input.sets ?? [], []),
|
|
377
|
+
variants: [{ culture: null, segment: null, name: input.name?.trim() || login }],
|
|
378
|
+
}
|
|
379
|
+
await checked(ports, save)
|
|
380
|
+
const created = await ports.members.create(save, principal)
|
|
381
|
+
if (!created.ok) throw failure(created.reason, created.status)
|
|
382
|
+
return detailOf(ports, await stored(ports, created.key, principal))
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
export interface MemberChange {
|
|
386
|
+
email?: string
|
|
387
|
+
login?: string
|
|
388
|
+
name?: string
|
|
389
|
+
sets?: ReadonlyArray<readonly [string, string]>
|
|
390
|
+
unset?: readonly string[]
|
|
391
|
+
addGroups?: readonly string[]
|
|
392
|
+
removeGroups?: readonly string[]
|
|
393
|
+
approved?: boolean
|
|
394
|
+
locked?: boolean
|
|
395
|
+
/** A new password, given. */
|
|
396
|
+
password?: string
|
|
397
|
+
/** A new password, made here and answered once. */
|
|
398
|
+
generatePassword?: boolean
|
|
399
|
+
/** False removes their second factor. */
|
|
400
|
+
twoFactor?: false
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export interface MemberChanged {
|
|
404
|
+
member: MemberDetail
|
|
405
|
+
changed: boolean
|
|
406
|
+
/** The password made for them, when one was. */
|
|
407
|
+
password: string | null
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* A member changed, the rest of them as stored: each field not named is kept,
|
|
412
|
+
* and a change to nothing saves nothing.
|
|
413
|
+
*/
|
|
414
|
+
export async function changeMember(
|
|
415
|
+
ports: MemberPorts,
|
|
416
|
+
principal: Principal,
|
|
417
|
+
ref: string,
|
|
418
|
+
change: MemberChange,
|
|
419
|
+
): Promise<MemberChanged> {
|
|
420
|
+
const key = await findMember(ports, ref)
|
|
421
|
+
const before = await stored(ports, key, principal)
|
|
422
|
+
if (change.generatePassword && before.kind === 'ExternalOnly')
|
|
423
|
+
throw new MemberAdminError(
|
|
424
|
+
'refused',
|
|
425
|
+
`${before.username} signs in only through an identity provider, so has no password to reset.`,
|
|
426
|
+
)
|
|
427
|
+
const email = change.email?.trim() ?? before.email
|
|
428
|
+
if (!looksLikeEmail(email))
|
|
429
|
+
throw new MemberAdminError('usage', `"${change.email}" is not an e-mail address.`)
|
|
430
|
+
const login = change.login?.trim() || before.username
|
|
431
|
+
const name = change.name?.trim() || before.variants[0]?.name || login
|
|
432
|
+
const removing = new Set(await groupKeysOf(ports, change.removeGroups ?? []))
|
|
433
|
+
const groupKeys = [
|
|
434
|
+
...new Set([
|
|
435
|
+
...before.groups.map(normaliseUuid).filter((k) => !removing.has(k)),
|
|
436
|
+
...(await groupKeysOf(ports, change.addGroups ?? [])),
|
|
437
|
+
]),
|
|
438
|
+
]
|
|
439
|
+
const password = change.generatePassword ? generatePassword() : change.password || null
|
|
440
|
+
const approved = change.approved ?? before.isApproved
|
|
441
|
+
const locked = change.locked ?? before.isLockedOut
|
|
442
|
+
const values = await withSets(
|
|
443
|
+
ports,
|
|
444
|
+
principal,
|
|
445
|
+
{ key, typeKey: before.memberType.id },
|
|
446
|
+
before.values.map(({ alias, culture, segment, value }) => ({
|
|
447
|
+
alias,
|
|
448
|
+
culture: culture ?? null,
|
|
449
|
+
segment: segment ?? null,
|
|
450
|
+
value,
|
|
451
|
+
})),
|
|
452
|
+
change.sets ?? [],
|
|
453
|
+
change.unset ?? [],
|
|
454
|
+
)
|
|
455
|
+
const sameGroups =
|
|
456
|
+
groupKeys.length === before.groups.length &&
|
|
457
|
+
before.groups.every((k) => groupKeys.includes(normaliseUuid(k)))
|
|
458
|
+
const changed =
|
|
459
|
+
email !== before.email ||
|
|
460
|
+
login !== before.username ||
|
|
461
|
+
name !== (before.variants[0]?.name ?? login) ||
|
|
462
|
+
!sameGroups ||
|
|
463
|
+
approved !== before.isApproved ||
|
|
464
|
+
locked !== before.isLockedOut ||
|
|
465
|
+
(change.locked === false && before.failedPasswordAttempts > 0) ||
|
|
466
|
+
password !== null ||
|
|
467
|
+
(change.twoFactor === false && before.isTwoFactorEnabled) ||
|
|
468
|
+
(change.sets?.length ?? 0) > 0 ||
|
|
469
|
+
(change.unset ?? []).some((alias) => before.values.some((v) => v.alias === alias))
|
|
470
|
+
if (!changed) return { member: await detailOf(ports, before), changed: false, password: null }
|
|
471
|
+
const save: SaveMember = {
|
|
472
|
+
key,
|
|
473
|
+
memberTypeKey: before.memberType.id,
|
|
474
|
+
email,
|
|
475
|
+
username: login,
|
|
476
|
+
password,
|
|
477
|
+
isApproved: approved,
|
|
478
|
+
isLockedOut: locked,
|
|
479
|
+
isTwoFactorEnabled: change.twoFactor !== false,
|
|
480
|
+
groupKeys,
|
|
481
|
+
values,
|
|
482
|
+
variants: [{ culture: null, segment: null, name }],
|
|
483
|
+
}
|
|
484
|
+
await checked(ports, save)
|
|
485
|
+
const updated = await ports.members.update(key, save, principal)
|
|
486
|
+
if (!updated.ok) throw failure(updated.reason, updated.status)
|
|
487
|
+
return {
|
|
488
|
+
member: await detailOf(ports, await stored(ports, key, principal)),
|
|
489
|
+
changed: true,
|
|
490
|
+
password: change.generatePassword ? password : null,
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** A member removed, with the groups they were in. */
|
|
495
|
+
export async function removeMember(
|
|
496
|
+
ports: MemberPorts,
|
|
497
|
+
viewer: Principal,
|
|
498
|
+
ref: string,
|
|
499
|
+
): Promise<MemberDetail> {
|
|
500
|
+
const key = await findMember(ports, ref)
|
|
501
|
+
const member = await detailOf(ports, await stored(ports, key, viewer))
|
|
502
|
+
if (!(await ports.members.remove(key)))
|
|
503
|
+
throw new MemberAdminError('not_found', 'The member could not be found.')
|
|
504
|
+
return member
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** What a change did, as the audit log names it. */
|
|
508
|
+
export function memberChangeAction(change: MemberChange): string {
|
|
509
|
+
if (change.generatePassword || change.password) return 'ResetPassword'
|
|
510
|
+
if (change.twoFactor === false) return 'ResetTwoFactor'
|
|
511
|
+
if (change.locked === true) return 'Lock'
|
|
512
|
+
if (change.locked === false) return 'Unlock'
|
|
513
|
+
if (change.approved === true) return 'Approve'
|
|
514
|
+
if (change.addGroups?.length && !change.removeGroups?.length) return 'JoinGroup'
|
|
515
|
+
if (change.removeGroups?.length && !change.addGroups?.length) return 'LeaveGroup'
|
|
516
|
+
return 'Save'
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
export interface Place {
|
|
520
|
+
key: string
|
|
521
|
+
path: string
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
export interface MemberGroupInfo {
|
|
525
|
+
key: string
|
|
526
|
+
name: string
|
|
527
|
+
members: number
|
|
528
|
+
/** The pages whose access names the group. */
|
|
529
|
+
pages: Place[]
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
async function placeOf(db: Db, key: string): Promise<Place> {
|
|
533
|
+
return { key, path: `/${(await namedPath(db, key, 'content')) ?? key}` }
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
async function allGroups(ports: MemberPorts): Promise<Array<{ key: string; name: string }>> {
|
|
537
|
+
const page = await ports.groups.list({ skip: 0, take: Number.MAX_SAFE_INTEGER })
|
|
538
|
+
return page.items.map((g) => ({ key: normaliseUuid(g.id), name: g.name }))
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** A member group by its name, whatever the casing. */
|
|
542
|
+
export async function groupNamed(
|
|
543
|
+
ports: MemberPorts,
|
|
544
|
+
name: string,
|
|
545
|
+
): Promise<{ key: string; name: string }> {
|
|
546
|
+
const wanted = name.trim().toLowerCase()
|
|
547
|
+
const group = (await allGroups(ports)).find((g) => g.name.toLowerCase() === wanted)
|
|
548
|
+
if (!group) throw new MemberAdminError('not_found', `There is no member group "${name.trim()}".`)
|
|
549
|
+
return group
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** The pages whose access names a group, which a removed group drops out of. */
|
|
553
|
+
export async function pagesNaming(db: Db, group: string): Promise<Place[]> {
|
|
554
|
+
const rules = await new PublicAccessRepository(db).allRules()
|
|
555
|
+
const nodes = new NodeRepository(db)
|
|
556
|
+
const pages: Place[] = []
|
|
557
|
+
for (const rule of rules.filter((r) => r.memberGroupNames.includes(group))) {
|
|
558
|
+
const node = await nodes.byId(rule.nodeId)
|
|
559
|
+
if (node) pages.push(await placeOf(db, node.key))
|
|
560
|
+
}
|
|
561
|
+
return pages.sort((a, b) => a.path.localeCompare(b.path))
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** Every member group, with how many members it has and the pages that name it. */
|
|
565
|
+
export async function groupsOf(ports: MemberPorts): Promise<MemberGroupInfo[]> {
|
|
566
|
+
const counts = await ports.db.q
|
|
567
|
+
.selectFrom('member_group_member as mg')
|
|
568
|
+
.innerJoin('node as g', 'g.id', 'mg.member_group_id')
|
|
569
|
+
.select(['g.unique_id', (eb) => eb.fn.countAll<number>().as('members')])
|
|
570
|
+
.groupBy('g.unique_id')
|
|
571
|
+
.execute()
|
|
572
|
+
const byKey = new Map(counts.map((c) => [normaliseUuid(String(c.unique_id)), Number(c.members)]))
|
|
573
|
+
const out: MemberGroupInfo[] = []
|
|
574
|
+
for (const group of await allGroups(ports))
|
|
575
|
+
out.push({
|
|
576
|
+
...group,
|
|
577
|
+
members: byKey.get(group.key) ?? 0,
|
|
578
|
+
pages: await pagesNaming(ports.db, group.name),
|
|
579
|
+
})
|
|
580
|
+
return out.sort((a, b) => a.name.localeCompare(b.name))
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
export async function newGroup(
|
|
584
|
+
ports: MemberPorts,
|
|
585
|
+
name: string,
|
|
586
|
+
): Promise<{ key: string; name: string }> {
|
|
587
|
+
const wanted = name.trim()
|
|
588
|
+
if (!wanted) throw new MemberAdminError('usage', 'A member group needs a name.')
|
|
589
|
+
const taken = (await allGroups(ports)).some((g) => g.name.toLowerCase() === wanted.toLowerCase())
|
|
590
|
+
const made = taken ? undefined : await ports.groups.create({ name: wanted })
|
|
591
|
+
if (!made || made.status === 'duplicate-name' || !made.key)
|
|
592
|
+
throw new MemberAdminError('conflict', `There is already a member group called "${wanted}".`)
|
|
593
|
+
return { key: normaliseUuid(made.key), name: wanted }
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* A group removed, its members left out of it. A page whose access names it
|
|
598
|
+
* would lose it, so that needs `confirmed`.
|
|
599
|
+
*/
|
|
600
|
+
export async function removeGroup(
|
|
601
|
+
ports: MemberPorts,
|
|
602
|
+
name: string,
|
|
603
|
+
confirmed: boolean,
|
|
604
|
+
): Promise<MemberGroupInfo> {
|
|
605
|
+
const group = (await groupsOf(ports)).find(
|
|
606
|
+
(g) => g.name.toLowerCase() === name.trim().toLowerCase(),
|
|
607
|
+
)
|
|
608
|
+
if (!group) throw new MemberAdminError('not_found', `There is no member group "${name.trim()}".`)
|
|
609
|
+
if (group.pages.length > 0 && !confirmed)
|
|
610
|
+
throw new MemberAdminError(
|
|
611
|
+
'conflict',
|
|
612
|
+
`Who may see ${group.pages.length === 1 ? 'a page' : `${group.pages.length} pages`} names ${group.name}, and would no longer.`,
|
|
613
|
+
group.pages.map((p) => p.path),
|
|
614
|
+
)
|
|
615
|
+
await ports.groups.remove(group.key)
|
|
616
|
+
return group
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
export interface PageAccess {
|
|
620
|
+
page: Place
|
|
621
|
+
/** Whose rule applies: this page's own, an ancestor's, or none, when it is open to everyone. */
|
|
622
|
+
rule: 'own' | 'ancestor' | 'none'
|
|
623
|
+
protectedBy: Place | null
|
|
624
|
+
groups: string[]
|
|
625
|
+
members: string[]
|
|
626
|
+
loginPage: Place | null
|
|
627
|
+
noAccessPage: Place | null
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
async function pageKeyOf(db: Db, key: string): Promise<string> {
|
|
631
|
+
const node = await new NodeRepository(db).byKey(normaliseUuid(key))
|
|
632
|
+
if (!node || node.objectType !== ObjectTypes.Document || node.trashed)
|
|
633
|
+
throw new MemberAdminError('not_found', 'There is no such page.')
|
|
634
|
+
return node.key
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** Who may see a page, by its own rule or the nearest ancestor's. */
|
|
638
|
+
export async function pageAccess(db: Db, key: string): Promise<PageAccess> {
|
|
639
|
+
const page = await pageKeyOf(db, key)
|
|
640
|
+
const entry = await new PublicAccessRepository(db).entryFor(page)
|
|
641
|
+
const place = await placeOf(db, page)
|
|
642
|
+
// A rule names groups and members by name, so a removed or renamed one drops out, as in the back office.
|
|
643
|
+
const groups = new Set(
|
|
644
|
+
(
|
|
645
|
+
await new NodeRepository(db).roots(ObjectTypes.MemberGroup, 0, Number.MAX_SAFE_INTEGER)
|
|
646
|
+
).items.map((g) => g.text ?? ''),
|
|
647
|
+
)
|
|
648
|
+
const logins: string[] = []
|
|
649
|
+
const members = new MemberRepository(db)
|
|
650
|
+
for (const login of entry?.memberUserNames ?? [])
|
|
651
|
+
if (await members.byUsername(login)) logins.push(login)
|
|
652
|
+
if (!entry)
|
|
653
|
+
return {
|
|
654
|
+
page: place,
|
|
655
|
+
rule: 'none',
|
|
656
|
+
protectedBy: null,
|
|
657
|
+
groups: [],
|
|
658
|
+
members: [],
|
|
659
|
+
loginPage: null,
|
|
660
|
+
noAccessPage: null,
|
|
661
|
+
}
|
|
662
|
+
return {
|
|
663
|
+
page: place,
|
|
664
|
+
rule: entry.nodeKey === page ? 'own' : 'ancestor',
|
|
665
|
+
protectedBy: await placeOf(db, entry.nodeKey),
|
|
666
|
+
groups: entry.memberGroupNames.filter((name) => groups.has(name)),
|
|
667
|
+
members: logins,
|
|
668
|
+
loginPage: await placeOf(db, entry.loginNodeKey),
|
|
669
|
+
noAccessPage: await placeOf(db, entry.errorNodeKey),
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
export interface AccessInput {
|
|
674
|
+
groups?: readonly string[]
|
|
675
|
+
members?: readonly string[]
|
|
676
|
+
loginPage?: string
|
|
677
|
+
noAccessPage?: string
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
const RULE_BREAKS: Record<PublicAccessRuleBreak, [MemberAdminKind, string]> = {
|
|
681
|
+
'no-login-page': ['usage', 'A page for members needs a sign-in page.'],
|
|
682
|
+
'no-error-page': ['usage', 'A page for members needs a no-access page.'],
|
|
683
|
+
'no-one': ['usage', 'Name the member groups, or the members, the page is for.'],
|
|
684
|
+
ambiguous: ['usage', 'A page is for member groups or for members, not both.'],
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* A page made for some member groups or members. A page that has its own rule
|
|
689
|
+
* keeps the sign-in or no-access page a change leaves out.
|
|
690
|
+
*/
|
|
691
|
+
export async function setPageAccess(
|
|
692
|
+
ports: MemberPorts,
|
|
693
|
+
operations: DocumentOperations,
|
|
694
|
+
actor: Actor,
|
|
695
|
+
key: string,
|
|
696
|
+
input: AccessInput,
|
|
697
|
+
): Promise<PageAccess> {
|
|
698
|
+
const page = await pageKeyOf(ports.db, key)
|
|
699
|
+
const own = await new PublicAccessRepository(ports.db).byNodeKey(page)
|
|
700
|
+
const groups: string[] = []
|
|
701
|
+
for (const name of input.groups ?? []) groups.push((await groupNamed(ports, name)).name)
|
|
702
|
+
const members: string[] = []
|
|
703
|
+
for (const ref of input.members ?? []) {
|
|
704
|
+
const member = await new MemberRepository(ports.db).byKey(await findMember(ports, ref))
|
|
705
|
+
if (member) members.push(member.username)
|
|
706
|
+
}
|
|
707
|
+
const login = input.loginPage ? await pageKeyOf(ports.db, input.loginPage) : own?.loginNodeKey
|
|
708
|
+
const error = input.noAccessPage
|
|
709
|
+
? await pageKeyOf(ports.db, input.noAccessPage)
|
|
710
|
+
: own?.errorNodeKey
|
|
711
|
+
const broken = publicAccessRuleBreak({
|
|
712
|
+
loginDocumentKey: login,
|
|
713
|
+
errorDocumentKey: error,
|
|
714
|
+
memberGroupNames: groups,
|
|
715
|
+
memberUserNames: members,
|
|
716
|
+
})
|
|
717
|
+
if (broken) {
|
|
718
|
+
const [kind, message] = RULE_BREAKS[broken]
|
|
719
|
+
throw new MemberAdminError(kind, message)
|
|
720
|
+
}
|
|
721
|
+
const status = await operations.setPublicAccess(
|
|
722
|
+
actor,
|
|
723
|
+
page,
|
|
724
|
+
{
|
|
725
|
+
loginDocumentKey: login as string,
|
|
726
|
+
errorDocumentKey: error as string,
|
|
727
|
+
memberGroupNames: groups,
|
|
728
|
+
memberUserNames: members,
|
|
729
|
+
},
|
|
730
|
+
own ? 'set' : 'added',
|
|
731
|
+
)
|
|
732
|
+
accessStatus(status, page)
|
|
733
|
+
return pageAccess(ports.db, page)
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
function accessStatus(status: string, page: string): void {
|
|
737
|
+
if (status === 'ok' || status === 'entry-not-found') return
|
|
738
|
+
if (status === 'forbidden')
|
|
739
|
+
throw new MemberAdminError('refused', 'You may not change who may see this page.')
|
|
740
|
+
throw new MemberAdminError(
|
|
741
|
+
'not_found',
|
|
742
|
+
status === 'login-node-not-found'
|
|
743
|
+
? 'There is no such sign-in page.'
|
|
744
|
+
: status === 'error-node-not-found'
|
|
745
|
+
? 'There is no such no-access page.'
|
|
746
|
+
: `There is no page ${page}.`,
|
|
747
|
+
)
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** A page's own rule removed, so it is open as its ancestors are. */
|
|
751
|
+
export async function clearPageAccess(
|
|
752
|
+
db: Db,
|
|
753
|
+
operations: DocumentOperations,
|
|
754
|
+
actor: Actor,
|
|
755
|
+
key: string,
|
|
756
|
+
): Promise<{ access: PageAccess; changed: boolean }> {
|
|
757
|
+
const page = await pageKeyOf(db, key)
|
|
758
|
+
const status = await operations.removePublicAccess(actor, page)
|
|
759
|
+
accessStatus(status, page)
|
|
760
|
+
return { access: await pageAccess(db, page), changed: status === 'ok' }
|
|
761
|
+
}
|