@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,297 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The remote protocol's routes for the media library and for showing a page
|
|
3
|
+
* (story 355): media listed, found, shown with what uses it, changed, given a
|
|
4
|
+
* new file, folders made, and who may see an item read and set, through the core
|
|
5
|
+
* the command line uses; and a page as `content show` gives it. Each answers as
|
|
6
|
+
* the signed-in person, within their start nodes; CI is refused, since these act
|
|
7
|
+
* for a person. An item is named by its key or its path, encoded as one segment.
|
|
8
|
+
*/
|
|
9
|
+
import { rm } from 'node:fs/promises'
|
|
10
|
+
import { tmpdir } from 'node:os'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
import { hasSection, type Principal } from '@crombolo/api-management/domain'
|
|
13
|
+
import { type MediaOperations, userActor } from '@crombolo/content'
|
|
14
|
+
import { hasPathAccess, ObjectTypes } from '@crombolo/core'
|
|
15
|
+
import { type Db, describeRefFailure, NodeRepository, resolveNodeRef } from '@crombolo/data'
|
|
16
|
+
import { recordAudit } from './adapters/audit.ts'
|
|
17
|
+
import type { MediaFileStore } from './media-files.ts'
|
|
18
|
+
import {
|
|
19
|
+
findMedia,
|
|
20
|
+
listMedia,
|
|
21
|
+
MediaLibraryError,
|
|
22
|
+
makeFolders,
|
|
23
|
+
mediaAccess,
|
|
24
|
+
parseFocalPoint,
|
|
25
|
+
readAccessChange,
|
|
26
|
+
referencesTo,
|
|
27
|
+
setMediaAccess,
|
|
28
|
+
showMedia,
|
|
29
|
+
updateMedia,
|
|
30
|
+
} from './media-library.ts'
|
|
31
|
+
import { pageShown } from './undo.ts'
|
|
32
|
+
|
|
33
|
+
interface Problem {
|
|
34
|
+
code: string
|
|
35
|
+
title: string
|
|
36
|
+
detail?: string
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface MediaLibraryRouteOptions {
|
|
40
|
+
db: Db
|
|
41
|
+
media: MediaOperations
|
|
42
|
+
files(): Promise<MediaFileStore>
|
|
43
|
+
problem(status: number, body: Problem): Response
|
|
44
|
+
/** A refusal when the site's remote access level takes no changes to content. */
|
|
45
|
+
levelRefusal(): Response | undefined
|
|
46
|
+
/** Streams a request's body to a file, refusing one past the site's upload limit. */
|
|
47
|
+
receive(request: Request, path: string): Promise<{ size: number } | undefined>
|
|
48
|
+
/** Told after an item's permissions change, for the media cache here. */
|
|
49
|
+
onAccessChange?(key: string): void | Promise<void>
|
|
50
|
+
/** This server's name, on the cache instruction a permissions change appends. */
|
|
51
|
+
nodeId?: string
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The header a new file's name comes in, encoded as a URI component. */
|
|
55
|
+
export const FILE_NAME_HEADER = 'crombolo-file-name'
|
|
56
|
+
|
|
57
|
+
const STATUS: Record<MediaLibraryError['kind'], [number, string]> = {
|
|
58
|
+
not_found: [404, 'not-found'],
|
|
59
|
+
usage: [400, 'bad-request'],
|
|
60
|
+
refused: [422, 'refused'],
|
|
61
|
+
forbidden: [403, 'forbidden'],
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const body = async (request: Request): Promise<Record<string, unknown> | undefined> => {
|
|
65
|
+
const read = await request.json().catch(() => undefined)
|
|
66
|
+
return read && typeof read === 'object' ? (read as Record<string, unknown>) : undefined
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function createMediaLibraryRoutes(options: MediaLibraryRouteOptions) {
|
|
70
|
+
const { db, problem } = options
|
|
71
|
+
const refused = (error: unknown): Response => {
|
|
72
|
+
if (!(error instanceof MediaLibraryError)) throw error
|
|
73
|
+
const [status, code] = STATUS[error.kind]
|
|
74
|
+
return problem(status, {
|
|
75
|
+
code,
|
|
76
|
+
title: error.message,
|
|
77
|
+
...(error.hint ? { detail: error.hint } : {}),
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
const actorOf = (principal: Principal, request: Request) =>
|
|
81
|
+
userActor(principal, {
|
|
82
|
+
source: 'request',
|
|
83
|
+
forwardedFor: request.headers.get('x-forwarded-for'),
|
|
84
|
+
})
|
|
85
|
+
const paging = (url: URL) => ({
|
|
86
|
+
skip: Number(url.searchParams.get('skip')) || 0,
|
|
87
|
+
take: Number(url.searchParams.get('take')) || 25,
|
|
88
|
+
})
|
|
89
|
+
const notAllowed = () => new Response(null, { status: 405 })
|
|
90
|
+
|
|
91
|
+
async function mediaRoute(
|
|
92
|
+
request: Request,
|
|
93
|
+
url: URL,
|
|
94
|
+
principal: Principal,
|
|
95
|
+
rest: string[],
|
|
96
|
+
): Promise<Response> {
|
|
97
|
+
const reading = request.method === 'GET'
|
|
98
|
+
if (principal.ci)
|
|
99
|
+
return problem(403, {
|
|
100
|
+
code: 'ci-cannot-change-media',
|
|
101
|
+
title: reading ? 'Reading media needs a person' : 'Changing media needs a person',
|
|
102
|
+
detail: 'Sign in as yourself: CI cannot do this.',
|
|
103
|
+
})
|
|
104
|
+
if (!hasSection(principal, 'media'))
|
|
105
|
+
return problem(403, { code: 'forbidden', title: 'You may not see media here' })
|
|
106
|
+
if (!reading) {
|
|
107
|
+
const level = options.levelRefusal()
|
|
108
|
+
if (level) return level
|
|
109
|
+
}
|
|
110
|
+
const actor = actorOf(principal, request)
|
|
111
|
+
const [named, part] = rest
|
|
112
|
+
if (!named) {
|
|
113
|
+
if (!reading) return notAllowed()
|
|
114
|
+
const query = {
|
|
115
|
+
under: url.searchParams.get('under') || undefined,
|
|
116
|
+
type: url.searchParams.get('type') || undefined,
|
|
117
|
+
...paging(url),
|
|
118
|
+
}
|
|
119
|
+
const name = url.searchParams.get('name')
|
|
120
|
+
return Response.json(
|
|
121
|
+
name !== null
|
|
122
|
+
? await findMedia(db, actor, { ...query, name })
|
|
123
|
+
: await listMedia(db, actor, query),
|
|
124
|
+
)
|
|
125
|
+
}
|
|
126
|
+
if (named === 'folders' && !part) {
|
|
127
|
+
if (request.method !== 'POST') return notAllowed()
|
|
128
|
+
const path = (await body(request))?.path
|
|
129
|
+
if (typeof path !== 'string')
|
|
130
|
+
return problem(400, { code: 'bad-request', title: 'Send the path of the folder to make' })
|
|
131
|
+
return Response.json(await makeFolders({ db, media: options.media }, actor, path))
|
|
132
|
+
}
|
|
133
|
+
const ref = decodeURIComponent(named)
|
|
134
|
+
if (!part) {
|
|
135
|
+
if (reading)
|
|
136
|
+
return Response.json(
|
|
137
|
+
await showMedia(db, actor, ref, {
|
|
138
|
+
references: url.searchParams.get('references') === 'true',
|
|
139
|
+
...paging(url),
|
|
140
|
+
}),
|
|
141
|
+
)
|
|
142
|
+
if (request.method !== 'PATCH') return notAllowed()
|
|
143
|
+
const asked = await body(request)
|
|
144
|
+
if (!asked) return problem(400, { code: 'bad-request', title: 'Send the change to make' })
|
|
145
|
+
const focal = typeof asked.focal === 'string' ? parseFocalPoint(asked.focal) : undefined
|
|
146
|
+
if (asked.focal !== undefined && !focal)
|
|
147
|
+
return problem(400, {
|
|
148
|
+
code: 'bad-request',
|
|
149
|
+
title: 'focal is two numbers from 0 to 1, as 0.4,0.6',
|
|
150
|
+
})
|
|
151
|
+
for (const field of ['name', 'alt'] as const)
|
|
152
|
+
if (asked[field] !== undefined && typeof asked[field] !== 'string')
|
|
153
|
+
return problem(400, { code: 'bad-request', title: `${field} is text` })
|
|
154
|
+
return Response.json(
|
|
155
|
+
await updateMedia(
|
|
156
|
+
{ db, media: options.media, files: await options.files() },
|
|
157
|
+
actor,
|
|
158
|
+
ref,
|
|
159
|
+
{
|
|
160
|
+
...(typeof asked.name === 'string' ? { name: asked.name } : {}),
|
|
161
|
+
...(typeof asked.alt === 'string' ? { alt: asked.alt } : {}),
|
|
162
|
+
...(focal ? { focal } : {}),
|
|
163
|
+
},
|
|
164
|
+
{ dryRun: asked.dryRun === true },
|
|
165
|
+
),
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
if (part === 'file') {
|
|
169
|
+
if (request.method !== 'PUT') return notAllowed()
|
|
170
|
+
const name = decodeURIComponent(request.headers.get(FILE_NAME_HEADER) ?? '').trim()
|
|
171
|
+
if (!name)
|
|
172
|
+
return problem(400, { code: 'bad-request', title: `${FILE_NAME_HEADER} names the file` })
|
|
173
|
+
const local = join(tmpdir(), `crombolo-remote-file-${crypto.randomUUID()}`)
|
|
174
|
+
try {
|
|
175
|
+
let received: { size: number } | undefined
|
|
176
|
+
try {
|
|
177
|
+
received = await options.receive(request, local)
|
|
178
|
+
} catch {
|
|
179
|
+
return problem(413, {
|
|
180
|
+
code: 'too-large',
|
|
181
|
+
title: 'The file is larger than this remote takes',
|
|
182
|
+
})
|
|
183
|
+
}
|
|
184
|
+
if (!received)
|
|
185
|
+
return problem(400, { code: 'body-required', title: 'The request carried no file' })
|
|
186
|
+
const file = new File([await Bun.file(local).bytes()], name)
|
|
187
|
+
return Response.json(
|
|
188
|
+
await updateMedia(
|
|
189
|
+
{ db, media: options.media, files: await options.files() },
|
|
190
|
+
actor,
|
|
191
|
+
ref,
|
|
192
|
+
{ file },
|
|
193
|
+
{ dryRun: url.searchParams.get('dryRun') === 'true' },
|
|
194
|
+
),
|
|
195
|
+
)
|
|
196
|
+
} finally {
|
|
197
|
+
await rm(local, { force: true })
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (part === 'access') {
|
|
201
|
+
const context = { db, onChange: options.onAccessChange, nodeId: options.nodeId }
|
|
202
|
+
if (reading) return Response.json(await mediaAccess(context, actor, ref))
|
|
203
|
+
if (request.method !== 'PUT') return notAllowed()
|
|
204
|
+
const change = readAccessChange(await body(request))
|
|
205
|
+
if (typeof change === 'string') return problem(400, { code: 'bad-request', title: change })
|
|
206
|
+
const set = await setMediaAccess(context, actor, ref, change)
|
|
207
|
+
await recordAudit(db, {
|
|
208
|
+
category: 'media',
|
|
209
|
+
action: 'SetPermissions',
|
|
210
|
+
entityType: 'MediaAccess',
|
|
211
|
+
entityKey: set.key,
|
|
212
|
+
entityName: set.path,
|
|
213
|
+
detail: set.summary,
|
|
214
|
+
source: 'request',
|
|
215
|
+
userKey: principal.id,
|
|
216
|
+
userName: principal.name,
|
|
217
|
+
ipAddress: null,
|
|
218
|
+
forwardedFor: request.headers.get('x-forwarded-for'),
|
|
219
|
+
})
|
|
220
|
+
return Response.json(set)
|
|
221
|
+
}
|
|
222
|
+
return problem(404, { code: 'not-found', title: 'There is nothing here' })
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async function contentRoute(
|
|
226
|
+
request: Request,
|
|
227
|
+
url: URL,
|
|
228
|
+
principal: Principal,
|
|
229
|
+
named: string,
|
|
230
|
+
): Promise<Response> {
|
|
231
|
+
if (request.method !== 'GET') return notAllowed()
|
|
232
|
+
if (principal.ci)
|
|
233
|
+
return problem(403, {
|
|
234
|
+
code: 'ci-cannot-read-pages',
|
|
235
|
+
title: 'Reading pages needs a person',
|
|
236
|
+
detail: 'Sign in as yourself: CI cannot do this.',
|
|
237
|
+
})
|
|
238
|
+
if (!hasSection(principal, 'content'))
|
|
239
|
+
return problem(403, { code: 'forbidden', title: 'You may not see pages here' })
|
|
240
|
+
const ref = decodeURIComponent(named)
|
|
241
|
+
const resolved = await resolveNodeRef(db, [ObjectTypes.Document], ref)
|
|
242
|
+
if (!resolved.ok || resolved.node.objectType !== ObjectTypes.Document)
|
|
243
|
+
return problem(404, {
|
|
244
|
+
code: 'not-found',
|
|
245
|
+
title: resolved.ok ? `"${ref}" is not a page.` : describeRefFailure(ref, resolved),
|
|
246
|
+
})
|
|
247
|
+
const node = resolved.node
|
|
248
|
+
const ids = node.path
|
|
249
|
+
.split(',')
|
|
250
|
+
.map(Number)
|
|
251
|
+
.filter((id) => id > 0)
|
|
252
|
+
const chain = (await new NodeRepository(db).byIds(ids)).map((row) => row.key)
|
|
253
|
+
if (!hasPathAccess(principal.startNodes.document, chain, node.trashed))
|
|
254
|
+
return problem(403, { code: 'forbidden', title: `You may not see "${ref}".` })
|
|
255
|
+
const page = await pageShown(db, node.key)
|
|
256
|
+
if (!page) return problem(404, { code: 'not-found', title: `"${ref}" is not a page.` })
|
|
257
|
+
return Response.json({
|
|
258
|
+
...page,
|
|
259
|
+
...(url.searchParams.get('references') === 'true'
|
|
260
|
+
? { references: await referencesTo(db, node.key, paging(url)) }
|
|
261
|
+
: {}),
|
|
262
|
+
})
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
return {
|
|
266
|
+
/** The capabilities these routes add to discovery. */
|
|
267
|
+
capabilities: ['media-library', 'media-access', 'content-show'],
|
|
268
|
+
|
|
269
|
+
/** Whether a principal may use the media routes: a person with the Media section. */
|
|
270
|
+
mayMedia: (principal: Principal) => !principal.ci && hasSection(principal, 'media'),
|
|
271
|
+
|
|
272
|
+
/** Whether a principal may show pages: a person with the Content section. */
|
|
273
|
+
mayContent: (principal: Principal) => !principal.ci && hasSection(principal, 'content'),
|
|
274
|
+
|
|
275
|
+
/** Whether a request is a new file, streamed past the usual body limit. */
|
|
276
|
+
isUpload: (what: string, method: string) =>
|
|
277
|
+
method === 'PUT' && /^media-items\/[^/]+\/file$/.test(what),
|
|
278
|
+
|
|
279
|
+
/** Answers one of these routes, or undefined when `what` is none of them. */
|
|
280
|
+
async handle(
|
|
281
|
+
request: Request,
|
|
282
|
+
url: URL,
|
|
283
|
+
principal: Principal,
|
|
284
|
+
what: string,
|
|
285
|
+
): Promise<Response | undefined> {
|
|
286
|
+
const [head, ...rest] = what.split('/')
|
|
287
|
+
try {
|
|
288
|
+
if (head === 'media-items') return await mediaRoute(request, url, principal, rest)
|
|
289
|
+
if (head === 'content-items' && rest.length === 1 && rest[0])
|
|
290
|
+
return await contentRoute(request, url, principal, rest[0])
|
|
291
|
+
return undefined
|
|
292
|
+
} catch (error) {
|
|
293
|
+
return refused(error)
|
|
294
|
+
}
|
|
295
|
+
},
|
|
296
|
+
}
|
|
297
|
+
}
|
package/src/remote-media.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { join } from 'node:path'
|
|
|
12
12
|
import { writeFileAtomic } from './atomic-write.ts'
|
|
13
13
|
import { logger } from './logging.ts'
|
|
14
14
|
import type { MediaStore, StoredFile } from './media-store.ts'
|
|
15
|
-
import { freshAccessToken, type Keychain,
|
|
15
|
+
import { freshAccessToken, type Keychain, userKeychain } from './remote-credentials.ts'
|
|
16
16
|
|
|
17
17
|
export const REMOTE_MEDIA_FILE = join('.crombolo', 'remote-media.json')
|
|
18
18
|
|
|
@@ -48,7 +48,7 @@ export function withRemoteMedia(
|
|
|
48
48
|
): MediaStore {
|
|
49
49
|
const source = readRemoteMedia(siteDir)
|
|
50
50
|
if (!source) return store
|
|
51
|
-
const keychain = options.keychain ??
|
|
51
|
+
const keychain = options.keychain ?? userKeychain()
|
|
52
52
|
const http = options.http ?? fetch
|
|
53
53
|
const log = logger('media')
|
|
54
54
|
let warned = false
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The remote protocol's routes for members and who may see a page (story 354):
|
|
3
|
+
* members found, listed, made, changed and removed, member groups, and a page's
|
|
4
|
+
* public access. Each answers as the signed-in person through the core the
|
|
5
|
+
* command line uses; CI is refused, since these act for a person. A write is
|
|
6
|
+
* audited by the member's key, never their name, e-mail or values.
|
|
7
|
+
*/
|
|
8
|
+
import { hasSection, type Principal } from '@crombolo/api-management/domain'
|
|
9
|
+
import { type DocumentOperations, userActor } from '@crombolo/content'
|
|
10
|
+
import type { Db } from '@crombolo/data'
|
|
11
|
+
import { recordAudit } from './adapters/audit.ts'
|
|
12
|
+
import {
|
|
13
|
+
type AccessInput,
|
|
14
|
+
changeMember,
|
|
15
|
+
clearPageAccess,
|
|
16
|
+
groupsOf,
|
|
17
|
+
listMembers,
|
|
18
|
+
MemberAdminError,
|
|
19
|
+
type MemberChange,
|
|
20
|
+
type MemberPorts,
|
|
21
|
+
memberChangeAction,
|
|
22
|
+
newGroup,
|
|
23
|
+
newMember,
|
|
24
|
+
pageAccess,
|
|
25
|
+
removeGroup,
|
|
26
|
+
removeMember,
|
|
27
|
+
setPageAccess,
|
|
28
|
+
showMember,
|
|
29
|
+
} from './member-admin.ts'
|
|
30
|
+
|
|
31
|
+
interface Problem {
|
|
32
|
+
code: string
|
|
33
|
+
title: string
|
|
34
|
+
detail?: string
|
|
35
|
+
items?: string[]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface MemberRouteOptions {
|
|
39
|
+
db: Db
|
|
40
|
+
ports: () => Promise<MemberPorts>
|
|
41
|
+
/** Absent, a page's access is not offered. */
|
|
42
|
+
operations?: DocumentOperations
|
|
43
|
+
problem(status: number, body: Problem): Response
|
|
44
|
+
/** A refusal when the site's remote access level takes no changes. */
|
|
45
|
+
levelRefusal(): Response | undefined
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const KEY = '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}'
|
|
49
|
+
|
|
50
|
+
const STATUS: Record<MemberAdminError['kind'], [number, string]> = {
|
|
51
|
+
not_found: [404, 'not-found'],
|
|
52
|
+
refused: [403, 'forbidden'],
|
|
53
|
+
usage: [400, 'bad-request'],
|
|
54
|
+
conflict: [409, 'conflict'],
|
|
55
|
+
invalid: [400, 'invalid'],
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const body = async (request: Request): Promise<Record<string, unknown>> => {
|
|
59
|
+
const read = await request.json().catch(() => ({}))
|
|
60
|
+
return read && typeof read === 'object' ? (read as Record<string, unknown>) : {}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const text = (value: unknown): string | undefined => (typeof value === 'string' ? value : undefined)
|
|
64
|
+
const texts = (value: unknown): string[] =>
|
|
65
|
+
Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') : []
|
|
66
|
+
const pairs = (value: unknown): Array<[string, string]> =>
|
|
67
|
+
Array.isArray(value)
|
|
68
|
+
? value
|
|
69
|
+
.filter(
|
|
70
|
+
(p): p is [string, string] =>
|
|
71
|
+
Array.isArray(p) && typeof p[0] === 'string' && typeof p[1] === 'string',
|
|
72
|
+
)
|
|
73
|
+
.map(([a, b]) => [a, b])
|
|
74
|
+
: []
|
|
75
|
+
const flag = (value: unknown): boolean | undefined =>
|
|
76
|
+
typeof value === 'boolean' ? value : undefined
|
|
77
|
+
|
|
78
|
+
/** A change as a request names it: only the fields it gives. */
|
|
79
|
+
function changeOf(asked: Record<string, unknown>): MemberChange {
|
|
80
|
+
const change: MemberChange = {}
|
|
81
|
+
if (text(asked.email) !== undefined) change.email = text(asked.email)
|
|
82
|
+
if (text(asked.login) !== undefined) change.login = text(asked.login)
|
|
83
|
+
if (text(asked.name) !== undefined) change.name = text(asked.name)
|
|
84
|
+
if (Array.isArray(asked.sets)) change.sets = pairs(asked.sets)
|
|
85
|
+
if (Array.isArray(asked.unset)) change.unset = texts(asked.unset)
|
|
86
|
+
if (Array.isArray(asked.addGroups)) change.addGroups = texts(asked.addGroups)
|
|
87
|
+
if (Array.isArray(asked.removeGroups)) change.removeGroups = texts(asked.removeGroups)
|
|
88
|
+
if (flag(asked.approved) !== undefined) change.approved = flag(asked.approved)
|
|
89
|
+
if (flag(asked.locked) !== undefined) change.locked = flag(asked.locked)
|
|
90
|
+
if (text(asked.password)) change.password = text(asked.password)
|
|
91
|
+
if (asked.generatePassword === true) change.generatePassword = true
|
|
92
|
+
if (asked.twoFactor === false) change.twoFactor = false
|
|
93
|
+
return change
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function createMemberRoutes(options: MemberRouteOptions) {
|
|
97
|
+
const { db, problem } = options
|
|
98
|
+
const noSection = (what: string) =>
|
|
99
|
+
problem(403, { code: 'forbidden', title: `You may not ${what} here` })
|
|
100
|
+
const refused = (error: unknown): Response => {
|
|
101
|
+
if (!(error instanceof MemberAdminError)) throw error
|
|
102
|
+
const [status, code] = STATUS[error.kind]
|
|
103
|
+
return problem(status, {
|
|
104
|
+
code,
|
|
105
|
+
title: error.message,
|
|
106
|
+
...(error.details.length > 0 ? { items: error.details } : {}),
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
const audited = (
|
|
110
|
+
principal: Principal,
|
|
111
|
+
request: Request,
|
|
112
|
+
action: string,
|
|
113
|
+
entityType: 'Member' | 'MemberGroup',
|
|
114
|
+
entityKey: string,
|
|
115
|
+
) =>
|
|
116
|
+
recordAudit(db, {
|
|
117
|
+
category: 'member',
|
|
118
|
+
action,
|
|
119
|
+
source: 'request',
|
|
120
|
+
userKey: principal.id,
|
|
121
|
+
userName: principal.name,
|
|
122
|
+
entityType,
|
|
123
|
+
entityKey,
|
|
124
|
+
forwardedFor: request.headers.get('x-forwarded-for'),
|
|
125
|
+
detail: 'Through the remote protocol',
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
async function members(request: Request, url: URL, principal: Principal, ref?: string) {
|
|
129
|
+
const ports = await options.ports()
|
|
130
|
+
const method = request.method
|
|
131
|
+
if (method === 'GET' && !ref) {
|
|
132
|
+
const number = (name: string) => {
|
|
133
|
+
const value = url.searchParams.get(name)
|
|
134
|
+
return value !== null && /^\d+$/.test(value) ? Number(value) : undefined
|
|
135
|
+
}
|
|
136
|
+
return Response.json(
|
|
137
|
+
await listMembers(ports, principal, {
|
|
138
|
+
group: url.searchParams.get('group') ?? undefined,
|
|
139
|
+
type: url.searchParams.get('type') ?? undefined,
|
|
140
|
+
find: url.searchParams.get('find') ?? undefined,
|
|
141
|
+
skip: number('skip'),
|
|
142
|
+
take: number('take'),
|
|
143
|
+
}),
|
|
144
|
+
)
|
|
145
|
+
}
|
|
146
|
+
if (method === 'GET' && ref) return Response.json(await showMember(ports, principal, ref))
|
|
147
|
+
const level = options.levelRefusal()
|
|
148
|
+
if (level) return level
|
|
149
|
+
if (method === 'POST' && !ref) {
|
|
150
|
+
const asked = await body(request)
|
|
151
|
+
const made = await newMember(ports, principal, {
|
|
152
|
+
email: text(asked.email) ?? '',
|
|
153
|
+
type: text(asked.type) ?? '',
|
|
154
|
+
login: text(asked.login),
|
|
155
|
+
name: text(asked.name),
|
|
156
|
+
groups: texts(asked.groups),
|
|
157
|
+
sets: pairs(asked.sets),
|
|
158
|
+
password: text(asked.password),
|
|
159
|
+
})
|
|
160
|
+
await audited(principal, request, 'Create', 'Member', made.key)
|
|
161
|
+
return Response.json(made, { status: 201 })
|
|
162
|
+
}
|
|
163
|
+
if ((method === 'PATCH' || method === 'DELETE') && !new RegExp(`^${KEY}$`).test(ref ?? ''))
|
|
164
|
+
return problem(400, { code: 'bad-key', title: 'A member is changed by their key' })
|
|
165
|
+
if (method === 'PATCH' && ref) {
|
|
166
|
+
const change = changeOf(await body(request))
|
|
167
|
+
const done = await changeMember(ports, principal, ref, change)
|
|
168
|
+
if (done.changed)
|
|
169
|
+
await audited(principal, request, memberChangeAction(change), 'Member', done.member.key)
|
|
170
|
+
return Response.json(done)
|
|
171
|
+
}
|
|
172
|
+
if (method === 'DELETE' && ref) {
|
|
173
|
+
const gone = await removeMember(ports, principal, ref)
|
|
174
|
+
await audited(principal, request, 'Delete', 'Member', gone.key)
|
|
175
|
+
return Response.json(gone)
|
|
176
|
+
}
|
|
177
|
+
return new Response(null, { status: 405 })
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function groups(request: Request, url: URL, principal: Principal, name?: string) {
|
|
181
|
+
const ports = await options.ports()
|
|
182
|
+
const method = request.method
|
|
183
|
+
if (method === 'GET' && !name) return Response.json({ groups: await groupsOf(ports) })
|
|
184
|
+
const level = options.levelRefusal()
|
|
185
|
+
if (level) return level
|
|
186
|
+
if (method === 'POST' && !name) {
|
|
187
|
+
const made = await newGroup(ports, text((await body(request)).name) ?? '')
|
|
188
|
+
await audited(principal, request, 'Create', 'MemberGroup', made.key)
|
|
189
|
+
return Response.json(made, { status: 201 })
|
|
190
|
+
}
|
|
191
|
+
if (method === 'DELETE' && name) {
|
|
192
|
+
const gone = await removeGroup(ports, name, url.searchParams.get('confirmed') === 'true')
|
|
193
|
+
await audited(principal, request, 'Delete', 'MemberGroup', gone.key)
|
|
194
|
+
return Response.json(gone)
|
|
195
|
+
}
|
|
196
|
+
return new Response(null, { status: 405 })
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function access(
|
|
200
|
+
request: Request,
|
|
201
|
+
principal: Principal,
|
|
202
|
+
operations: DocumentOperations,
|
|
203
|
+
key: string,
|
|
204
|
+
) {
|
|
205
|
+
const method = request.method
|
|
206
|
+
if (method === 'GET') return Response.json(await pageAccess(db, key))
|
|
207
|
+
const level = options.levelRefusal()
|
|
208
|
+
if (level) return level
|
|
209
|
+
const actor = userActor(principal, {
|
|
210
|
+
source: 'request',
|
|
211
|
+
forwardedFor: request.headers.get('x-forwarded-for'),
|
|
212
|
+
})
|
|
213
|
+
if (method === 'PUT') {
|
|
214
|
+
const asked = await body(request)
|
|
215
|
+
const input: AccessInput = {
|
|
216
|
+
groups: texts(asked.groups),
|
|
217
|
+
members: texts(asked.members),
|
|
218
|
+
...(text(asked.loginPage) ? { loginPage: text(asked.loginPage) } : {}),
|
|
219
|
+
...(text(asked.noAccessPage) ? { noAccessPage: text(asked.noAccessPage) } : {}),
|
|
220
|
+
}
|
|
221
|
+
return Response.json(
|
|
222
|
+
await setPageAccess(await options.ports(), operations, actor, key, input),
|
|
223
|
+
)
|
|
224
|
+
}
|
|
225
|
+
if (method === 'DELETE') return Response.json(await clearPageAccess(db, operations, actor, key))
|
|
226
|
+
return new Response(null, { status: 405 })
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return {
|
|
230
|
+
/** The capabilities these routes add to discovery. */
|
|
231
|
+
capabilities: ['members', ...(options.operations ? ['public-access'] : [])],
|
|
232
|
+
|
|
233
|
+
/** Answers one of these routes, or undefined when `what` is none of them. */
|
|
234
|
+
async handle(
|
|
235
|
+
request: Request,
|
|
236
|
+
url: URL,
|
|
237
|
+
principal: Principal,
|
|
238
|
+
what: string,
|
|
239
|
+
): Promise<Response | undefined> {
|
|
240
|
+
const member = /^members(?:\/([^/]+))?$/.exec(what)
|
|
241
|
+
const group = /^member-groups(?:\/([^/]+))?$/.exec(what)
|
|
242
|
+
const page = options.operations ? new RegExp(`^content/(${KEY})/access$`).exec(what) : null
|
|
243
|
+
if (!member && !group && !page) return undefined
|
|
244
|
+
if (principal.ci)
|
|
245
|
+
return problem(403, {
|
|
246
|
+
code: 'ci-cannot-change-people',
|
|
247
|
+
title: 'Members need a person',
|
|
248
|
+
detail: 'Sign in as yourself: CI cannot do this.',
|
|
249
|
+
})
|
|
250
|
+
try {
|
|
251
|
+
if (page) {
|
|
252
|
+
if (!hasSection(principal, 'content')) return noSection('change who may see pages')
|
|
253
|
+
return await access(
|
|
254
|
+
request,
|
|
255
|
+
principal,
|
|
256
|
+
options.operations as DocumentOperations,
|
|
257
|
+
page[1] as string,
|
|
258
|
+
)
|
|
259
|
+
}
|
|
260
|
+
if (!hasSection(principal, 'members')) return noSection('look after members')
|
|
261
|
+
const named = (member ?? group)?.[1]
|
|
262
|
+
const decoded = named === undefined ? undefined : decodeURIComponent(named)
|
|
263
|
+
return member
|
|
264
|
+
? await members(request, url, principal, decoded)
|
|
265
|
+
: await groups(request, url, principal, decoded)
|
|
266
|
+
} catch (error) {
|
|
267
|
+
return refused(error)
|
|
268
|
+
}
|
|
269
|
+
},
|
|
270
|
+
}
|
|
271
|
+
}
|