@crombolo/server 0.65.1 → 0.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/package.json +15 -14
- package/src/adapters/blueprints.ts +19 -5
- package/src/adapters/elements.ts +49 -36
- package/src/adapters/members.ts +53 -5
- package/src/adapters/users.ts +18 -0
- package/src/approvals.ts +21 -0
- package/src/atomic-write.ts +2 -2
- package/src/background-jobs.ts +170 -0
- package/src/cli-tokens-api.ts +158 -0
- package/src/config.ts +52 -1
- package/src/content-events.ts +22 -0
- package/src/content-operations.ts +26 -1
- package/src/extension-activity.ts +121 -0
- package/src/external-sign-in.ts +8 -2
- package/src/identity-providers.ts +44 -1
- 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 +36 -0
- package/src/remote-background-jobs.ts +99 -0
- package/src/remote-ci.ts +34 -26
- 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-people.ts +269 -0
- package/src/remote-undo.ts +234 -0
- package/src/remote-users.ts +229 -0
- package/src/remote.ts +174 -10
- package/src/seed/values.ts +82 -4
- package/src/seo.ts +81 -61
- package/src/server.ts +191 -94
- package/src/settings.ts +93 -0
- package/src/undo.ts +358 -0
- package/src/user-admin.ts +581 -0
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Back-office users, their sign-ins and where a group starts (story 356), the
|
|
3
|
+
* same for the command line on the site's own database and for the remote
|
|
4
|
+
* protocol. Each change goes through the user ports the Users section uses, so
|
|
5
|
+
* its rules — who may act on an administrator, which groups a person may hand
|
|
6
|
+
* out, that the site keeps an administrator — are the back office's.
|
|
7
|
+
*/
|
|
8
|
+
import type {
|
|
9
|
+
Principal,
|
|
10
|
+
UserGroupInput,
|
|
11
|
+
UserGroupPort,
|
|
12
|
+
UserGroupStatus,
|
|
13
|
+
UserPort,
|
|
14
|
+
UserStatus,
|
|
15
|
+
} from '@crombolo/api-management/domain'
|
|
16
|
+
import { AuthStore } from '@crombolo/auth'
|
|
17
|
+
import { normaliseUuid, ObjectTypes } from '@crombolo/core'
|
|
18
|
+
import {
|
|
19
|
+
type Db,
|
|
20
|
+
DbDate,
|
|
21
|
+
describeRefFailure,
|
|
22
|
+
NodeRepository,
|
|
23
|
+
resolveNodeRef,
|
|
24
|
+
type UserGroupRecord,
|
|
25
|
+
UserGroupRepository,
|
|
26
|
+
type UserRecord,
|
|
27
|
+
UserRepository,
|
|
28
|
+
userState,
|
|
29
|
+
} from '@crombolo/data'
|
|
30
|
+
|
|
31
|
+
export type UserAdminKind = 'not_found' | 'refused' | 'usage' | 'conflict'
|
|
32
|
+
|
|
33
|
+
/** Why a change to a user, a sign-in or a group was refused, in words for a person. */
|
|
34
|
+
export class UserAdminError extends Error {
|
|
35
|
+
constructor(
|
|
36
|
+
readonly kind: UserAdminKind,
|
|
37
|
+
message: string,
|
|
38
|
+
readonly hint?: string,
|
|
39
|
+
) {
|
|
40
|
+
super(message)
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface UserPorts {
|
|
45
|
+
db: Db
|
|
46
|
+
users: UserPort
|
|
47
|
+
groups: UserGroupPort
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface UserSummary {
|
|
51
|
+
key: string
|
|
52
|
+
name: string
|
|
53
|
+
email: string
|
|
54
|
+
userName: string
|
|
55
|
+
state: string
|
|
56
|
+
/** Their groups, by alias. */
|
|
57
|
+
groups: string[]
|
|
58
|
+
uiLanguage: string | null
|
|
59
|
+
lastSignIn: string | null
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const REFUSALS: Partial<Record<UserStatus | UserGroupStatus, [UserAdminKind, string]>> = {
|
|
63
|
+
UserNotFound: ['not_found', 'There is no such user.'],
|
|
64
|
+
NotFound: ['not_found', 'There is no such user group.'],
|
|
65
|
+
MissingUserGroup: ['not_found', 'There is no group with that alias.'],
|
|
66
|
+
DuplicateUserName: ['conflict', 'Another user has that username.'],
|
|
67
|
+
DuplicateEmail: ['conflict', 'Another user has that e-mail address.'],
|
|
68
|
+
InvalidEmail: ['usage', 'That is not an e-mail address.'],
|
|
69
|
+
InvalidUserName: ['usage', 'A user needs a username.'],
|
|
70
|
+
UserNameIsNotEmail: ['usage', "This site's usernames are e-mail addresses."],
|
|
71
|
+
InvalidPassword: ['usage', "That password does not meet this site's password rules."],
|
|
72
|
+
NoUserGroup: ['usage', 'A user needs at least one group.'],
|
|
73
|
+
InvalidIsoCode: ['usage', 'That is not a language code, such as en-US.'],
|
|
74
|
+
CannotDisableInvitedUser: [
|
|
75
|
+
'refused',
|
|
76
|
+
'An invited user cannot be disabled; delete the invitation instead.',
|
|
77
|
+
],
|
|
78
|
+
CannotInvite: ['refused', 'The invitation could not be made.'],
|
|
79
|
+
SelfOldPasswordRequired: [
|
|
80
|
+
'refused',
|
|
81
|
+
'Your own password is changed in your profile in the back office, which asks for the old one.',
|
|
82
|
+
],
|
|
83
|
+
Forbidden: ['refused', "Only an administrator can change an administrator's account."],
|
|
84
|
+
NotGroupOwner: ['refused', 'You can only add people to, or take them out of, groups you own.'],
|
|
85
|
+
AdminGroupCannotBeEmpty: ['refused', 'That would leave the site with no administrator.'],
|
|
86
|
+
CannotDeleteSelf: ['refused', "You can't remove yourself."],
|
|
87
|
+
CannotDisableSelf: ['refused', "You can't disable yourself."],
|
|
88
|
+
CannotDelete: ['refused', "The site's built-in administrator can't be removed."],
|
|
89
|
+
AdministratorsOnly: ['refused', 'Only an administrator can change a group.'],
|
|
90
|
+
DeclaredInFiles: [
|
|
91
|
+
'refused',
|
|
92
|
+
"That is kept in the group's file: change it in the site's files and deploy it.",
|
|
93
|
+
],
|
|
94
|
+
CannotBeOwned: [
|
|
95
|
+
'refused',
|
|
96
|
+
"The administrators group, and a group that can move sites or install code, can't have owners.",
|
|
97
|
+
],
|
|
98
|
+
OwnerNotFound: ['not_found', 'One of the owner groups could not be found.'],
|
|
99
|
+
DocumentStartNodeKeyNotFound: ['not_found', 'There is no such page to start at.'],
|
|
100
|
+
MediaStartNodeKeyNotFound: ['not_found', 'There is no such media folder to start at.'],
|
|
101
|
+
ElementStartNodeKeyNotFound: ['not_found', 'There is no such Library folder to start at.'],
|
|
102
|
+
LanguageNotFound: ['not_found', 'One of its languages could not be found.'],
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** A user or group port status other than `Success`, as a refusal. */
|
|
106
|
+
export function userRefusal(
|
|
107
|
+
status: UserStatus | UserGroupStatus,
|
|
108
|
+
who?: string,
|
|
109
|
+
): UserAdminError | undefined {
|
|
110
|
+
if (status === 'Success') return undefined
|
|
111
|
+
if (status === 'CannotDeleteUserWithLoginHistory')
|
|
112
|
+
return new UserAdminError(
|
|
113
|
+
'refused',
|
|
114
|
+
`${who ?? 'They'} ${who ? 'has' : 'have'} signed in before, so they can be disabled but not removed.`,
|
|
115
|
+
`\`crombolo users disable${who ? ` ${who}` : ''}\` stops them signing in.`,
|
|
116
|
+
)
|
|
117
|
+
const [kind, message] = REFUSALS[status] ?? ['refused', status]
|
|
118
|
+
return new UserAdminError(kind, message)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const check = (status: UserStatus | UserGroupStatus, who?: string): void => {
|
|
122
|
+
const refusal = userRefusal(status, who)
|
|
123
|
+
if (refusal) throw refusal
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const iso = (date: Date | undefined) => date?.toISOString() ?? null
|
|
127
|
+
|
|
128
|
+
async function groupAliases(db: Db): Promise<Map<string, string>> {
|
|
129
|
+
return new Map((await new UserGroupRepository(db).all()).map((g) => [g.key, g.alias]))
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function summaryOf(user: UserRecord, aliases: Map<string, string>): UserSummary {
|
|
133
|
+
return {
|
|
134
|
+
key: user.key,
|
|
135
|
+
name: user.name,
|
|
136
|
+
email: user.email,
|
|
137
|
+
userName: user.userName,
|
|
138
|
+
state: userState(user),
|
|
139
|
+
groups: user.groupKeys.map((k) => aliases.get(k) ?? k),
|
|
140
|
+
uiLanguage: user.languageIsoCode,
|
|
141
|
+
lastSignIn: iso(user.lastLoginDate),
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function userRecord(db: Db, who: string): Promise<UserRecord | undefined> {
|
|
146
|
+
const wanted = who.trim().toLowerCase()
|
|
147
|
+
// Postgres keeps the key as a uuid, which neither lower() nor a non-uuid comparison takes.
|
|
148
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(wanted)
|
|
149
|
+
const row = await db.q
|
|
150
|
+
.selectFrom('user_account')
|
|
151
|
+
.select('key')
|
|
152
|
+
.where((eb) =>
|
|
153
|
+
uuid
|
|
154
|
+
? eb('key', '=', normaliseUuid(wanted))
|
|
155
|
+
: eb.or([
|
|
156
|
+
eb(eb.fn('lower', ['email']), '=', wanted),
|
|
157
|
+
eb(eb.fn('lower', ['login']), '=', wanted),
|
|
158
|
+
]),
|
|
159
|
+
)
|
|
160
|
+
.executeTakeFirst()
|
|
161
|
+
return row ? new UserRepository(db).byKey(String(row.key)) : undefined
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** A user by key, e-mail or username, whatever the casing, as the caller may see them. */
|
|
165
|
+
export async function findUser(
|
|
166
|
+
ports: UserPorts,
|
|
167
|
+
principal: Principal,
|
|
168
|
+
who: string,
|
|
169
|
+
): Promise<UserSummary> {
|
|
170
|
+
const user = await userRecord(ports.db, who)
|
|
171
|
+
if (!user)
|
|
172
|
+
throw new UserAdminError('not_found', `No user "${who}".`, '`crombolo users list` lists them.')
|
|
173
|
+
const seen = await ports.users.get(principal, user.key)
|
|
174
|
+
check(seen.status)
|
|
175
|
+
return summaryOf(user, await groupAliases(ports.db))
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** A change to a user: only what it names. */
|
|
179
|
+
export interface UserChange {
|
|
180
|
+
name?: string
|
|
181
|
+
email?: string
|
|
182
|
+
addGroups?: string[]
|
|
183
|
+
removeGroups?: string[]
|
|
184
|
+
uiLanguage?: string
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export type UserField = 'name' | 'email' | 'userName' | 'groups' | 'uiLanguage'
|
|
188
|
+
|
|
189
|
+
export interface UserChanged {
|
|
190
|
+
user: UserSummary
|
|
191
|
+
/** What changed; none when it was so already. */
|
|
192
|
+
changed: UserField[]
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function groupKeyOf(db: Db, alias: string): Promise<string> {
|
|
196
|
+
const wanted = alias.trim().toLowerCase()
|
|
197
|
+
const group = (await new UserGroupRepository(db).all()).find(
|
|
198
|
+
(g) => g.alias.toLowerCase() === wanted,
|
|
199
|
+
)
|
|
200
|
+
if (!group)
|
|
201
|
+
throw new UserAdminError(
|
|
202
|
+
'not_found',
|
|
203
|
+
`There is no user group "${alias}".`,
|
|
204
|
+
'`crombolo users groups list` lists them.',
|
|
205
|
+
)
|
|
206
|
+
return group.key
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Changes a user through the port's whole-user update, keeping what the change
|
|
211
|
+
* does not name. A username that was their e-mail follows a new one where the
|
|
212
|
+
* site's usernames are e-mail addresses.
|
|
213
|
+
*/
|
|
214
|
+
export async function changeUser(
|
|
215
|
+
ports: UserPorts,
|
|
216
|
+
principal: Principal,
|
|
217
|
+
key: string,
|
|
218
|
+
change: UserChange,
|
|
219
|
+
): Promise<UserChanged> {
|
|
220
|
+
const users = new UserRepository(ports.db)
|
|
221
|
+
const user = await users.byKey(key)
|
|
222
|
+
if (!user) throw new UserAdminError('not_found', 'There is no such user.')
|
|
223
|
+
const seen = await ports.users.get(principal, user.key)
|
|
224
|
+
check(seen.status)
|
|
225
|
+
const adding = await Promise.all((change.addGroups ?? []).map((a) => groupKeyOf(ports.db, a)))
|
|
226
|
+
const removing = new Set(
|
|
227
|
+
await Promise.all((change.removeGroups ?? []).map((a) => groupKeyOf(ports.db, a))),
|
|
228
|
+
)
|
|
229
|
+
const groupKeys = [
|
|
230
|
+
...user.groupKeys.filter((k) => !removing.has(k)),
|
|
231
|
+
...adding.filter((k) => !user.groupKeys.includes(k) && !removing.has(k)),
|
|
232
|
+
]
|
|
233
|
+
const email = change.email ?? user.email
|
|
234
|
+
const follows =
|
|
235
|
+
ports.users.configuration().usernameIsEmail &&
|
|
236
|
+
change.email !== undefined &&
|
|
237
|
+
user.userName.toLowerCase() === user.email.toLowerCase()
|
|
238
|
+
const next = {
|
|
239
|
+
name: change.name ?? user.name,
|
|
240
|
+
email,
|
|
241
|
+
userName: follows ? email : user.userName,
|
|
242
|
+
uiLanguage: change.uiLanguage ?? user.languageIsoCode,
|
|
243
|
+
}
|
|
244
|
+
const changed: UserField[] = [
|
|
245
|
+
...(next.name !== user.name ? (['name'] as const) : []),
|
|
246
|
+
...(next.email !== user.email ? (['email'] as const) : []),
|
|
247
|
+
...(next.userName !== user.userName ? (['userName'] as const) : []),
|
|
248
|
+
...(groupKeys.length !== user.groupKeys.length ||
|
|
249
|
+
groupKeys.some((k) => !user.groupKeys.includes(k))
|
|
250
|
+
? (['groups'] as const)
|
|
251
|
+
: []),
|
|
252
|
+
...((next.uiLanguage ?? null) !== (user.languageIsoCode ?? null)
|
|
253
|
+
? (['uiLanguage'] as const)
|
|
254
|
+
: []),
|
|
255
|
+
]
|
|
256
|
+
const aliases = await groupAliases(ports.db)
|
|
257
|
+
if (changed.length === 0) return { user: summaryOf(user, aliases), changed }
|
|
258
|
+
check(
|
|
259
|
+
await ports.users.update(principal, user.key, {
|
|
260
|
+
name: next.name,
|
|
261
|
+
email: next.email,
|
|
262
|
+
userName: next.userName,
|
|
263
|
+
languageIsoCode: next.uiLanguage ?? '',
|
|
264
|
+
groupKeys,
|
|
265
|
+
documentStartNodeKeys: [],
|
|
266
|
+
hasDocumentRootAccess: false,
|
|
267
|
+
mediaStartNodeKeys: [],
|
|
268
|
+
hasMediaRootAccess: false,
|
|
269
|
+
elementStartNodeKeys: [],
|
|
270
|
+
hasElementRootAccess: false,
|
|
271
|
+
}),
|
|
272
|
+
)
|
|
273
|
+
const after = (await users.byKey(user.key)) ?? user
|
|
274
|
+
return { user: summaryOf(after, aliases), changed }
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Removes a user who has never signed in, as the Users section deletes one. */
|
|
278
|
+
export async function removeUser(
|
|
279
|
+
ports: UserPorts,
|
|
280
|
+
principal: Principal,
|
|
281
|
+
key: string,
|
|
282
|
+
): Promise<UserSummary> {
|
|
283
|
+
const user = await new UserRepository(ports.db).byKey(key)
|
|
284
|
+
if (!user) throw new UserAdminError('not_found', 'There is no such user.')
|
|
285
|
+
const summary = summaryOf(user, await groupAliases(ports.db))
|
|
286
|
+
check(await ports.users.delete(principal, [user.key]), user.email || user.userName)
|
|
287
|
+
return summary
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** An open sign-in: a browser, or a terminal by the name its device gave. */
|
|
291
|
+
export interface SignIn {
|
|
292
|
+
id: string
|
|
293
|
+
user: { key: string; name: string }
|
|
294
|
+
kind: 'browser' | 'terminal'
|
|
295
|
+
/** The name a terminal's device gave; null for a browser. */
|
|
296
|
+
device: string | null
|
|
297
|
+
signedIn: string
|
|
298
|
+
lastUsed: string | null
|
|
299
|
+
address: string | null
|
|
300
|
+
/** The sign-in this request, or this command line, is using. */
|
|
301
|
+
current: boolean
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const OTHERS = 'Only an administrator can see or end someone else’s sign-ins.'
|
|
305
|
+
|
|
306
|
+
/** Every open sign-in: one whose session is not ended and still has a refresh token to renew. */
|
|
307
|
+
async function openSignIns(
|
|
308
|
+
db: Db,
|
|
309
|
+
userId: number | undefined,
|
|
310
|
+
current: string | undefined,
|
|
311
|
+
): Promise<SignIn[]> {
|
|
312
|
+
const now = DbDate.toDb(new Date())
|
|
313
|
+
let query = db.q
|
|
314
|
+
.selectFrom('user_login_session as s')
|
|
315
|
+
.innerJoin('user_account as u', 'u.id', 's.user_id')
|
|
316
|
+
.leftJoin('device_authorization as d', (join) =>
|
|
317
|
+
join.onRef('d.session_id', '=', 's.session_id').on('d.status', '=', 'issued'),
|
|
318
|
+
)
|
|
319
|
+
.select([
|
|
320
|
+
's.session_id',
|
|
321
|
+
's.logged_in_utc',
|
|
322
|
+
's.last_validated_utc',
|
|
323
|
+
's.ip_address',
|
|
324
|
+
'u.key',
|
|
325
|
+
'u.user_name',
|
|
326
|
+
'd.id as device_id',
|
|
327
|
+
'd.client_name',
|
|
328
|
+
])
|
|
329
|
+
.select((eb) =>
|
|
330
|
+
eb
|
|
331
|
+
.selectFrom('auth_token as t')
|
|
332
|
+
.select((t) => t.fn.max('t.create_date').as('used'))
|
|
333
|
+
.whereRef('t.session_id', '=', 's.session_id')
|
|
334
|
+
.as('last_token'),
|
|
335
|
+
)
|
|
336
|
+
.where('s.logged_out_utc', 'is', null)
|
|
337
|
+
.where((eb) =>
|
|
338
|
+
eb.exists(
|
|
339
|
+
eb
|
|
340
|
+
.selectFrom('auth_token as r')
|
|
341
|
+
.select('r.id')
|
|
342
|
+
.whereRef('r.session_id', '=', 's.session_id')
|
|
343
|
+
.where('r.token_type', '=', 'refresh')
|
|
344
|
+
.where('r.revoked_at', 'is', null)
|
|
345
|
+
.where('r.expires_at', '>', now),
|
|
346
|
+
),
|
|
347
|
+
)
|
|
348
|
+
if (userId !== undefined) query = query.where('s.user_id', '=', userId)
|
|
349
|
+
const rows = await query.orderBy('s.logged_in_utc', 'desc').execute()
|
|
350
|
+
return rows.map((row) => {
|
|
351
|
+
const signedIn = DbDate.fromDb(row.logged_in_utc) ?? new Date(0)
|
|
352
|
+
const used = DbDate.fromDb(row.last_token) ?? DbDate.fromDb(row.last_validated_utc)
|
|
353
|
+
const id = String(row.session_id)
|
|
354
|
+
return {
|
|
355
|
+
id,
|
|
356
|
+
user: { key: normaliseUuid(String(row.key)), name: String(row.user_name) },
|
|
357
|
+
kind: row.device_id === null ? 'browser' : 'terminal',
|
|
358
|
+
device: row.client_name === null ? null : String(row.client_name),
|
|
359
|
+
signedIn: signedIn.toISOString(),
|
|
360
|
+
lastUsed: iso(used),
|
|
361
|
+
address: row.ip_address === null ? null : String(row.ip_address),
|
|
362
|
+
current: current !== undefined && normaliseUuid(id) === normaliseUuid(current),
|
|
363
|
+
}
|
|
364
|
+
})
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const isSelf = (principal: Principal, key: string) =>
|
|
368
|
+
normaliseUuid(principal.id) === normaliseUuid(key)
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* A user's open sign-ins: the caller's own when `user` is left out, and anyone's
|
|
372
|
+
* for an administrator. `current` is the session the caller is using.
|
|
373
|
+
*/
|
|
374
|
+
export async function signIns(
|
|
375
|
+
db: Db,
|
|
376
|
+
principal: Principal,
|
|
377
|
+
options: { user?: string; current?: string } = {},
|
|
378
|
+
): Promise<SignIn[]> {
|
|
379
|
+
const key = options.user ?? principal.id
|
|
380
|
+
if (!isSelf(principal, key) && !principal.isAdmin) throw new UserAdminError('refused', OTHERS)
|
|
381
|
+
const user = await new UserRepository(db).byKey(key)
|
|
382
|
+
if (!user) throw new UserAdminError('not_found', 'There is no such user.')
|
|
383
|
+
return openSignIns(db, user.id, options.current)
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Ends one open sign-in, named by its id or the start of it: the caller's own, or anyone's for an administrator. */
|
|
387
|
+
export async function endSignIn(
|
|
388
|
+
db: Db,
|
|
389
|
+
principal: Principal,
|
|
390
|
+
id: string,
|
|
391
|
+
options: { current?: string } = {},
|
|
392
|
+
): Promise<SignIn> {
|
|
393
|
+
const wanted = id.trim().toLowerCase()
|
|
394
|
+
if (wanted.length < 8)
|
|
395
|
+
throw new UserAdminError('usage', 'Name a sign-in by at least the eight characters listed.')
|
|
396
|
+
const open = await openSignIns(db, undefined, options.current)
|
|
397
|
+
const matches = open.filter((s) => s.id.toLowerCase().startsWith(wanted))
|
|
398
|
+
const mine = matches.filter((s) => isSelf(principal, s.user.key))
|
|
399
|
+
if (matches.length > 0 && mine.length === 0 && !principal.isAdmin)
|
|
400
|
+
throw new UserAdminError('refused', OTHERS)
|
|
401
|
+
const found = principal.isAdmin ? matches : mine
|
|
402
|
+
if (found.length === 0)
|
|
403
|
+
throw new UserAdminError(
|
|
404
|
+
'not_found',
|
|
405
|
+
`There is no open sign-in "${id}".`,
|
|
406
|
+
'`crombolo users sessions` lists them.',
|
|
407
|
+
)
|
|
408
|
+
if (found.length > 1)
|
|
409
|
+
throw new UserAdminError(
|
|
410
|
+
'usage',
|
|
411
|
+
`"${id}" is the start of more than one sign-in: give more of it.`,
|
|
412
|
+
)
|
|
413
|
+
const signIn = found[0] as SignIn
|
|
414
|
+
await new AuthStore(db).endSession(signIn.id)
|
|
415
|
+
return signIn
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Where a group starts in one tree: all of it, none of it, or a place in it. */
|
|
419
|
+
export interface StartAt {
|
|
420
|
+
at: 'root' | 'none' | 'node'
|
|
421
|
+
key: string | null
|
|
422
|
+
path: string | null
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
export interface GroupPlace {
|
|
426
|
+
key: string
|
|
427
|
+
alias: string
|
|
428
|
+
name: string
|
|
429
|
+
content: StartAt
|
|
430
|
+
media: StartAt
|
|
431
|
+
library: StartAt
|
|
432
|
+
/** The groups that own it, by alias. */
|
|
433
|
+
owners: string[]
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** What `placeGroup` changes: a place is a path, a key, `root` or `none`. */
|
|
437
|
+
export interface GroupPlaceChange {
|
|
438
|
+
content?: string
|
|
439
|
+
media?: string
|
|
440
|
+
library?: string
|
|
441
|
+
addOwners?: string[]
|
|
442
|
+
removeOwners?: string[]
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
export type PlaceField = 'content' | 'media' | 'library' | 'owners'
|
|
446
|
+
|
|
447
|
+
export interface GroupPlaced {
|
|
448
|
+
group: GroupPlace
|
|
449
|
+
changed: PlaceField[]
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const TREES = {
|
|
453
|
+
content: { tree: 'document', types: [ObjectTypes.Document], what: 'page' },
|
|
454
|
+
media: { tree: 'media', types: [ObjectTypes.Media], what: 'media folder' },
|
|
455
|
+
library: {
|
|
456
|
+
tree: 'element',
|
|
457
|
+
types: [ObjectTypes.ElementContainer, ObjectTypes.Element],
|
|
458
|
+
what: 'Library folder',
|
|
459
|
+
},
|
|
460
|
+
} as const
|
|
461
|
+
|
|
462
|
+
type Tree = keyof typeof TREES
|
|
463
|
+
|
|
464
|
+
async function pathOf(db: Db, key: string): Promise<string | null> {
|
|
465
|
+
const nodes = new NodeRepository(db)
|
|
466
|
+
const node = await nodes.byKey(normaliseUuid(key))
|
|
467
|
+
if (!node) return null
|
|
468
|
+
const names: string[] = []
|
|
469
|
+
for (const id of node.path
|
|
470
|
+
.split(',')
|
|
471
|
+
.map(Number)
|
|
472
|
+
.filter((n) => n > 0)) {
|
|
473
|
+
const row = await nodes.byId(id)
|
|
474
|
+
if (!row) return null
|
|
475
|
+
names.push(row.text ?? row.key)
|
|
476
|
+
}
|
|
477
|
+
return `/${names.join('/')}`
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
async function startAt(db: Db, start: { root: boolean; key: string | null }): Promise<StartAt> {
|
|
481
|
+
if (start.root) return { at: 'root', key: null, path: null }
|
|
482
|
+
if (!start.key) return { at: 'none', key: null, path: null }
|
|
483
|
+
return { at: 'node', key: start.key, path: await pathOf(db, start.key) }
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** Where a group starts in each tree, and who owns it, as the database keeps them. */
|
|
487
|
+
export async function groupPlaceOf(db: Db, group: UserGroupRecord): Promise<GroupPlace> {
|
|
488
|
+
const aliases = await groupAliases(db)
|
|
489
|
+
return {
|
|
490
|
+
key: group.key,
|
|
491
|
+
alias: group.alias,
|
|
492
|
+
name: group.name,
|
|
493
|
+
content: await startAt(db, group.startNodes.document),
|
|
494
|
+
media: await startAt(db, group.startNodes.media),
|
|
495
|
+
library: await startAt(db, group.startNodes.element),
|
|
496
|
+
owners: group.owners.map((k) => aliases.get(normaliseUuid(k)) ?? k),
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
async function groupNamed(db: Db, alias: string): Promise<UserGroupRecord> {
|
|
501
|
+
return (await new UserGroupRepository(db).byKey(await groupKeyOf(db, alias))) as UserGroupRecord
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
async function placeFor(
|
|
505
|
+
db: Db,
|
|
506
|
+
tree: Tree,
|
|
507
|
+
ref: string,
|
|
508
|
+
): Promise<{ root: boolean; key: string | null }> {
|
|
509
|
+
const plain = ref.trim()
|
|
510
|
+
if (plain.toLowerCase() === 'root') return { root: true, key: null }
|
|
511
|
+
if (plain.toLowerCase() === 'none') return { root: false, key: null }
|
|
512
|
+
const { types, what } = TREES[tree]
|
|
513
|
+
const resolved = await resolveNodeRef(db, types, plain)
|
|
514
|
+
if (!resolved.ok) throw new UserAdminError('not_found', describeRefFailure(plain, resolved))
|
|
515
|
+
if (!(types as readonly string[]).includes(resolved.node.objectType ?? ''))
|
|
516
|
+
throw new UserAdminError('not_found', `"${ref}" is not a ${what}.`)
|
|
517
|
+
return { root: false, key: resolved.node.key }
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
/**
|
|
521
|
+
* Changes where a group starts and who owns it, through the port's whole-group
|
|
522
|
+
* update, so its rules — an administrator's change, owners kept in a file that
|
|
523
|
+
* names them — are the group screen's. A dry run says what would change.
|
|
524
|
+
*/
|
|
525
|
+
export async function placeGroup(
|
|
526
|
+
ports: UserPorts,
|
|
527
|
+
principal: Principal,
|
|
528
|
+
alias: string,
|
|
529
|
+
change: GroupPlaceChange,
|
|
530
|
+
options: { dryRun?: boolean } = {},
|
|
531
|
+
): Promise<GroupPlaced> {
|
|
532
|
+
const group = await groupNamed(ports.db, alias)
|
|
533
|
+
if (!principal.isAdmin) check('AdministratorsOnly')
|
|
534
|
+
const starts = { ...group.startNodes }
|
|
535
|
+
const changed: PlaceField[] = []
|
|
536
|
+
for (const tree of Object.keys(TREES) as Tree[]) {
|
|
537
|
+
const ref = change[tree]
|
|
538
|
+
if (ref === undefined) continue
|
|
539
|
+
const next = await placeFor(ports.db, tree, ref)
|
|
540
|
+
const was = group.startNodes[TREES[tree].tree]
|
|
541
|
+
if (next.root !== was.root || (next.key ?? null) !== (was.key ?? null)) changed.push(tree)
|
|
542
|
+
starts[TREES[tree].tree] = next
|
|
543
|
+
}
|
|
544
|
+
const adding = await Promise.all((change.addOwners ?? []).map((a) => groupKeyOf(ports.db, a)))
|
|
545
|
+
const removing = new Set(
|
|
546
|
+
await Promise.all((change.removeOwners ?? []).map((a) => groupKeyOf(ports.db, a))),
|
|
547
|
+
)
|
|
548
|
+
const had = group.owners.map(normaliseUuid)
|
|
549
|
+
const owners = [
|
|
550
|
+
...had.filter((k) => !removing.has(k)),
|
|
551
|
+
...[...new Set(adding)].filter((k) => !had.includes(k) && !removing.has(k)),
|
|
552
|
+
]
|
|
553
|
+
if (owners.length !== had.length || owners.some((k) => !had.includes(k))) changed.push('owners')
|
|
554
|
+
const projected = { ...group, startNodes: starts, owners }
|
|
555
|
+
if (changed.length === 0 || options.dryRun)
|
|
556
|
+
return { group: await groupPlaceOf(ports.db, projected), changed }
|
|
557
|
+
const current = await ports.groups.get(principal, group.key)
|
|
558
|
+
if (typeof current === 'string') check(current)
|
|
559
|
+
const shown = current as Exclude<typeof current, string>
|
|
560
|
+
const input: UserGroupInput = {
|
|
561
|
+
key: group.key,
|
|
562
|
+
name: shown.name,
|
|
563
|
+
alias: shown.alias,
|
|
564
|
+
description: shown.description ?? null,
|
|
565
|
+
icon: shown.icon ?? null,
|
|
566
|
+
sections: shown.sections,
|
|
567
|
+
languages: shown.languages,
|
|
568
|
+
hasAccessToAllLanguages: shown.hasAccessToAllLanguages,
|
|
569
|
+
documentStartNode: starts.document.key,
|
|
570
|
+
documentRootAccess: starts.document.root,
|
|
571
|
+
mediaStartNode: starts.media.key,
|
|
572
|
+
mediaRootAccess: starts.media.root,
|
|
573
|
+
elementStartNode: starts.element.key,
|
|
574
|
+
elementRootAccess: starts.element.root,
|
|
575
|
+
fallbackPermissions: shown.fallbackPermissions,
|
|
576
|
+
permissions: shown.permissions,
|
|
577
|
+
...(changed.includes('owners') ? { owners } : {}),
|
|
578
|
+
}
|
|
579
|
+
check(await ports.groups.update(principal, group.key, input))
|
|
580
|
+
return { group: await groupPlaceOf(ports.db, await groupNamed(ports.db, group.alias)), changed }
|
|
581
|
+
}
|