@crombolo/server 0.33.1 → 0.35.2
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 +14 -0
- package/package.json +13 -13
- package/src/adapters/audit.ts +1 -0
- package/src/adapters/bundles.ts +5 -4
- package/src/adapters/documents.ts +48 -22
- package/src/bundle-build.ts +7 -1
- package/src/bundle-code.ts +10 -71
- package/src/bundle-media.ts +613 -0
- package/src/bundles.ts +511 -57
- package/src/components.ts +58 -0
- package/src/config.ts +17 -1
- package/src/content-events.ts +11 -6
- package/src/delivery-media.ts +58 -0
- package/src/image-metadata.ts +355 -0
- package/src/imaging.ts +98 -0
- package/src/index.ts +3 -0
- package/src/marketplace.ts +88 -12
- package/src/media-access.ts +319 -0
- package/src/member-auth.ts +24 -3
- package/src/ports.ts +7 -2
- package/src/rate-limit.ts +54 -0
- package/src/schema.ts +78 -8
- package/src/seed/export.ts +16 -6
- package/src/seo.ts +5 -6
- package/src/server.ts +369 -73
- package/src/settings.ts +8 -0
- package/src/site-file.ts +2 -2
package/src/index.ts
CHANGED
|
@@ -21,6 +21,7 @@ export * from './boot-failure.ts'
|
|
|
21
21
|
export * from './bundle-build.ts'
|
|
22
22
|
export * from './bundle-code.ts'
|
|
23
23
|
export * from './bundle-install.ts'
|
|
24
|
+
export * from './bundle-media.ts'
|
|
24
25
|
export * from './bundle-reload.ts'
|
|
25
26
|
export * from './bundle-sections.ts'
|
|
26
27
|
export * from './bundle-tables.ts'
|
|
@@ -60,6 +61,7 @@ export * from './git-routes.ts'
|
|
|
60
61
|
export * from './host-token.ts'
|
|
61
62
|
export * from './identity-provider-overrides.ts'
|
|
62
63
|
export * from './identity-providers.ts'
|
|
64
|
+
export * from './image-metadata.ts'
|
|
63
65
|
export * from './imaging.ts'
|
|
64
66
|
export * from './jobs.ts'
|
|
65
67
|
export * from './listen.ts'
|
|
@@ -77,6 +79,7 @@ export * from './models-builder.ts'
|
|
|
77
79
|
export * from './no-nodes.ts'
|
|
78
80
|
export * from './oembed.ts'
|
|
79
81
|
export * from './ports.ts'
|
|
82
|
+
export * from './rate-limit.ts'
|
|
80
83
|
export * from './redirects.ts'
|
|
81
84
|
export * from './remote.ts'
|
|
82
85
|
export * from './remote-credentials.ts'
|
package/src/marketplace.ts
CHANGED
|
@@ -113,6 +113,11 @@ export interface InstallOutcome {
|
|
|
113
113
|
message: string
|
|
114
114
|
/** What happened to the content the bundle carries; absent when it carries none. */
|
|
115
115
|
content?: ContentOutcome
|
|
116
|
+
/**
|
|
117
|
+
* Refused because the bundle runs code on the server and the request did not
|
|
118
|
+
* accept that (story 194): the screen asks, and sends the install again.
|
|
119
|
+
*/
|
|
120
|
+
needsServerConsent?: boolean
|
|
116
121
|
}
|
|
117
122
|
|
|
118
123
|
export type PackageInstaller = (
|
|
@@ -155,11 +160,21 @@ export interface Marketplace {
|
|
|
155
160
|
install(
|
|
156
161
|
name: string,
|
|
157
162
|
version: string | undefined,
|
|
158
|
-
options?: { applyContent?: boolean },
|
|
163
|
+
options?: { applyContent?: boolean; acceptServerCode?: boolean },
|
|
159
164
|
): Promise<InstallOutcome>
|
|
160
165
|
uninstall(name: string): Promise<InstallOutcome>
|
|
161
166
|
}
|
|
162
167
|
|
|
168
|
+
/**
|
|
169
|
+
* The argv an install runs. `add` never runs a package's install scripts,
|
|
170
|
+
* whatever Bun's own list of trusted packages says (story 194).
|
|
171
|
+
*/
|
|
172
|
+
export function installCommand(action: 'add' | 'remove', specifier: string): string[] {
|
|
173
|
+
return action === 'add'
|
|
174
|
+
? ['bun', 'add', '--ignore-scripts', specifier]
|
|
175
|
+
: ['bun', action, specifier]
|
|
176
|
+
}
|
|
177
|
+
|
|
163
178
|
/**
|
|
164
179
|
* `bun add` in the site directory: Bun owns resolution and writes the lockfile.
|
|
165
180
|
*
|
|
@@ -170,7 +185,7 @@ export interface Marketplace {
|
|
|
170
185
|
*/
|
|
171
186
|
export const bunInstaller: PackageInstaller = async (action, specifier, siteDir) => {
|
|
172
187
|
try {
|
|
173
|
-
const proc = Bun.spawn(
|
|
188
|
+
const proc = Bun.spawn(installCommand(action, specifier), {
|
|
174
189
|
cwd: siteDir,
|
|
175
190
|
stdout: 'pipe',
|
|
176
191
|
stderr: 'pipe',
|
|
@@ -213,20 +228,37 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
|
|
|
213
228
|
options.extensions.bundles().bundles.find((bundle) => bundle.packageName === name)?.version ??
|
|
214
229
|
null
|
|
215
230
|
|
|
216
|
-
/**
|
|
217
|
-
|
|
231
|
+
/**
|
|
232
|
+
* What the registry says a version carries: the version asked for (an exact
|
|
233
|
+
* one, or the highest a range admits), or the latest. `not-a-bundle` when that
|
|
234
|
+
* version is no valid bundle, `unreachable` when the registry could not say.
|
|
235
|
+
*/
|
|
236
|
+
const declaresAt = async (
|
|
237
|
+
name: string,
|
|
238
|
+
wanted?: string,
|
|
239
|
+
): Promise<BundlePackage['carries'] | 'not-a-bundle' | 'unreachable'> => {
|
|
218
240
|
try {
|
|
219
241
|
const response = await call(`${options.registry}/${encodeURIComponent(name)}`, {
|
|
220
242
|
headers: { accept: 'application/json' },
|
|
221
243
|
})
|
|
222
|
-
if (!response.ok) return
|
|
244
|
+
if (!response.ok) return response.status === 404 ? 'not-a-bundle' : 'unreachable'
|
|
223
245
|
const packument = (await response.json()) as {
|
|
224
|
-
'dist-tags'?:
|
|
246
|
+
'dist-tags'?: Record<string, string>
|
|
225
247
|
versions?: Record<string, PackageJson>
|
|
226
248
|
}
|
|
227
|
-
const
|
|
228
|
-
const
|
|
229
|
-
|
|
249
|
+
const versions = packument.versions ?? {}
|
|
250
|
+
const resolved =
|
|
251
|
+
wanted === undefined
|
|
252
|
+
? packument['dist-tags']?.latest
|
|
253
|
+
: wanted in versions
|
|
254
|
+
? wanted
|
|
255
|
+
: (packument['dist-tags']?.[wanted] ??
|
|
256
|
+
Object.keys(versions)
|
|
257
|
+
.filter((v) => Bun.semver.satisfies(v, wanted))
|
|
258
|
+
.sort(Bun.semver.order)
|
|
259
|
+
.at(-1))
|
|
260
|
+
const version = resolved ? versions[resolved] : undefined
|
|
261
|
+
if (!version || validateBundlePackage(version).length > 0) return 'not-a-bundle'
|
|
230
262
|
const field = version.crombolo as {
|
|
231
263
|
extensions?: unknown[]
|
|
232
264
|
content?: boolean
|
|
@@ -238,10 +270,16 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
|
|
|
238
270
|
server: field.server !== undefined,
|
|
239
271
|
}
|
|
240
272
|
} catch {
|
|
241
|
-
return
|
|
273
|
+
return 'unreachable'
|
|
242
274
|
}
|
|
243
275
|
}
|
|
244
276
|
|
|
277
|
+
/** What the registry says this package's latest version carries, when it is a valid bundle. */
|
|
278
|
+
const declares = async (name: string): Promise<BundlePackage['carries'] | undefined> => {
|
|
279
|
+
const carries = await declaresAt(name)
|
|
280
|
+
return typeof carries === 'string' ? undefined : carries
|
|
281
|
+
}
|
|
282
|
+
|
|
245
283
|
return {
|
|
246
284
|
url: () => options.marketplaceUrl,
|
|
247
285
|
|
|
@@ -329,6 +367,22 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
|
|
|
329
367
|
if (version !== undefined && !isValidVersion(version))
|
|
330
368
|
return { ok: false, message: `'${version}' is not a version npm would accept.` }
|
|
331
369
|
|
|
370
|
+
// What the version being installed carries, read before anything is
|
|
371
|
+
// installed: server code needs an explicit yes (story 194), and only a
|
|
372
|
+
// bundle is installed here at all.
|
|
373
|
+
const declared = await declaresAt(name, version)
|
|
374
|
+
if (declared === 'unreachable')
|
|
375
|
+
return {
|
|
376
|
+
ok: false,
|
|
377
|
+
message: `The package registry could not say what ${name} contains, so it was not installed. Try again in a moment.`,
|
|
378
|
+
}
|
|
379
|
+
if (declared === 'not-a-bundle')
|
|
380
|
+
return {
|
|
381
|
+
ok: false,
|
|
382
|
+
message: `${name} is not a bundle for this site, so it was not installed.`,
|
|
383
|
+
}
|
|
384
|
+
if (declared.server && request.acceptServerCode !== true) return serverConsentNeeded(name)
|
|
385
|
+
|
|
332
386
|
const specifier = version ? `${name}@${version}` : name
|
|
333
387
|
const result = await install('add', specifier, options.siteDir)
|
|
334
388
|
options.extensions.invalidate()
|
|
@@ -348,6 +402,16 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
|
|
|
348
402
|
dependency: { name, range, version: version ?? range },
|
|
349
403
|
message: `${name} was installed, but it is not a valid bundle, so nothing was added to the backoffice.`,
|
|
350
404
|
}
|
|
405
|
+
// The version that landed is what counts: a release published between
|
|
406
|
+
// reading the registry and installing may have brought server code.
|
|
407
|
+
if (found.carries.server && request.acceptServerCode !== true) {
|
|
408
|
+
await install('remove', name, options.siteDir)
|
|
409
|
+
options.extensions.invalidate()
|
|
410
|
+
return serverConsentNeeded(
|
|
411
|
+
name,
|
|
412
|
+
`${name}@${found.version} turned out to run code on the server, so it was removed again.`,
|
|
413
|
+
)
|
|
414
|
+
}
|
|
351
415
|
|
|
352
416
|
// The content half lands after the dependency, so a refused check leaves
|
|
353
417
|
// the package installed and says why, rather than undoing an install that
|
|
@@ -373,9 +437,9 @@ export function createMarketplace(options: MarketplaceOptions): Marketplace {
|
|
|
373
437
|
// committed; saying so is the difference between a surprise and a plan.
|
|
374
438
|
message: `${name}@${found.version} is installed. Commit the changed package.json and bun.lock to keep it across deployments.${
|
|
375
439
|
found.carries.server
|
|
376
|
-
?
|
|
440
|
+
? " Its server code runs only once your site's developers turn it on and deploy the site."
|
|
377
441
|
: ''
|
|
378
|
-
}`,
|
|
442
|
+
}${found.carries.extensions ? ` ${SCREENS_NOTICE}` : ''}`,
|
|
379
443
|
...(content ? { content } : {}),
|
|
380
444
|
}
|
|
381
445
|
},
|
|
@@ -408,6 +472,18 @@ function descriptionOf(directory: string): string {
|
|
|
408
472
|
}
|
|
409
473
|
}
|
|
410
474
|
|
|
475
|
+
/** Said of every bundle installed here: its screens are someone else's code in our browsers. */
|
|
476
|
+
export const SCREENS_NOTICE = 'Its screens run in the browser of everyone who uses the back office.'
|
|
477
|
+
|
|
478
|
+
/** A refusal the screen answers by asking for an explicit yes (story 194). */
|
|
479
|
+
function serverConsentNeeded(name: string, before = ''): InstallOutcome {
|
|
480
|
+
return {
|
|
481
|
+
ok: false,
|
|
482
|
+
needsServerConsent: true,
|
|
483
|
+
message: `${before ? `${before} ` : ''}${name} runs code on the server, with access to the site's data, files and settings. Confirm that you trust its publisher to install it.`,
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
411
487
|
/** What a site that does not install at runtime says instead, with what to do. */
|
|
412
488
|
function refusedHere(
|
|
413
489
|
name: string,
|
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Who may read a media file, and the back office's permissions for media
|
|
3
|
+
* (story 196). docs/media.md, "Protected media".
|
|
4
|
+
*
|
|
5
|
+
* `/media/…` asks `mayRead` of a protected file: a member by their site
|
|
6
|
+
* cookie or a Delivery API member token, or a back-office user with the Media
|
|
7
|
+
* section within their start nodes. The back office's "Permissions" action
|
|
8
|
+
* reads and sets rules through `handle`, under
|
|
9
|
+
* `<backoffice>/crombolo/api/media-access/{key}`, which is not in the contract.
|
|
10
|
+
*/
|
|
11
|
+
import { hasSection, type Principal } from '@crombolo/api-management'
|
|
12
|
+
import {
|
|
13
|
+
fallbackPermissions,
|
|
14
|
+
hasPathAccess,
|
|
15
|
+
isProtectedMedia,
|
|
16
|
+
MEDIA_POLICIES,
|
|
17
|
+
MEMBER_FILE_TYPES,
|
|
18
|
+
type MediaMember,
|
|
19
|
+
MediaPermissions,
|
|
20
|
+
type MediaPolicy,
|
|
21
|
+
memberMay,
|
|
22
|
+
NEW_MEDIA_READ,
|
|
23
|
+
NEW_MEDIA_WRITE,
|
|
24
|
+
type NewMediaRead,
|
|
25
|
+
type NewMediaWrite,
|
|
26
|
+
normaliseUuid,
|
|
27
|
+
ObjectTypes,
|
|
28
|
+
} from '@crombolo/core'
|
|
29
|
+
import {
|
|
30
|
+
appendCacheInstruction,
|
|
31
|
+
type Db,
|
|
32
|
+
type MediaAccessEntry,
|
|
33
|
+
type MediaAccessGroup,
|
|
34
|
+
MediaAccessRepository,
|
|
35
|
+
type MediaByUrl,
|
|
36
|
+
MemberRepository,
|
|
37
|
+
NodeRepository,
|
|
38
|
+
ruleOf,
|
|
39
|
+
} from '@crombolo/data'
|
|
40
|
+
|
|
41
|
+
export interface MediaAccessDeps {
|
|
42
|
+
db: Db
|
|
43
|
+
/** The member a request's site cookie carries. */
|
|
44
|
+
member(request: Request): Promise<MediaMember | undefined>
|
|
45
|
+
/** The member a Delivery API token names, when member tokens are on. */
|
|
46
|
+
memberByToken?(token: string): Promise<MediaMember | undefined>
|
|
47
|
+
/** The back-office user a request carries. */
|
|
48
|
+
principal(request: Request): Promise<Principal | undefined>
|
|
49
|
+
/** Told after a rule or an item's setting changes, with its key, for the media cache here. */
|
|
50
|
+
onChange?(key: string): void | Promise<void>
|
|
51
|
+
/** This server's name, on the cache instruction an item's change appends. */
|
|
52
|
+
nodeId?: string
|
|
53
|
+
/** The folders wired bundles declare (story 198), by bundle name and node path. */
|
|
54
|
+
bundleFolders?(): ReadonlyArray<{ bundle: string; nodePath: string }>
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const bearerOf = (request: Request): string | undefined => {
|
|
58
|
+
const header = request.headers.get('authorization')
|
|
59
|
+
return header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : undefined
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const isUuid = (value: string) =>
|
|
63
|
+
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)
|
|
64
|
+
|
|
65
|
+
/** A rule as the back office sends and shows it. */
|
|
66
|
+
interface RuleBody {
|
|
67
|
+
publicRead: boolean
|
|
68
|
+
groups: MediaAccessGroup[]
|
|
69
|
+
newRead: NewMediaRead | null
|
|
70
|
+
newWrite: NewMediaWrite | null
|
|
71
|
+
/** File types members may upload below (story 198); empty is none. */
|
|
72
|
+
memberTypes: string[]
|
|
73
|
+
/** The largest file a member may upload below, in bytes; null sets none. */
|
|
74
|
+
memberMaxBytes: number | null
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const ruleBody = (entry: MediaAccessEntry): RuleBody => ({
|
|
78
|
+
publicRead: entry.publicRead,
|
|
79
|
+
groups: entry.groups,
|
|
80
|
+
newRead: entry.newRead,
|
|
81
|
+
newWrite: entry.newWrite,
|
|
82
|
+
memberTypes: entry.memberTypes,
|
|
83
|
+
memberMaxBytes: entry.memberMaxBytes,
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
/** A rule from a request body; a string saying what is wrong otherwise. Pure. */
|
|
87
|
+
export function parseRuleBody(raw: unknown): RuleBody | string {
|
|
88
|
+
if (!raw || typeof raw !== 'object') return 'Send the permissions to set.'
|
|
89
|
+
const body = raw as Record<string, unknown>
|
|
90
|
+
const groups = Array.isArray(body.groups) ? body.groups : []
|
|
91
|
+
const parsed: MediaAccessGroup[] = []
|
|
92
|
+
for (const group of groups) {
|
|
93
|
+
const g = group as Record<string, unknown>
|
|
94
|
+
if (!g || typeof g.name !== 'string' || g.name.trim() === '') return 'Each group needs a name.'
|
|
95
|
+
parsed.push({ name: g.name.trim(), read: g.read === true, write: g.write === true })
|
|
96
|
+
}
|
|
97
|
+
const newRead = body.newRead ?? null
|
|
98
|
+
if (newRead !== null && !NEW_MEDIA_READ.includes(newRead as NewMediaRead))
|
|
99
|
+
return 'Choose who may see new files: everyone, the groups, or the member who added it.'
|
|
100
|
+
const newWrite = body.newWrite ?? null
|
|
101
|
+
if (newWrite !== null && !NEW_MEDIA_WRITE.includes(newWrite as NewMediaWrite))
|
|
102
|
+
return 'Choose who may change new files: the groups, the member who added it, or no member.'
|
|
103
|
+
const known = MEMBER_FILE_TYPES.map((type) => type.id)
|
|
104
|
+
const memberTypes = body.memberTypes ?? []
|
|
105
|
+
if (!Array.isArray(memberTypes) || memberTypes.some((t) => !known.includes(t as string)))
|
|
106
|
+
return 'Choose the file types members may upload from the list.'
|
|
107
|
+
const memberMaxBytes = body.memberMaxBytes ?? null
|
|
108
|
+
if (
|
|
109
|
+
memberMaxBytes !== null &&
|
|
110
|
+
(typeof memberMaxBytes !== 'number' || !Number.isInteger(memberMaxBytes) || memberMaxBytes <= 0)
|
|
111
|
+
)
|
|
112
|
+
return 'The largest file members may upload must be a size above nothing, or left empty.'
|
|
113
|
+
return {
|
|
114
|
+
publicRead: body.publicRead === true,
|
|
115
|
+
groups: parsed,
|
|
116
|
+
newRead: newRead as NewMediaRead | null,
|
|
117
|
+
newWrite: newWrite as NewMediaWrite | null,
|
|
118
|
+
memberTypes: [...new Set(memberTypes as string[])],
|
|
119
|
+
memberMaxBytes: memberMaxBytes as number | null,
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function createMediaAccess(deps: MediaAccessDeps) {
|
|
124
|
+
const { db } = deps
|
|
125
|
+
const repo = new MediaAccessRepository(db)
|
|
126
|
+
const nodes = new NodeRepository(db)
|
|
127
|
+
|
|
128
|
+
/** A node's media ancestors' keys then its own, root first. */
|
|
129
|
+
const chainOf = async (path: string): Promise<string[]> => {
|
|
130
|
+
const ids = path
|
|
131
|
+
.split(',')
|
|
132
|
+
.map(Number)
|
|
133
|
+
.filter((id) => id > 0)
|
|
134
|
+
const byId = new Map((await nodes.byIds(ids)).map((row) => [row.id, row]))
|
|
135
|
+
return ids.flatMap((id) => {
|
|
136
|
+
const row = byId.get(id)
|
|
137
|
+
return row && row.objectType === ObjectTypes.Media ? [row.key] : []
|
|
138
|
+
})
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const mayView = async (principal: Principal, path: string, trashed: boolean) =>
|
|
142
|
+
hasSection(principal, 'media') &&
|
|
143
|
+
hasPathAccess(principal.startNodes.media, await chainOf(path), trashed)
|
|
144
|
+
|
|
145
|
+
/** The member a request carries: its site cookie, else a Delivery API member token. */
|
|
146
|
+
const memberOf = async (request: Request): Promise<MediaMember | undefined> => {
|
|
147
|
+
const fromCookie = await deps.member(request)
|
|
148
|
+
if (fromCookie) return fromCookie
|
|
149
|
+
const token = bearerOf(request)
|
|
150
|
+
return token && deps.memberByToken ? deps.memberByToken(token) : undefined
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Whether this request may read a protected file. A file in the recycle bin
|
|
155
|
+
* has left the folder that protected it, so only a back-office user may.
|
|
156
|
+
*/
|
|
157
|
+
async function mayRead(request: Request, item: MediaByUrl): Promise<boolean> {
|
|
158
|
+
if (!item.trashed) {
|
|
159
|
+
const member = await memberOf(request)
|
|
160
|
+
if (member && memberMay('read', item.access, item.rule, member)) return true
|
|
161
|
+
}
|
|
162
|
+
const principal = await deps.principal(request)
|
|
163
|
+
return principal ? mayView(principal, item.path, item.trashed) : false
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Whether a file is closed to someone who is not signed in. */
|
|
167
|
+
const isProtected = (item: MediaByUrl) => item.trashed || isProtectedMedia(item.access, item.rule)
|
|
168
|
+
|
|
169
|
+
const memberGroups = async (): Promise<string[]> => {
|
|
170
|
+
const rows = await db.query<{ text: string | null }>(
|
|
171
|
+
'SELECT text FROM node WHERE node_object_type = ? ORDER BY text',
|
|
172
|
+
[ObjectTypes.MemberGroup],
|
|
173
|
+
)
|
|
174
|
+
return rows.flatMap((row) => (row.text ? [String(row.text)] : []))
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* The bundles that use a folder: those declaring it, or one below it, so a
|
|
179
|
+
* rename, move or delete of it would break their path. Sorted, each once.
|
|
180
|
+
*/
|
|
181
|
+
const usedBy = (id: number): string[] =>
|
|
182
|
+
[
|
|
183
|
+
...new Set(
|
|
184
|
+
(deps.bundleFolders?.() ?? [])
|
|
185
|
+
.filter((folder) => `,${folder.nodePath},`.includes(`,${id},`))
|
|
186
|
+
.map((folder) => folder.bundle),
|
|
187
|
+
),
|
|
188
|
+
].sort()
|
|
189
|
+
|
|
190
|
+
/** Every folder a bundle's path runs through, with the bundles that use it. */
|
|
191
|
+
async function usedFolders(): Promise<Array<{ key: string; name: string; bundles: string[] }>> {
|
|
192
|
+
const ids = new Set<number>()
|
|
193
|
+
for (const folder of deps.bundleFolders?.() ?? [])
|
|
194
|
+
for (const id of folder.nodePath.split(',').map(Number)) if (id > 0) ids.add(id)
|
|
195
|
+
const rows = await nodes.byIds([...ids])
|
|
196
|
+
return rows
|
|
197
|
+
.filter((row) => row.objectType === ObjectTypes.Media)
|
|
198
|
+
.map((row) => ({ key: row.key, name: row.text ?? '', bundles: usedBy(row.id) }))
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** What the Permissions dialog shows for a folder or item. */
|
|
202
|
+
async function describe(key: string) {
|
|
203
|
+
const node = await nodes.byKey(key)
|
|
204
|
+
if (!node || node.objectType !== ObjectTypes.Media) return undefined
|
|
205
|
+
const own = await repo.byNodeKey(key)
|
|
206
|
+
const inherited = await repo.ruleFor(key, { above: true })
|
|
207
|
+
const item = (await repo.itemAccess(key)) ?? {
|
|
208
|
+
readPolicy: 'inherit' as const,
|
|
209
|
+
writePolicy: 'inherit' as const,
|
|
210
|
+
creatorMemberKey: null,
|
|
211
|
+
}
|
|
212
|
+
const fileRows = await db.query<{ file_url: string | null }>(
|
|
213
|
+
'SELECT file_url FROM content WHERE node_id = ?',
|
|
214
|
+
[node.id],
|
|
215
|
+
)
|
|
216
|
+
const from = inherited ? await nodes.byKey(inherited.nodeKey) : undefined
|
|
217
|
+
const creator = item.creatorMemberKey
|
|
218
|
+
? await new MemberRepository(db).byKey(item.creatorMemberKey)
|
|
219
|
+
: undefined
|
|
220
|
+
const effective = own ?? inherited
|
|
221
|
+
return {
|
|
222
|
+
key: node.key,
|
|
223
|
+
name: node.text ?? '',
|
|
224
|
+
hasFile: Boolean(fileRows[0]?.file_url),
|
|
225
|
+
own: own ? ruleBody(own) : null,
|
|
226
|
+
inherited:
|
|
227
|
+
inherited && from
|
|
228
|
+
? { from: { key: from.key, name: from.text ?? '' }, ...ruleBody(inherited) }
|
|
229
|
+
: null,
|
|
230
|
+
item: {
|
|
231
|
+
readPolicy: item.readPolicy,
|
|
232
|
+
writePolicy: item.writePolicy,
|
|
233
|
+
creator: item.creatorMemberKey
|
|
234
|
+
? { key: item.creatorMemberKey, name: creator?.name ?? null }
|
|
235
|
+
: null,
|
|
236
|
+
},
|
|
237
|
+
protected: node.trashed || isProtectedMedia(item, effective ? ruleOf(effective) : undefined),
|
|
238
|
+
memberGroups: await memberGroups(),
|
|
239
|
+
memberFileTypes: MEMBER_FILE_TYPES.map((type) => ({ id: type.id, label: type.label })),
|
|
240
|
+
usedBy: usedBy(node.id),
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* `GET|PUT|DELETE /{key}`. A PUT sends `rule` (null takes the folder's or
|
|
246
|
+
* item's own rule off) and, for a file, `item` with its own policies.
|
|
247
|
+
*/
|
|
248
|
+
async function handle(
|
|
249
|
+
request: Request,
|
|
250
|
+
subpath: string,
|
|
251
|
+
principal: Principal,
|
|
252
|
+
): Promise<Response | undefined> {
|
|
253
|
+
const key = subpath.replace(/^\//, '')
|
|
254
|
+
if (key === 'used') {
|
|
255
|
+
if (!hasSection(principal, 'media')) return new Response('Forbidden', { status: 403 })
|
|
256
|
+
if (request.method !== 'GET') return new Response('Method Not Allowed', { status: 405 })
|
|
257
|
+
return Response.json(await usedFolders())
|
|
258
|
+
}
|
|
259
|
+
if (!isUuid(key)) return undefined
|
|
260
|
+
if (!hasSection(principal, 'media')) return new Response('Forbidden', { status: 403 })
|
|
261
|
+
const node = await nodes.byKey(key)
|
|
262
|
+
if (!node || node.objectType !== ObjectTypes.Media)
|
|
263
|
+
return new Response('Not Found', { status: 404 })
|
|
264
|
+
if (!(await mayView(principal, node.path, node.trashed)))
|
|
265
|
+
return new Response('Forbidden', { status: 403 })
|
|
266
|
+
|
|
267
|
+
if (request.method === 'GET') return Response.json(await describe(key))
|
|
268
|
+
if (request.method !== 'PUT' && request.method !== 'DELETE')
|
|
269
|
+
return new Response('Method Not Allowed', { status: 405 })
|
|
270
|
+
if (!fallbackPermissions(principal.groups).has(MediaPermissions.Update))
|
|
271
|
+
return new Response('Forbidden', { status: 403 })
|
|
272
|
+
|
|
273
|
+
if (request.method === 'DELETE') {
|
|
274
|
+
await repo.remove(key)
|
|
275
|
+
} else {
|
|
276
|
+
const body = (await request.json().catch(() => undefined)) as
|
|
277
|
+
| Record<string, unknown>
|
|
278
|
+
| undefined
|
|
279
|
+
if (!body) return Response.json({ reason: 'Send the permissions to set.' }, { status: 400 })
|
|
280
|
+
let item: { readPolicy: MediaPolicy; writePolicy: MediaPolicy } | undefined
|
|
281
|
+
if (body.item !== undefined) {
|
|
282
|
+
const raw = (body.item ?? {}) as Record<string, unknown>
|
|
283
|
+
const read = raw.readPolicy ?? 'inherit'
|
|
284
|
+
const write = raw.writePolicy ?? 'inherit'
|
|
285
|
+
if (!MEDIA_POLICIES.includes(read as MediaPolicy))
|
|
286
|
+
return Response.json({ reason: 'Choose who may see this file.' }, { status: 400 })
|
|
287
|
+
if (!MEDIA_POLICIES.includes(write as MediaPolicy) || write === 'public')
|
|
288
|
+
return Response.json({ reason: 'Choose who may change this file.' }, { status: 400 })
|
|
289
|
+
item = { readPolicy: read as MediaPolicy, writePolicy: write as MediaPolicy }
|
|
290
|
+
}
|
|
291
|
+
let rule: RuleBody | null | undefined
|
|
292
|
+
if (body.rule === null) rule = null
|
|
293
|
+
else if (body.rule !== undefined) {
|
|
294
|
+
const parsed = parseRuleBody(body.rule)
|
|
295
|
+
if (typeof parsed === 'string') return Response.json({ reason: parsed }, { status: 400 })
|
|
296
|
+
rule = parsed
|
|
297
|
+
}
|
|
298
|
+
await db.transaction(async (tx) => {
|
|
299
|
+
const writing = new MediaAccessRepository(tx)
|
|
300
|
+
if (rule === null) await writing.remove(key)
|
|
301
|
+
else if (rule) await writing.save({ nodeKey: key, ...rule })
|
|
302
|
+
if (item) await writing.setItemAccess(key, item)
|
|
303
|
+
// The item carries its own settings in every server's media cache (story 197).
|
|
304
|
+
if (item)
|
|
305
|
+
await appendCacheInstruction(tx, {
|
|
306
|
+
kind: 'content',
|
|
307
|
+
payload: { media: [normaliseUuid(key)] },
|
|
308
|
+
by: deps.nodeId,
|
|
309
|
+
})
|
|
310
|
+
})
|
|
311
|
+
}
|
|
312
|
+
await deps.onChange?.(normaliseUuid(key))
|
|
313
|
+
return Response.json(await describe(normaliseUuid(key)))
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
return { mayRead, isProtected, handle, describe }
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export type MediaAccess = ReturnType<typeof createMediaAccess>
|
package/src/member-auth.ts
CHANGED
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
* accounts is a decision a site makes, not one a framework makes for it.
|
|
24
24
|
*/
|
|
25
25
|
import {
|
|
26
|
+
antiforgeryToken,
|
|
26
27
|
expireCookie,
|
|
27
28
|
hashPassword,
|
|
28
29
|
isNativeHash,
|
|
@@ -35,6 +36,7 @@ import {
|
|
|
35
36
|
serializeCookie,
|
|
36
37
|
signMemberTicket,
|
|
37
38
|
signShortLived,
|
|
39
|
+
verifyAntiforgery,
|
|
38
40
|
verifyPassword,
|
|
39
41
|
} from '@crombolo/auth'
|
|
40
42
|
import {
|
|
@@ -77,9 +79,20 @@ export interface MemberAuthOptions {
|
|
|
77
79
|
nodeId?: string
|
|
78
80
|
}
|
|
79
81
|
|
|
82
|
+
/** A member signed in by the site's cookie, with that session's anti-forgery token. */
|
|
83
|
+
export interface MemberSession {
|
|
84
|
+
member: RequestMember
|
|
85
|
+
/** For `<AntiforgeryMeta />`. */
|
|
86
|
+
antiforgery: string
|
|
87
|
+
/** Whether a request's `Crombolo-Antiforgery` value belongs to this session. */
|
|
88
|
+
verify(token: string | null): Promise<boolean>
|
|
89
|
+
}
|
|
90
|
+
|
|
80
91
|
export interface MemberAuth {
|
|
81
92
|
/** The member this request carries, or undefined. */
|
|
82
93
|
resolve(request: Request): Promise<RequestMember | undefined>
|
|
94
|
+
/** The member this request's cookie carries, and its anti-forgery token (story 186). */
|
|
95
|
+
session(request: Request): Promise<MemberSession | undefined>
|
|
83
96
|
/**
|
|
84
97
|
* Whether a member may see a page, and what to render instead when not. The
|
|
85
98
|
* answer is Umbraco's: the login page for a visitor who is not signed in, the
|
|
@@ -269,8 +282,9 @@ export function createMemberAuth(
|
|
|
269
282
|
},
|
|
270
283
|
)
|
|
271
284
|
|
|
272
|
-
const
|
|
273
|
-
const
|
|
285
|
+
const session: MemberAuth['session'] = async (request) => {
|
|
286
|
+
const key = await secret()
|
|
287
|
+
const ticket = await readMemberTicket(key, readCookie(request, cookie))
|
|
274
288
|
if (!ticket) return undefined
|
|
275
289
|
const member = await members.byKey(ticket.id)
|
|
276
290
|
if (!member) return undefined
|
|
@@ -278,9 +292,15 @@ export function createMemberAuth(
|
|
|
278
292
|
// lockout rotates it, and every ticket issued before it is now worthless.
|
|
279
293
|
if ((member.securityStamp ?? '') !== ticket.stamp) return undefined
|
|
280
294
|
if (!member.isApproved || member.isLockedOut) return undefined
|
|
281
|
-
return
|
|
295
|
+
return {
|
|
296
|
+
member: asRequestMember(member),
|
|
297
|
+
antiforgery: await antiforgeryToken(key, ticket),
|
|
298
|
+
verify: (token) => verifyAntiforgery(key, ticket, token),
|
|
299
|
+
}
|
|
282
300
|
}
|
|
283
301
|
|
|
302
|
+
const resolve: MemberAuth['resolve'] = async (request) => (await session(request))?.member
|
|
303
|
+
|
|
284
304
|
const decide: MemberAuth['decide'] = async (content, member) => {
|
|
285
305
|
const entry = await access.entryFor(content.key)
|
|
286
306
|
if (!entry) return { status: 'allowed' }
|
|
@@ -562,6 +582,7 @@ export function createMemberAuth(
|
|
|
562
582
|
|
|
563
583
|
return {
|
|
564
584
|
resolve,
|
|
585
|
+
session,
|
|
565
586
|
decide,
|
|
566
587
|
signOutCookie: () => expireCookie(cookie, config.secureCookies),
|
|
567
588
|
externalSignInUrl: (providerId, returnUrl) =>
|
package/src/ports.ts
CHANGED
|
@@ -591,7 +591,8 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
591
591
|
},
|
|
592
592
|
events: createMediaEventSink({ webhooks: options.webhooks, nudge: options.nudgeEvents }),
|
|
593
593
|
files: mediaFiles,
|
|
594
|
-
|
|
594
|
+
// Only the items it touched: a media change leaves the pages alone (story 197).
|
|
595
|
+
onChange: (change) => options.cache?.media?.apply(change),
|
|
595
596
|
refusalReason: (error) =>
|
|
596
597
|
error instanceof TemporaryFileMissingError ? error.message : undefined,
|
|
597
598
|
})
|
|
@@ -672,9 +673,13 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
672
673
|
})
|
|
673
674
|
deps.searchIndex = createSearchIndexPort(options.db, options.onSearchQueued)
|
|
674
675
|
deps.publishedCache = {
|
|
675
|
-
reload: () =>
|
|
676
|
+
reload: () => {
|
|
677
|
+
cache.invalidate()
|
|
678
|
+
cache.media?.clear()
|
|
679
|
+
},
|
|
676
680
|
rebuild: async () => {
|
|
677
681
|
cache.invalidate()
|
|
682
|
+
cache.media?.clear()
|
|
678
683
|
await cache.snapshot()
|
|
679
684
|
},
|
|
680
685
|
isRebuilding: () => false,
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Request limits for a bundle's member and public routes (story 186): counted
|
|
3
|
+
* per server, in memory, in a sliding window, as sign-in throttling counts
|
|
4
|
+
* failures (`AttemptLimiter`). Behind N servers a site allows up to N times
|
|
5
|
+
* the limit in total.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Keys held before the idle ones are swept, so a flood of addresses cannot grow the map for ever. */
|
|
9
|
+
const SWEEP_AT = 10_000
|
|
10
|
+
|
|
11
|
+
export class RateLimiter {
|
|
12
|
+
#hits = new Map<string, number[]>()
|
|
13
|
+
readonly #max: number
|
|
14
|
+
readonly #windowMs: number
|
|
15
|
+
readonly #now: () => number
|
|
16
|
+
|
|
17
|
+
constructor(options: { max: number; windowMs: number; now?: () => number }) {
|
|
18
|
+
this.#max = options.max
|
|
19
|
+
this.#windowMs = options.windowMs
|
|
20
|
+
this.#now = options.now ?? Date.now
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Counts a request: undefined when it may go ahead, or the seconds until one may. */
|
|
24
|
+
take(key: string): number | undefined {
|
|
25
|
+
const now = this.#now()
|
|
26
|
+
const since = now - this.#windowMs
|
|
27
|
+
if (this.#hits.size >= SWEEP_AT)
|
|
28
|
+
for (const [held, times] of this.#hits)
|
|
29
|
+
if ((times.at(-1) ?? 0) <= since) this.#hits.delete(held)
|
|
30
|
+
const recent = (this.#hits.get(key) ?? []).filter((t) => t > since)
|
|
31
|
+
if (recent.length >= this.#max) {
|
|
32
|
+
this.#hits.set(key, recent)
|
|
33
|
+
return Math.max(1, Math.ceil(((recent[0] as number) + this.#windowMs - now) / 1000))
|
|
34
|
+
}
|
|
35
|
+
recent.push(now)
|
|
36
|
+
this.#hits.set(key, recent)
|
|
37
|
+
return undefined
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const PRIVATE_ADDRESS =
|
|
42
|
+
/^(?:::ffff:)?(?:127\.|10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.)|^(?:::1|f[cd][0-9a-f]{2}:|fe80:)/i
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The address a request came from. The socket's peer, unless that is a
|
|
46
|
+
* private address — a proxy or load balancer in front of the site — when the
|
|
47
|
+
* last `X-Forwarded-For` entry, the one that proxy added, is the caller.
|
|
48
|
+
* Earlier entries are the client's own to write, so they are never trusted.
|
|
49
|
+
*/
|
|
50
|
+
export function callerAddress(peer: string | undefined, forwardedFor: string | null): string {
|
|
51
|
+
const forwarded = forwardedFor?.split(',').at(-1)?.trim()
|
|
52
|
+
if (forwarded && (!peer || PRIVATE_ADDRESS.test(peer))) return forwarded
|
|
53
|
+
return peer ?? 'unknown'
|
|
54
|
+
}
|