@crombolo/server 0.65.1 → 0.67.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +15 -14
- package/src/adapters/blueprints.ts +19 -5
- package/src/adapters/elements.ts +49 -36
- package/src/adapters/members.ts +53 -5
- package/src/adapters/users.ts +18 -0
- package/src/approvals.ts +21 -0
- package/src/atomic-write.ts +2 -2
- package/src/background-jobs.ts +170 -0
- package/src/cli-tokens-api.ts +158 -0
- package/src/config.ts +52 -1
- package/src/content-events.ts +22 -0
- package/src/content-operations.ts +26 -1
- package/src/extension-activity.ts +121 -0
- package/src/external-sign-in.ts +8 -2
- package/src/identity-providers.ts +44 -1
- package/src/index.ts +14 -0
- package/src/media-access.ts +30 -125
- package/src/media-library.ts +953 -0
- package/src/member-admin.ts +761 -0
- package/src/node-operations.ts +19 -2
- package/src/ports.ts +2 -0
- package/src/principal.ts +36 -0
- package/src/remote-background-jobs.ts +99 -0
- package/src/remote-ci.ts +34 -26
- package/src/remote-credentials.ts +114 -6
- package/src/remote-extension-activity.ts +66 -0
- package/src/remote-media-library.ts +297 -0
- package/src/remote-media.ts +2 -2
- package/src/remote-members.ts +271 -0
- package/src/remote-people.ts +269 -0
- package/src/remote-undo.ts +234 -0
- package/src/remote-users.ts +229 -0
- package/src/remote.ts +174 -10
- package/src/seed/values.ts +82 -4
- package/src/seo.ts +81 -61
- package/src/server.ts +191 -94
- package/src/settings.ts +93 -0
- package/src/undo.ts +358 -0
- package/src/user-admin.ts +581 -0
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A person signed in through a provider reaches the remote (story 364): a token
|
|
3
|
+
* one of the site's own back-office providers issued for the remote, exchanged
|
|
4
|
+
* (RFC 8693) at the same endpoint as CI's for a fifteen-minute sign-in as the
|
|
5
|
+
* person it names. The provider must opt in from the config or the server, the
|
|
6
|
+
* token's `aud` must be the audience it names and never a sign-in client id,
|
|
7
|
+
* and the person is found by the claim that names them across the provider's
|
|
8
|
+
* apps, as their last sign-in recorded it. docs/remote-protocol.md, "Signing
|
|
9
|
+
* in as a person through a provider".
|
|
10
|
+
*/
|
|
11
|
+
import {
|
|
12
|
+
type Db,
|
|
13
|
+
ExternalLoginRepository,
|
|
14
|
+
externalLoginProvider,
|
|
15
|
+
RemoteExchangeIds,
|
|
16
|
+
} from '@crombolo/data'
|
|
17
|
+
import { type JWTPayload, jwtVerify } from 'jose'
|
|
18
|
+
import { type ExternalAccount, syncedGroups } from './external-sign-in.ts'
|
|
19
|
+
import type { IdentityProvider } from './identity-providers.ts'
|
|
20
|
+
import {
|
|
21
|
+
ACCESS_TOKEN_TYPE,
|
|
22
|
+
issuerKeys,
|
|
23
|
+
JWT_TOKEN_TYPE,
|
|
24
|
+
overHttps,
|
|
25
|
+
TOKEN_EXCHANGE_GRANT,
|
|
26
|
+
unverifiedIssuer,
|
|
27
|
+
usableIssuer,
|
|
28
|
+
} from './remote-ci.ts'
|
|
29
|
+
import { AttemptLimiter } from './setup.ts'
|
|
30
|
+
|
|
31
|
+
/** How long an exchanged sign-in lasts. There is no refresh: the holder exchanges again. */
|
|
32
|
+
export const PERSON_TOKEN_SECONDS = 15 * 60
|
|
33
|
+
/** A provider's token valid for longer than this is refused; Entra's last 60 to 90 minutes. */
|
|
34
|
+
export const MAX_PROVIDER_TOKEN_SECONDS = 90 * 60
|
|
35
|
+
|
|
36
|
+
const ASYMMETRIC = ['RS256', 'RS384', 'RS512', 'PS256', 'PS384', 'PS512', 'ES256', 'ES384', 'ES512']
|
|
37
|
+
|
|
38
|
+
const text = (claims: JWTPayload, name: string | undefined): string | undefined => {
|
|
39
|
+
const value = name ? claims[name] : undefined
|
|
40
|
+
return typeof value === 'string' && value !== '' ? value : undefined
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const list = (claims: JWTPayload, name: string | undefined): string[] => {
|
|
44
|
+
const value = name ? claims[name] : undefined
|
|
45
|
+
if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string')
|
|
46
|
+
return typeof value === 'string' && value !== '' ? [value] : []
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The person-side of the site the exchange needs: back-office users, as sign-in finds them. */
|
|
50
|
+
export interface ExchangeAccounts {
|
|
51
|
+
byKey(key: string): Promise<ExternalAccount | undefined>
|
|
52
|
+
byEmail(email: string): Promise<ExternalAccount | undefined>
|
|
53
|
+
setGroups(account: ExternalAccount, groups: string[]): Promise<void>
|
|
54
|
+
/** Why the person may not sign in now: locked out, disabled, or with no back-office section. */
|
|
55
|
+
refusal(key: string): Promise<string | undefined>
|
|
56
|
+
/** Signs them in as a device of their own, or says why not. */
|
|
57
|
+
signIn(
|
|
58
|
+
key: string,
|
|
59
|
+
provider: { id: string; name: string },
|
|
60
|
+
seconds: number,
|
|
61
|
+
ip: string | undefined,
|
|
62
|
+
): Promise<{ accessToken: string } | { refused: string }>
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export type PeopleExchangeOutcome =
|
|
66
|
+
| { ok: true; provider: IdentityProvider; account: ExternalAccount }
|
|
67
|
+
| { ok: false; reason: string; provider?: IdentityProvider }
|
|
68
|
+
|
|
69
|
+
export interface PeopleExchange {
|
|
70
|
+
/** What the discovery document says, when any provider exchanges. */
|
|
71
|
+
discovery(origin: string, api: string): Promise<Record<string, unknown> | undefined>
|
|
72
|
+
/** Whether a token's issuer is an exchanging provider's, so this exchange answers it. */
|
|
73
|
+
handles(issuer: string): Promise<boolean>
|
|
74
|
+
exchange(request: Request, url: URL, ip: string | undefined): Promise<Response>
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function createPeopleExchange(options: {
|
|
78
|
+
db: Db
|
|
79
|
+
/** The providers that exchange, as declared. */
|
|
80
|
+
providers: readonly IdentityProvider[]
|
|
81
|
+
/** Every back-office provider, as declared: none of their client ids is ever an audience. */
|
|
82
|
+
backoffice: readonly IdentityProvider[]
|
|
83
|
+
/** A provider as sign-in uses it, with an administrator's overrides (033). */
|
|
84
|
+
resolve(provider: IdentityProvider): Promise<IdentityProvider>
|
|
85
|
+
accounts: ExchangeAccounts
|
|
86
|
+
/** Told of each exchange, accepted or refused, for the audit log. */
|
|
87
|
+
onExchange(outcome: PeopleExchangeOutcome, request: Request): Promise<void>
|
|
88
|
+
}): PeopleExchange {
|
|
89
|
+
const logins = new ExternalLoginRepository(options.db)
|
|
90
|
+
const ids = new RemoteExchangeIds(options.db)
|
|
91
|
+
const keysOf = issuerKeys()
|
|
92
|
+
const limiter = new AttemptLimiter({ max: 10, maxAll: 200, windowMs: 15 * 60_000 })
|
|
93
|
+
|
|
94
|
+
const effective = () =>
|
|
95
|
+
Promise.all(
|
|
96
|
+
options.providers.map(async (declared) => {
|
|
97
|
+
const provider = await options.resolve(declared).catch(() => declared)
|
|
98
|
+
return { ...provider, remoteExchange: declared.remoteExchange }
|
|
99
|
+
}),
|
|
100
|
+
)
|
|
101
|
+
const issuerOf = (provider: IdentityProvider) => provider.oidc.issuer.replace(/\/+$/, '')
|
|
102
|
+
const audienceOf = (provider: IdentityProvider, origin: string) =>
|
|
103
|
+
provider.remoteExchange?.audience ?? origin
|
|
104
|
+
const usable = (provider: IdentityProvider) =>
|
|
105
|
+
!provider.unavailable && usableIssuer(issuerOf(provider))
|
|
106
|
+
|
|
107
|
+
const json = (body: unknown, status: number) =>
|
|
108
|
+
Response.json(body, { status, headers: { 'cache-control': 'no-store' } })
|
|
109
|
+
|
|
110
|
+
const refuse = async (
|
|
111
|
+
request: Request,
|
|
112
|
+
ip: string | undefined,
|
|
113
|
+
reason: string,
|
|
114
|
+
provider?: IdentityProvider,
|
|
115
|
+
) => {
|
|
116
|
+
limiter.fail(`ip:${ip ?? 'unknown'}`)
|
|
117
|
+
if (provider) limiter.fail(`issuer:${issuerOf(provider)}`)
|
|
118
|
+
await options.onExchange({ ok: false, reason, provider }, request)
|
|
119
|
+
// The same answer whatever went wrong: the audit log has the reason, the caller does not.
|
|
120
|
+
return json(
|
|
121
|
+
{ error: 'invalid_grant', error_description: 'The identity token was not accepted.' },
|
|
122
|
+
400,
|
|
123
|
+
)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The account the token names: by its recorded identity, else by email where allowed. */
|
|
127
|
+
const accountFor = async (
|
|
128
|
+
provider: IdentityProvider,
|
|
129
|
+
issuer: string,
|
|
130
|
+
claims: JWTPayload,
|
|
131
|
+
): Promise<ExternalAccount | string> => {
|
|
132
|
+
const loginProvider = externalLoginProvider('user', provider.oidc.id)
|
|
133
|
+
const value = text(claims, provider.oidc.claims.identity ?? 'sub')
|
|
134
|
+
if (!value) return 'the token names no person'
|
|
135
|
+
const linked = await logins.findByIdentity(loginProvider, { value, issuer })
|
|
136
|
+
if (linked) {
|
|
137
|
+
const account = await options.accounts.byKey(linked.ownerKey)
|
|
138
|
+
return account ?? 'the person it is linked to no longer exists'
|
|
139
|
+
}
|
|
140
|
+
// Story 364, D5: never an account made, and a link is only ever made by a sign-in.
|
|
141
|
+
const email = text(claims, provider.oidc.claims.email)?.toLowerCase()
|
|
142
|
+
const verified = claims.email_verified === true || claims.email_verified === 'true'
|
|
143
|
+
if (!provider.linkByEmail || !email || !(verified || provider.emailsVerified))
|
|
144
|
+
return 'nobody is linked to this person; they sign in to the back office once first'
|
|
145
|
+
const sameEmail = await options.accounts.byEmail(email)
|
|
146
|
+
if (!sameEmail) return 'nobody here has their email address, and an exchange makes no account'
|
|
147
|
+
const links = await logins.forOwner(sameEmail.key)
|
|
148
|
+
if (links.some((l) => l.loginProvider === loginProvider))
|
|
149
|
+
return 'the account with their email is linked to someone else at this provider'
|
|
150
|
+
return sameEmail
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return {
|
|
154
|
+
async discovery(origin, api) {
|
|
155
|
+
const providers = (await effective()).filter(usable)
|
|
156
|
+
if (providers.length === 0) return undefined
|
|
157
|
+
return {
|
|
158
|
+
tokenExchange: `${api}/token`,
|
|
159
|
+
grantType: TOKEN_EXCHANGE_GRANT,
|
|
160
|
+
subjectTokenType: JWT_TOKEN_TYPE,
|
|
161
|
+
audience: origin,
|
|
162
|
+
providers: providers.map((p) => ({
|
|
163
|
+
id: p.oidc.id,
|
|
164
|
+
name: p.oidc.name,
|
|
165
|
+
issuer: issuerOf(p),
|
|
166
|
+
audience: audienceOf(p, origin),
|
|
167
|
+
})),
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
|
|
171
|
+
async handles(issuer) {
|
|
172
|
+
return (await effective()).some((p) => usable(p) && issuerOf(p) === issuer)
|
|
173
|
+
},
|
|
174
|
+
|
|
175
|
+
async exchange(request, url, ip) {
|
|
176
|
+
if (!overHttps(request, url))
|
|
177
|
+
return json(
|
|
178
|
+
{ error: 'invalid_request', error_description: 'Signing in from elsewhere needs HTTPS.' },
|
|
179
|
+
400,
|
|
180
|
+
)
|
|
181
|
+
if (limiter.blocked(`ip:${ip ?? 'unknown'}`))
|
|
182
|
+
return json({ error: 'slow_down', error_description: 'Too many refused tokens.' }, 429)
|
|
183
|
+
const form = new URLSearchParams(await request.text())
|
|
184
|
+
if (form.get('grant_type') !== TOKEN_EXCHANGE_GRANT)
|
|
185
|
+
return json({ error: 'unsupported_grant_type' }, 400)
|
|
186
|
+
if (form.get('subject_token_type') !== JWT_TOKEN_TYPE)
|
|
187
|
+
return json({ error: 'invalid_request', error_description: 'A JWT is expected.' }, 400)
|
|
188
|
+
const token = form.get('subject_token') ?? ''
|
|
189
|
+
|
|
190
|
+
const issuer = unverifiedIssuer(token)
|
|
191
|
+
const provider = (await effective()).find((p) => usable(p) && issuerOf(p) === issuer)
|
|
192
|
+
if (!issuer || !provider)
|
|
193
|
+
return refuse(request, ip, 'an issuer that is not an exchanging provider')
|
|
194
|
+
if (limiter.blocked(`issuer:${issuer}`))
|
|
195
|
+
return json({ error: 'slow_down', error_description: 'Too many refused tokens.' }, 429)
|
|
196
|
+
|
|
197
|
+
const audience = audienceOf(provider, url.origin)
|
|
198
|
+
const signInClients = await Promise.all(
|
|
199
|
+
options.backoffice.map(
|
|
200
|
+
async (p) => (await options.resolve(p).catch(() => p)).oidc.clientId,
|
|
201
|
+
),
|
|
202
|
+
)
|
|
203
|
+
if (signInClients.includes(audience))
|
|
204
|
+
return refuse(request, ip, 'its audience is a sign-in client id', provider)
|
|
205
|
+
|
|
206
|
+
let claims: JWTPayload
|
|
207
|
+
try {
|
|
208
|
+
;({ payload: claims } = await jwtVerify(token, await keysOf(issuer), {
|
|
209
|
+
issuer,
|
|
210
|
+
audience,
|
|
211
|
+
algorithms: ASYMMETRIC,
|
|
212
|
+
requiredClaims: ['exp', 'iat'],
|
|
213
|
+
}))
|
|
214
|
+
} catch (error) {
|
|
215
|
+
return refuse(
|
|
216
|
+
request,
|
|
217
|
+
ip,
|
|
218
|
+
`the token did not verify: ${error instanceof Error ? error.message : String(error)}`,
|
|
219
|
+
provider,
|
|
220
|
+
)
|
|
221
|
+
}
|
|
222
|
+
if (claims.nonce !== undefined)
|
|
223
|
+
return refuse(request, ip, 'it is a sign-in ID token, which carries a nonce', provider)
|
|
224
|
+
const exp = claims.exp as number
|
|
225
|
+
if (exp - (claims.iat as number) > MAX_PROVIDER_TOKEN_SECONDS)
|
|
226
|
+
return refuse(request, ip, 'the token is valid for too long', provider)
|
|
227
|
+
// Entra calls its one-time id `uti`.
|
|
228
|
+
const tokenId = text(claims, 'jti') ?? text(claims, 'uti')
|
|
229
|
+
if (!tokenId) return refuse(request, ip, 'the token has no one-time id', provider)
|
|
230
|
+
if (!(await ids.spend(issuer, tokenId, new Date(exp * 1000))))
|
|
231
|
+
return refuse(request, ip, 'the token was already used', provider)
|
|
232
|
+
|
|
233
|
+
const found = await accountFor(provider, issuer, claims)
|
|
234
|
+
if (typeof found === 'string') return refuse(request, ip, found, provider)
|
|
235
|
+
const refusal = await options.accounts.refusal(found.key)
|
|
236
|
+
if (refusal) return refuse(request, ip, refusal, provider)
|
|
237
|
+
|
|
238
|
+
let account = found
|
|
239
|
+
if (Object.keys(provider.groupMap).length > 0) {
|
|
240
|
+
const groups = syncedGroups(
|
|
241
|
+
account.groups,
|
|
242
|
+
list(claims, provider.oidc.claims.groups),
|
|
243
|
+
provider.groupMap,
|
|
244
|
+
)
|
|
245
|
+
if (groups.join('\n') !== account.groups.join('\n')) {
|
|
246
|
+
await options.accounts.setGroups(account, groups)
|
|
247
|
+
account = { ...account, groups }
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const signedIn = await options.accounts.signIn(
|
|
251
|
+
account.key,
|
|
252
|
+
{ id: provider.oidc.id, name: provider.oidc.name },
|
|
253
|
+
PERSON_TOKEN_SECONDS,
|
|
254
|
+
ip,
|
|
255
|
+
)
|
|
256
|
+
if ('refused' in signedIn) return refuse(request, ip, signedIn.refused, provider)
|
|
257
|
+
await options.onExchange({ ok: true, provider, account }, request)
|
|
258
|
+
return json(
|
|
259
|
+
{
|
|
260
|
+
access_token: signedIn.accessToken,
|
|
261
|
+
issued_token_type: ACCESS_TOKEN_TYPE,
|
|
262
|
+
token_type: 'Bearer',
|
|
263
|
+
expires_in: PERSON_TOKEN_SECONDS,
|
|
264
|
+
},
|
|
265
|
+
200,
|
|
266
|
+
)
|
|
267
|
+
},
|
|
268
|
+
}
|
|
269
|
+
}
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The remote protocol's routes for undoing a change (story 353): a page's
|
|
3
|
+
* history, a version shown, rolled back and kept, and the recycle bin listed and
|
|
4
|
+
* restored from. Each answers as the signed-in person, through the operations the
|
|
5
|
+
* back office's handlers use; CI is refused, since these act for a person.
|
|
6
|
+
*/
|
|
7
|
+
import { hasSection, type Principal } from '@crombolo/api-management/domain'
|
|
8
|
+
import {
|
|
9
|
+
type DocumentOperations,
|
|
10
|
+
MEDIA_JOBS,
|
|
11
|
+
type MediaOperations,
|
|
12
|
+
type Refusal,
|
|
13
|
+
userActor,
|
|
14
|
+
} from '@crombolo/content'
|
|
15
|
+
import { type Db, DocumentRepository, JobRepository } from '@crombolo/data'
|
|
16
|
+
import {
|
|
17
|
+
type BinItem,
|
|
18
|
+
type BinKind,
|
|
19
|
+
binItems,
|
|
20
|
+
pageHistory,
|
|
21
|
+
pageVersion,
|
|
22
|
+
placeGone,
|
|
23
|
+
} from './undo.ts'
|
|
24
|
+
|
|
25
|
+
interface Problem {
|
|
26
|
+
code: string
|
|
27
|
+
title: string
|
|
28
|
+
detail?: string
|
|
29
|
+
items?: string[]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface UndoRouteOptions {
|
|
33
|
+
db: Db
|
|
34
|
+
operations: { documents: DocumentOperations; media: MediaOperations }
|
|
35
|
+
problem(status: number, body: Problem): Response
|
|
36
|
+
/** A refusal when the site's remote access level takes no changes to content. */
|
|
37
|
+
levelRefusal(): Response | undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
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}'
|
|
41
|
+
const UUID = new RegExp(`^${KEY}$`)
|
|
42
|
+
const SECTION: Record<BinKind, 'content' | 'media'> = { content: 'content', media: 'media' }
|
|
43
|
+
|
|
44
|
+
const CODES: Partial<Record<Refusal['kind'], string>> = {
|
|
45
|
+
notFound: 'not-found',
|
|
46
|
+
forbidden: 'forbidden',
|
|
47
|
+
needsApproval: 'needs-approval',
|
|
48
|
+
invalid: 'invalid',
|
|
49
|
+
conflict: 'conflict',
|
|
50
|
+
blocked: 'blocked',
|
|
51
|
+
validation: 'invalid',
|
|
52
|
+
stale: 'conflict',
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const body = async (request: Request): Promise<Record<string, unknown>> => {
|
|
56
|
+
const read = await request.json().catch(() => ({}))
|
|
57
|
+
return read && typeof read === 'object' ? (read as Record<string, unknown>) : {}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function createUndoRoutes(options: UndoRouteOptions) {
|
|
61
|
+
const { db, operations, problem } = options
|
|
62
|
+
const refused = (
|
|
63
|
+
result: Refusal & { blocked?: Array<{ key: string; reasons: string[] }> },
|
|
64
|
+
): Response =>
|
|
65
|
+
problem(result.kind === 'needsApproval' ? 409 : result.status || 400, {
|
|
66
|
+
code: CODES[result.kind] ?? 'refused',
|
|
67
|
+
title: result.reason,
|
|
68
|
+
...(result.blocked ? { items: result.blocked.flatMap((b) => b.reasons) } : {}),
|
|
69
|
+
})
|
|
70
|
+
const actorOf = (principal: Principal, request: Request, skipApproval = false) =>
|
|
71
|
+
userActor(
|
|
72
|
+
principal,
|
|
73
|
+
{ source: 'request', forwardedFor: request.headers.get('x-forwarded-for') },
|
|
74
|
+
{ skipApproval },
|
|
75
|
+
)
|
|
76
|
+
const notHere = (title: string) => problem(404, { code: 'not-found', title })
|
|
77
|
+
const noSection = (what: string) =>
|
|
78
|
+
problem(403, { code: 'forbidden', title: `You may not ${what} here` })
|
|
79
|
+
|
|
80
|
+
async function rollback(request: Request, principal: Principal, id: string) {
|
|
81
|
+
const level = options.levelRefusal()
|
|
82
|
+
if (level) return level
|
|
83
|
+
const asked = await body(request)
|
|
84
|
+
const publish = asked.publish === true
|
|
85
|
+
const skipApproval = asked.skipApproval === true
|
|
86
|
+
if (skipApproval && !principal.isAdmin)
|
|
87
|
+
return problem(403, { code: 'forbidden', title: 'Only an administrator can skip approval' })
|
|
88
|
+
const version = await pageVersion(db, id)
|
|
89
|
+
if (!version) return notHere('There is no such version')
|
|
90
|
+
const actor = actorOf(principal, request, skipApproval)
|
|
91
|
+
const rolled = await operations.documents.rollback(actor, id, { overwrite: true })
|
|
92
|
+
if (!rolled.ok) return refused(rolled)
|
|
93
|
+
if (publish) {
|
|
94
|
+
const published = await operations.documents.publishMany(
|
|
95
|
+
actor,
|
|
96
|
+
[version.page.key],
|
|
97
|
+
null,
|
|
98
|
+
'publish',
|
|
99
|
+
)
|
|
100
|
+
if (!published.ok)
|
|
101
|
+
return refused({
|
|
102
|
+
...published,
|
|
103
|
+
reason: `It was rolled back to a draft, and not published: ${published.reason}`,
|
|
104
|
+
})
|
|
105
|
+
}
|
|
106
|
+
return Response.json({ page: version.page, version: id, published: publish })
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function keep(request: Request, id: string) {
|
|
110
|
+
const level = options.levelRefusal()
|
|
111
|
+
if (level) return level
|
|
112
|
+
const keeping = (await body(request)).keep !== false
|
|
113
|
+
if (!(await pageVersion(db, id))) return notHere('There is no such version')
|
|
114
|
+
await new DocumentRepository(db).setPreventCleanup(id, keeping)
|
|
115
|
+
return Response.json({ version: id, kept: keeping })
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const kindsFor = (principal: Principal, asked: string | null): BinKind[] | Response => {
|
|
119
|
+
const held = (['content', 'media'] as const).filter((kind) =>
|
|
120
|
+
hasSection(principal, SECTION[kind]),
|
|
121
|
+
)
|
|
122
|
+
if (asked === 'content' || asked === 'media')
|
|
123
|
+
return held.includes(asked) ? [asked] : noSection(`see the ${asked} recycle bin`)
|
|
124
|
+
if (asked) return problem(400, { code: 'bad-query', title: 'kind is content or media' })
|
|
125
|
+
return held.length > 0 ? held : noSection('see the recycle bin')
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function restore(request: Request, principal: Principal, key: string) {
|
|
129
|
+
const level = options.levelRefusal()
|
|
130
|
+
if (level) return level
|
|
131
|
+
const item = (await binItems(db)).find((candidate) => candidate.key === key.toLowerCase())
|
|
132
|
+
if (!item) return notHere('That is not in the recycle bin')
|
|
133
|
+
if (!hasSection(principal, SECTION[item.kind]))
|
|
134
|
+
return noSection(`restore ${item.kind === 'media' ? 'media' : 'pages'}`)
|
|
135
|
+
const asked = await body(request)
|
|
136
|
+
const target = asked.target
|
|
137
|
+
if (
|
|
138
|
+
target !== undefined &&
|
|
139
|
+
target !== null &&
|
|
140
|
+
!(typeof target === 'string' && UUID.test(target))
|
|
141
|
+
)
|
|
142
|
+
return problem(400, { code: 'bad-key', title: 'target is a key, or null for the top level' })
|
|
143
|
+
const gone = placeGone(item)
|
|
144
|
+
if (target === undefined && gone)
|
|
145
|
+
return problem(409, {
|
|
146
|
+
code: 'place-gone',
|
|
147
|
+
title: gone,
|
|
148
|
+
detail: 'Name another place to restore it to.',
|
|
149
|
+
})
|
|
150
|
+
const actor = actorOf(principal, request)
|
|
151
|
+
const to = target === undefined ? undefined : (target as string | null)
|
|
152
|
+
const done =
|
|
153
|
+
item.kind === 'media'
|
|
154
|
+
? await operations.media.restore(actor, item.key, to)
|
|
155
|
+
: await operations.documents.restore(actor, item.key, to)
|
|
156
|
+
if (!done.ok) return refused(done)
|
|
157
|
+
const queued = (done as { queued?: string }).queued
|
|
158
|
+
if (queued) return Response.json({ item: described(item), queued }, { status: 202 })
|
|
159
|
+
return Response.json({ item: described(item), restored: true })
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const described = (item: BinItem) => ({ key: item.key, name: item.name, kind: item.kind })
|
|
163
|
+
|
|
164
|
+
async function restoreJob(principal: Principal, id: string) {
|
|
165
|
+
if (!hasSection(principal, 'media')) return noSection('restore media')
|
|
166
|
+
const job = await new JobRepository(db).get(id)
|
|
167
|
+
if (!job || job.name !== MEDIA_JOBS.restore) return notHere('There is no such restore')
|
|
168
|
+
return Response.json({
|
|
169
|
+
state: job.state,
|
|
170
|
+
progress: job.progress,
|
|
171
|
+
error: job.state === 'failed' ? job.lastError : null,
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
/** Answers one of these routes, or undefined when `what` is none of them. */
|
|
177
|
+
async handle(
|
|
178
|
+
request: Request,
|
|
179
|
+
url: URL,
|
|
180
|
+
principal: Principal,
|
|
181
|
+
what: string,
|
|
182
|
+
): Promise<Response | undefined> {
|
|
183
|
+
const history = new RegExp(`^content/(${KEY})/history$`).exec(what)
|
|
184
|
+
const version = /^content\/versions\/(\d+)(?:\/(rollback|keep))?$/.exec(what)
|
|
185
|
+
const bin = new RegExp(`^recycle-bin(?:/(${KEY})/restore|/jobs/(${KEY}))?$`).exec(what)
|
|
186
|
+
if (!history && !version && !bin) return undefined
|
|
187
|
+
if (principal.ci)
|
|
188
|
+
return problem(403, {
|
|
189
|
+
code: 'needs-person',
|
|
190
|
+
title: 'Undoing a change needs a person',
|
|
191
|
+
detail: 'Sign in as yourself: CI cannot do this.',
|
|
192
|
+
})
|
|
193
|
+
const method = request.method
|
|
194
|
+
if (history || version) {
|
|
195
|
+
if (!hasSection(principal, 'content')) return noSection('see the history of pages')
|
|
196
|
+
if (history && method === 'GET') {
|
|
197
|
+
const found = await pageHistory(db, history[1] as string)
|
|
198
|
+
return found ? Response.json(found) : notHere('There is no such page')
|
|
199
|
+
}
|
|
200
|
+
const [, id, action] = version as unknown as [string, string, string | undefined]
|
|
201
|
+
if (!action && method === 'GET') {
|
|
202
|
+
const shown = await pageVersion(db, id, { diff: url.searchParams.get('diff') === 'true' })
|
|
203
|
+
return shown ? Response.json(shown) : notHere('There is no such version')
|
|
204
|
+
}
|
|
205
|
+
if (action === 'rollback' && method === 'POST') return rollback(request, principal, id)
|
|
206
|
+
if (action === 'keep' && method === 'PUT') return keep(request, id)
|
|
207
|
+
return new Response(null, { status: 405 })
|
|
208
|
+
}
|
|
209
|
+
const [, restoreKey, jobId] = bin as unknown as [
|
|
210
|
+
string,
|
|
211
|
+
string | undefined,
|
|
212
|
+
string | undefined,
|
|
213
|
+
]
|
|
214
|
+
if (restoreKey)
|
|
215
|
+
return method === 'POST'
|
|
216
|
+
? restore(request, principal, restoreKey)
|
|
217
|
+
: new Response(null, { status: 405 })
|
|
218
|
+
if (jobId)
|
|
219
|
+
return method === 'GET' ? restoreJob(principal, jobId) : new Response(null, { status: 405 })
|
|
220
|
+
if (method !== 'GET') return new Response(null, { status: 405 })
|
|
221
|
+
const kinds = kindsFor(principal, url.searchParams.get('kind'))
|
|
222
|
+
if (kinds instanceof Response) return kinds
|
|
223
|
+
const days = url.searchParams.get('olderThan')
|
|
224
|
+
if (days !== null && !/^\d+$/.test(days))
|
|
225
|
+
return problem(400, { code: 'bad-query', title: 'olderThan is a whole number of days' })
|
|
226
|
+
return Response.json({
|
|
227
|
+
items: await binItems(db, {
|
|
228
|
+
kinds,
|
|
229
|
+
...(days !== null ? { olderThanDays: Number(days) } : {}),
|
|
230
|
+
}),
|
|
231
|
+
})
|
|
232
|
+
},
|
|
233
|
+
}
|
|
234
|
+
}
|