@crombolo/server 0.34.0 → 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/package.json +12 -12
- 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/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 +347 -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'
|
|
@@ -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
|
+
}
|
package/src/schema.ts
CHANGED
|
@@ -16,6 +16,8 @@ import {
|
|
|
16
16
|
ensureSystemContentTypes,
|
|
17
17
|
ensureSystemMemberTypes,
|
|
18
18
|
type Finding,
|
|
19
|
+
instructionEffects,
|
|
20
|
+
instructionsBetween,
|
|
19
21
|
Locks,
|
|
20
22
|
latestCacheInstructionId,
|
|
21
23
|
latestCheckpoint,
|
|
@@ -251,12 +253,30 @@ export interface CachePollerOptions {
|
|
|
251
253
|
content?: {
|
|
252
254
|
served(): { checkpoint: number | undefined; builtAt: Date } | undefined
|
|
253
255
|
behind(latest: number): void
|
|
256
|
+
/**
|
|
257
|
+
* Told that every change from the one it serves up to `checkpoint` left the
|
|
258
|
+
* pages alone — media only (story 197) — so its snapshot holds them too.
|
|
259
|
+
*/
|
|
260
|
+
covered?(checkpoint: number): void
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* The media cache (story 197). Every change, this node's own included, is
|
|
264
|
+
* read in checkpoint order: a media change drops the items it names, and a
|
|
265
|
+
* change that empties caches empties it. A gap in the checkpoints, or being
|
|
266
|
+
* further behind than `MEDIA_REPLAY_LIMIT`, empties it too.
|
|
267
|
+
*/
|
|
268
|
+
media?: {
|
|
269
|
+
apply(change: { keys: string[]; moved: string[] }): void
|
|
270
|
+
clear(): void
|
|
254
271
|
}
|
|
255
272
|
}
|
|
256
273
|
|
|
257
274
|
/** A rebuild asked for and not yet served is asked for again after this long. */
|
|
258
275
|
const REASK_AFTER_MS = 30_000
|
|
259
276
|
|
|
277
|
+
/** Further behind than this many changes, the media cache is emptied rather than replayed. */
|
|
278
|
+
export const MEDIA_REPLAY_LIMIT = 5_000
|
|
279
|
+
|
|
260
280
|
/**
|
|
261
281
|
* Polls `cache_instruction` from where this node came in; own instructions are
|
|
262
282
|
* skipped. Where the database can notify, a write wakes it at once and the
|
|
@@ -283,6 +303,10 @@ export class CacheInstructionPoller {
|
|
|
283
303
|
/** The checkpoint this node last asked its cache to catch up to, and when. */
|
|
284
304
|
#asked: { checkpoint: number; at: number } | undefined
|
|
285
305
|
#latest: number | undefined
|
|
306
|
+
/** The checkpoint whose changes have all been read for the caches; undefined before the start. */
|
|
307
|
+
#followed: number | undefined
|
|
308
|
+
/** Checkpoints read whose changes left the pages alone. */
|
|
309
|
+
#pagesFree = new Set<number>()
|
|
286
310
|
|
|
287
311
|
/** The latest committed content checkpoint, as of the last poll. */
|
|
288
312
|
get latestCheckpoint(): number | undefined {
|
|
@@ -318,6 +342,8 @@ export class CacheInstructionPoller {
|
|
|
318
342
|
this.#paused = await readWritesPaused(this.#options.db)
|
|
319
343
|
this.#cursor = await latestCacheInstructionId(this.#options.db)
|
|
320
344
|
this.#origin = this.#cursor
|
|
345
|
+
// An empty media cache is current with whatever has committed so far.
|
|
346
|
+
this.#followed = await latestCheckpoint(this.#options.db)
|
|
321
347
|
if (intervalMs > 0) {
|
|
322
348
|
this.#timer = setInterval(() => void this.poll().catch(() => {}), intervalMs)
|
|
323
349
|
this.#timer.unref()
|
|
@@ -355,6 +381,8 @@ export class CacheInstructionPoller {
|
|
|
355
381
|
|
|
356
382
|
async #pollOnce(): Promise<number> {
|
|
357
383
|
const { db, nodeId, nodeState, onInstruction } = this.#options
|
|
384
|
+
// Read first: every instruction numbered up to it has committed, and is visible below.
|
|
385
|
+
const latest = await latestCheckpoint(db)
|
|
358
386
|
// A row can commit after one with a higher id (Postgres hands ids out
|
|
359
387
|
// before commit), so a short window behind the cursor is read again and
|
|
360
388
|
// the ids already seen are skipped.
|
|
@@ -371,7 +399,8 @@ export class CacheInstructionPoller {
|
|
|
371
399
|
onInstruction(instruction.kind, instruction.payload)
|
|
372
400
|
}
|
|
373
401
|
for (const id of this.#seen) if (id <= this.#cursor - CURSOR_WINDOW) this.#seen.delete(id)
|
|
374
|
-
|
|
402
|
+
await this.#follow(latest)
|
|
403
|
+
const served = this.#catchUp(latest)
|
|
375
404
|
await touchServer(db, {
|
|
376
405
|
nodeId,
|
|
377
406
|
...nodeState,
|
|
@@ -394,19 +423,60 @@ export class CacheInstructionPoller {
|
|
|
394
423
|
return applied
|
|
395
424
|
}
|
|
396
425
|
|
|
426
|
+
/**
|
|
427
|
+
* Reads every change since the last checkpoint followed, in order: for the
|
|
428
|
+
* media cache, and to know which left the pages alone. Checkpoints count up
|
|
429
|
+
* by one per change, so a number with no instruction was pruned before this
|
|
430
|
+
* node read it, and the media cache cannot know what it missed.
|
|
431
|
+
*/
|
|
432
|
+
async #follow(latest: number): Promise<void> {
|
|
433
|
+
const from = this.#followed
|
|
434
|
+
if (from === undefined || latest === from) return
|
|
435
|
+
const media = this.#options.media
|
|
436
|
+
this.#followed = latest
|
|
437
|
+
// Behind a reset count, or too far behind to replay: start the media again.
|
|
438
|
+
if (latest < from || latest - from > MEDIA_REPLAY_LIMIT) {
|
|
439
|
+
media?.clear()
|
|
440
|
+
this.#pagesFree.clear()
|
|
441
|
+
return
|
|
442
|
+
}
|
|
443
|
+
const missed = await instructionsBetween(this.#options.db, from, latest)
|
|
444
|
+
const numbered = new Set(missed.map((instruction) => instruction.checkpoint))
|
|
445
|
+
let gap = false
|
|
446
|
+
for (let checkpoint = from + 1; checkpoint <= latest && !gap; checkpoint++)
|
|
447
|
+
gap = !numbered.has(checkpoint)
|
|
448
|
+
if (gap) media?.clear()
|
|
449
|
+
for (const instruction of missed) {
|
|
450
|
+
const effects = instructionEffects(instruction.kind, instruction.payload)
|
|
451
|
+
if (!effects.pages && instruction.checkpoint !== null)
|
|
452
|
+
this.#pagesFree.add(instruction.checkpoint)
|
|
453
|
+
if (gap || !media || effects.media === 'keep') continue
|
|
454
|
+
if (effects.media === 'clear') media.clear()
|
|
455
|
+
else media.apply(effects.media)
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
397
459
|
/**
|
|
398
460
|
* Tells the cache it is behind when the latest committed checkpoint is past
|
|
399
|
-
* the one it serves
|
|
400
|
-
*
|
|
401
|
-
* failed rebuild is retried.
|
|
461
|
+
* the one it serves, and any changes between left pages alone. A cache that
|
|
462
|
+
* has not been built yet is left to build on its first read. A request not
|
|
463
|
+
* served within a while is made again, so a failed rebuild is retried.
|
|
402
464
|
*/
|
|
403
|
-
|
|
465
|
+
#catchUp(latest: number) {
|
|
404
466
|
const content = this.#options.content
|
|
405
467
|
if (!content) return undefined
|
|
406
|
-
const latest = await latestCheckpoint(this.#options.db)
|
|
407
468
|
this.#latest = latest
|
|
408
|
-
|
|
409
|
-
if (served?.checkpoint === undefined
|
|
469
|
+
let served = content.served()
|
|
470
|
+
if (served?.checkpoint === undefined) return served
|
|
471
|
+
let covered = served.checkpoint
|
|
472
|
+
while (this.#pagesFree.has(covered + 1)) covered += 1
|
|
473
|
+
for (const checkpoint of this.#pagesFree)
|
|
474
|
+
if (checkpoint <= covered) this.#pagesFree.delete(checkpoint)
|
|
475
|
+
if (covered > served.checkpoint) {
|
|
476
|
+
content.covered?.(covered)
|
|
477
|
+
served = content.served() ?? served
|
|
478
|
+
}
|
|
479
|
+
if (covered >= latest) return served
|
|
410
480
|
const asked = this.#asked
|
|
411
481
|
if (!asked || asked.checkpoint < latest || Date.now() - asked.at > REASK_AFTER_MS) {
|
|
412
482
|
this.#asked = { checkpoint: latest, at: Date.now() }
|