@crombolo/api-delivery 0.20.0 → 0.22.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 +4 -4
- package/src/cors.ts +101 -0
- package/src/forms.ts +126 -0
- package/src/handler.ts +472 -54
- package/src/index.ts +2 -0
- package/src/output.ts +10 -0
- package/src/settings.ts +76 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/api-delivery",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.0",
|
|
4
4
|
"description": "Umbraco's Content Delivery API for crombolo: published content and media as JSON, served from the published cache.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Crombolo",
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"access": "public"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@crombolo/core": "0.
|
|
32
|
-
"@crombolo/contracts": "0.
|
|
33
|
-
"@crombolo/render": "0.
|
|
31
|
+
"@crombolo/core": "0.22.0",
|
|
32
|
+
"@crombolo/contracts": "0.22.0",
|
|
33
|
+
"@crombolo/render": "0.22.0"
|
|
34
34
|
}
|
|
35
35
|
}
|
package/src/cors.ts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-origin access to the Delivery API, so an app on another origin can call
|
|
3
|
+
* it from the browser. docs/delivery-api.md, "Requests from another origin".
|
|
4
|
+
*/
|
|
5
|
+
import type { DeliveryApiSettings } from './settings.ts'
|
|
6
|
+
|
|
7
|
+
export interface CorsPolicy {
|
|
8
|
+
/** Exact origins allowed, lower case, as `URL.origin` writes them. */
|
|
9
|
+
origins: ReadonlySet<string>
|
|
10
|
+
/** `*` was listed and the API is public. */
|
|
11
|
+
any: boolean
|
|
12
|
+
/** Configured origins that were ignored, said once at boot. */
|
|
13
|
+
problems: string[]
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The headers the API reads from a caller; a pre-flight allows exactly these. */
|
|
17
|
+
export const CORS_ALLOWED_HEADERS =
|
|
18
|
+
'Accept-Language, Api-Key, Authorization, Content-Type, Preview, Preview-Token, Start-Item'
|
|
19
|
+
|
|
20
|
+
const MAX_AGE_SECONDS = '600'
|
|
21
|
+
|
|
22
|
+
/** The configured origins, checked: a path, query or missing scheme is a problem. Pure. */
|
|
23
|
+
export function corsPolicy(settings: DeliveryApiSettings): CorsPolicy {
|
|
24
|
+
const origins = new Set<string>()
|
|
25
|
+
const problems: string[] = []
|
|
26
|
+
let any = false
|
|
27
|
+
for (const raw of settings.cors.allowedOrigins) {
|
|
28
|
+
const value = raw.trim()
|
|
29
|
+
if (value === '*') {
|
|
30
|
+
if (settings.publicAccess) any = true
|
|
31
|
+
else
|
|
32
|
+
problems.push(
|
|
33
|
+
'An allowed origin of "*" is ignored because the Delivery API is not public; list each origin instead.',
|
|
34
|
+
)
|
|
35
|
+
continue
|
|
36
|
+
}
|
|
37
|
+
const origin = originOf(value)
|
|
38
|
+
if (origin) origins.add(origin)
|
|
39
|
+
else
|
|
40
|
+
problems.push(
|
|
41
|
+
`The allowed origin "${value}" is ignored: it must be a scheme and host, such as https://app.example.com, with no path.`,
|
|
42
|
+
)
|
|
43
|
+
}
|
|
44
|
+
return { origins, any, problems }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function originOf(value: string): string | undefined {
|
|
48
|
+
if (!/^https?:\/\//i.test(value)) return undefined
|
|
49
|
+
try {
|
|
50
|
+
const url = new URL(value)
|
|
51
|
+
if (url.pathname !== '/' || url.search || url.hash || url.username || url.password)
|
|
52
|
+
return undefined
|
|
53
|
+
if (value.replace(/\/$/, '').toLowerCase() !== url.origin.toLowerCase()) return undefined
|
|
54
|
+
return url.origin.toLowerCase()
|
|
55
|
+
} catch {
|
|
56
|
+
return undefined
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The `Access-Control-Allow-Origin` value for a request, or none. Pure. */
|
|
61
|
+
export function allowedOrigin(policy: CorsPolicy, request: Request): string | undefined {
|
|
62
|
+
const origin = request.headers.get('origin')
|
|
63
|
+
if (!origin) return undefined
|
|
64
|
+
if (policy.origins.has(origin.toLowerCase())) return origin
|
|
65
|
+
return policy.any ? '*' : undefined
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A browser's pre-flight: `OPTIONS` naming the method it means to send. Pure. */
|
|
69
|
+
export const isPreflight = (request: Request): boolean =>
|
|
70
|
+
request.method === 'OPTIONS' &&
|
|
71
|
+
request.headers.has('origin') &&
|
|
72
|
+
request.headers.has('access-control-request-method')
|
|
73
|
+
|
|
74
|
+
/** The answer to a pre-flight; with no allowed origin it says nothing, and the browser refuses. */
|
|
75
|
+
export function preflightResponse(policy: CorsPolicy, request: Request, methods: string): Response {
|
|
76
|
+
const origin = allowedOrigin(policy, request)
|
|
77
|
+
const headers = new Headers({ vary: 'Origin' })
|
|
78
|
+
if (origin) {
|
|
79
|
+
headers.set('access-control-allow-origin', origin)
|
|
80
|
+
headers.set('access-control-allow-methods', methods)
|
|
81
|
+
headers.set('access-control-allow-headers', CORS_ALLOWED_HEADERS)
|
|
82
|
+
headers.set('access-control-max-age', MAX_AGE_SECONDS)
|
|
83
|
+
}
|
|
84
|
+
return new Response(null, { status: 204, headers })
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The response with the CORS headers a cross-origin caller needs to read it. */
|
|
88
|
+
export function withCors(policy: CorsPolicy, request: Request, response: Response): Response {
|
|
89
|
+
if (policy.origins.size === 0 && !policy.any) return response
|
|
90
|
+
const origin = allowedOrigin(policy, request)
|
|
91
|
+
const headers = new Headers(response.headers)
|
|
92
|
+
const vary = headers.get('vary')
|
|
93
|
+
if (!vary?.split(',').some((v) => v.trim().toLowerCase() === 'origin'))
|
|
94
|
+
headers.set('vary', vary ? `${vary}, Origin` : 'Origin')
|
|
95
|
+
if (origin) headers.set('access-control-allow-origin', origin)
|
|
96
|
+
return new Response(response.body, {
|
|
97
|
+
status: response.status,
|
|
98
|
+
statusText: response.statusText,
|
|
99
|
+
headers,
|
|
100
|
+
})
|
|
101
|
+
}
|
package/src/forms.ts
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A form as data, for an app that draws it itself (story 056): what a visitor
|
|
3
|
+
* sees and answers, and what a submission must carry. Never its workflows, its
|
|
4
|
+
* notes or its storage rules, which are the site's business and can hold
|
|
5
|
+
* addresses and secrets. docs/delivery-api.md, "Forms".
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
allFormFields,
|
|
9
|
+
choiceOptions,
|
|
10
|
+
FORM_HONEYPOT_FIELD,
|
|
11
|
+
FORM_PAGE_FIELD,
|
|
12
|
+
FORM_RENDERED_FIELD,
|
|
13
|
+
FORM_TOKEN_FIELD,
|
|
14
|
+
type FormTypes,
|
|
15
|
+
formFieldType,
|
|
16
|
+
type SchemaForm,
|
|
17
|
+
type SchemaFormField,
|
|
18
|
+
} from '@crombolo/core'
|
|
19
|
+
|
|
20
|
+
export interface ApiFormContext {
|
|
21
|
+
types: FormTypes
|
|
22
|
+
/** Where a submission is posted: absolute, since an app is somewhere else. */
|
|
23
|
+
action: string
|
|
24
|
+
/** Signed for this form and `renderedAt`, as a rendered form's is. */
|
|
25
|
+
token: string
|
|
26
|
+
renderedAt: number
|
|
27
|
+
/** The address of the page `redirectTo` names, if it has one. */
|
|
28
|
+
redirectUrl: string | undefined
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A form picker's value when it is not expanded: enough to fetch the rest. */
|
|
32
|
+
export const apiFormReference = (form: SchemaForm) => ({
|
|
33
|
+
id: form.key ?? form.alias,
|
|
34
|
+
alias: form.alias,
|
|
35
|
+
name: form.name,
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
const defined = (record: Record<string, unknown>) =>
|
|
39
|
+
Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined))
|
|
40
|
+
|
|
41
|
+
function apiField(field: SchemaFormField): Record<string, unknown> {
|
|
42
|
+
return defined({
|
|
43
|
+
key: field.key,
|
|
44
|
+
alias: field.alias,
|
|
45
|
+
type: field.type,
|
|
46
|
+
caption: field.caption,
|
|
47
|
+
helpText: field.helpText,
|
|
48
|
+
mandatory: field.mandatory,
|
|
49
|
+
mandatoryMessage: field.mandatoryMessage,
|
|
50
|
+
pattern: field.pattern,
|
|
51
|
+
patternMessage: field.patternMessage,
|
|
52
|
+
cssClass: field.cssClass,
|
|
53
|
+
autocomplete: field.autocomplete,
|
|
54
|
+
// A source's choices already resolved; the stored list otherwise.
|
|
55
|
+
options: field.source || field.values.length > 0 ? choiceOptions(field) : undefined,
|
|
56
|
+
placeholder: field.placeholder,
|
|
57
|
+
defaultValue: field.defaultValue,
|
|
58
|
+
content: field.content,
|
|
59
|
+
maxlength: field.maxlength,
|
|
60
|
+
rows: field.rows,
|
|
61
|
+
min: field.min,
|
|
62
|
+
max: field.max,
|
|
63
|
+
step: field.step,
|
|
64
|
+
accept: field.accept.length > 0 ? field.accept : undefined,
|
|
65
|
+
maxSizeKb: field.maxSizeKb,
|
|
66
|
+
multiple: field.multiple,
|
|
67
|
+
settings: field.settings,
|
|
68
|
+
condition: field.condition,
|
|
69
|
+
})
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The form an app draws and submits. Pure. */
|
|
73
|
+
export function apiForm(form: SchemaForm, context: ApiFormContext): Record<string, unknown> {
|
|
74
|
+
const used = new Set(allFormFields(form).map((field) => field.type))
|
|
75
|
+
const types: Record<string, unknown> = {}
|
|
76
|
+
for (const type of used) {
|
|
77
|
+
const info = formFieldType(type, context.types)
|
|
78
|
+
if (!info) continue
|
|
79
|
+
types[type] = defined({
|
|
80
|
+
label: info.label,
|
|
81
|
+
stores: info.stores,
|
|
82
|
+
choices: info.choices,
|
|
83
|
+
presentational: info.presentational,
|
|
84
|
+
// A bundle's type says what it is and what it takes, so an app can recognise one it does not know.
|
|
85
|
+
bundle: info.bundle,
|
|
86
|
+
settings: info.declared.length > 0 ? info.declared : undefined,
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
return defined({
|
|
90
|
+
...apiFormReference(form),
|
|
91
|
+
stepPages: form.stepPages ?? false,
|
|
92
|
+
submitLabel: form.submitLabel,
|
|
93
|
+
nextLabel: form.nextLabel,
|
|
94
|
+
previousLabel: form.previousLabel,
|
|
95
|
+
messageOnSubmit: form.messageOnSubmit,
|
|
96
|
+
redirectTo: context.redirectUrl,
|
|
97
|
+
pages: form.pages.map((page) =>
|
|
98
|
+
defined({
|
|
99
|
+
caption: page.caption,
|
|
100
|
+
condition: page.condition,
|
|
101
|
+
groups: page.groups.map((group) =>
|
|
102
|
+
defined({
|
|
103
|
+
caption: group.caption,
|
|
104
|
+
columns: group.columns,
|
|
105
|
+
condition: group.condition,
|
|
106
|
+
fields: group.fields.map(apiField),
|
|
107
|
+
}),
|
|
108
|
+
),
|
|
109
|
+
}),
|
|
110
|
+
),
|
|
111
|
+
types,
|
|
112
|
+
submit: {
|
|
113
|
+
action: context.action,
|
|
114
|
+
method: 'POST',
|
|
115
|
+
// Post these with the answers, as multipart or URL-encoded form data.
|
|
116
|
+
fields: defined({
|
|
117
|
+
[FORM_TOKEN_FIELD]: context.token,
|
|
118
|
+
[FORM_RENDERED_FIELD]: String(context.renderedAt),
|
|
119
|
+
}),
|
|
120
|
+
// Sent empty: a bot fills it. Absent when the form has no honeypot.
|
|
121
|
+
honeypot: form.honeypot ? FORM_HONEYPOT_FIELD : undefined,
|
|
122
|
+
// Set to a page's index to check that page alone, for a stepped form.
|
|
123
|
+
page: FORM_PAGE_FIELD,
|
|
124
|
+
},
|
|
125
|
+
})
|
|
126
|
+
}
|
package/src/handler.ts
CHANGED
|
@@ -4,14 +4,27 @@
|
|
|
4
4
|
* Every answer is read from memory, so it scales with the nodes that render.
|
|
5
5
|
* docs/delivery-api.md.
|
|
6
6
|
*/
|
|
7
|
-
import { branchAccess } from '@crombolo/core'
|
|
7
|
+
import { branchAccess, type SchemaForm } from '@crombolo/core'
|
|
8
8
|
import type {
|
|
9
9
|
PublishedCache,
|
|
10
10
|
PublishedContent,
|
|
11
11
|
PublishedMedia,
|
|
12
12
|
SearchableText,
|
|
13
13
|
} from '@crombolo/render'
|
|
14
|
-
import {
|
|
14
|
+
import {
|
|
15
|
+
type Cacheable,
|
|
16
|
+
type CacheSettings,
|
|
17
|
+
cacheable,
|
|
18
|
+
excerpt,
|
|
19
|
+
excerptHtml,
|
|
20
|
+
isRightToLeft,
|
|
21
|
+
lifetimeFor,
|
|
22
|
+
type MenuItem,
|
|
23
|
+
PRIVATE_NO_STORE,
|
|
24
|
+
resolveCacheSettings,
|
|
25
|
+
shortest,
|
|
26
|
+
} from '@crombolo/render'
|
|
27
|
+
import { corsPolicy, isPreflight, preflightResponse, withCors } from './cors.ts'
|
|
15
28
|
import {
|
|
16
29
|
ALL_FIELDS,
|
|
17
30
|
type ExpansionNode,
|
|
@@ -50,6 +63,37 @@ export interface DeliveryApiPorts {
|
|
|
50
63
|
protection(): Promise<ProtectionRule[]>
|
|
51
64
|
/** The member an access token names; undefined for none, or one not valid now. */
|
|
52
65
|
member(token: string): Promise<DeliveryMember | undefined>
|
|
66
|
+
/**
|
|
67
|
+
* Drafts for a `Preview: true` request (story 053): given whether it carries
|
|
68
|
+
* the API key, the draft cache and, for a preview token, which pages its
|
|
69
|
+
* editor may read; undefined when the request may not preview.
|
|
70
|
+
*/
|
|
71
|
+
preview?(request: Request, keyed: boolean): Promise<PreviewAccess | undefined>
|
|
72
|
+
/** How long answers may be kept (story 057); nothing is kept when absent. */
|
|
73
|
+
caching?: CacheSettings
|
|
74
|
+
/**
|
|
75
|
+
* A page's search and sharing details, worked out as `<SeoHead>` works them
|
|
76
|
+
* out, for `seo=true` (story 055).
|
|
77
|
+
*/
|
|
78
|
+
seo?(content: PublishedContent, request: Request): Promise<Record<string, unknown>>
|
|
79
|
+
/** The sitemap's pages for a hostname; undefined when the site serves no sitemap (story 055). */
|
|
80
|
+
sitemap?(request: Request, host: string): Promise<unknown[] | undefined>
|
|
81
|
+
/**
|
|
82
|
+
* Forms as data (story 056): a definition by key or alias, and, for one
|
|
83
|
+
* request in one culture, how to draw any form as `v2/forms/{key}` answers it.
|
|
84
|
+
*/
|
|
85
|
+
forms?: {
|
|
86
|
+
byKey(key: string): SchemaForm | undefined
|
|
87
|
+
shaper(
|
|
88
|
+
culture: string | null,
|
|
89
|
+
request: Request,
|
|
90
|
+
): Promise<(form: SchemaForm) => Record<string, unknown>>
|
|
91
|
+
}
|
|
92
|
+
/** The page the site shows for an address nothing answers, if it has one (story 054). */
|
|
93
|
+
notFound?(
|
|
94
|
+
host: string,
|
|
95
|
+
path: string,
|
|
96
|
+
): Promise<{ key: string; culture: string | null } | undefined>
|
|
53
97
|
/** The member sign-in endpoints under `v1/security/member/`, when built. */
|
|
54
98
|
security?(request: Request, action: string): Promise<Response | undefined>
|
|
55
99
|
/**
|
|
@@ -68,12 +112,34 @@ export interface DeliveryApiPorts {
|
|
|
68
112
|
): Promise<{ total: number; items: Array<{ key: string; score: number; text: SearchableText }> }>
|
|
69
113
|
}
|
|
70
114
|
|
|
115
|
+
export interface PreviewAccess {
|
|
116
|
+
/** Every page as last saved. */
|
|
117
|
+
cache: PublishedCache
|
|
118
|
+
/** For an editor's preview token: whether a page, by its ancestors' keys then its own, may be read. */
|
|
119
|
+
mayRead?(chain: readonly string[]): boolean
|
|
120
|
+
}
|
|
121
|
+
|
|
71
122
|
export interface DeliveryApi {
|
|
72
123
|
handle(request: Request): Promise<Response | undefined>
|
|
124
|
+
/** Configured cross-origin settings that were ignored, said once at boot. */
|
|
125
|
+
problems: string[]
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The methods a cross-origin caller may send to a path, or none for a path a
|
|
130
|
+
* browser reaches by navigating (sign-in and sign-out) or that is not the API's. Pure.
|
|
131
|
+
*/
|
|
132
|
+
export function corsMethodsFor(rest: string): string | undefined {
|
|
133
|
+
if (/^v2\/(content|media|search|route|sitemap|forms|menus)(\/.*)?$/.test(rest)) return 'GET, HEAD'
|
|
134
|
+
const security = /^v1\/security\/member\/([^/]+)\/?$/.exec(rest)?.[1]
|
|
135
|
+
if (security === 'token' || security === 'revoke') return 'POST'
|
|
136
|
+
if (security === 'userinfo') return 'GET, POST'
|
|
137
|
+
return undefined
|
|
73
138
|
}
|
|
74
139
|
|
|
75
140
|
const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
76
141
|
const ROOT_KEY = '00000000-0000-0000-0000-000000000000'
|
|
142
|
+
const PREVIEW_PATH = /^preview-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i
|
|
77
143
|
const CONTENT_VARY = 'Accept-Language, Accept-Segment, Preview, Start-Item'
|
|
78
144
|
|
|
79
145
|
/** 401, 403 and 404 carry no body in Umbraco's Delivery API. */
|
|
@@ -101,6 +167,30 @@ const invalid = (field: string, value: string) =>
|
|
|
101
167
|
{ status: 400, headers: { 'content-type': 'application/problem+json' } },
|
|
102
168
|
)
|
|
103
169
|
|
|
170
|
+
/**
|
|
171
|
+
* Whether an answer depends on who asked: a member's token, or an API that is
|
|
172
|
+
* not public, whose answers are for the key's holder. Pure.
|
|
173
|
+
*/
|
|
174
|
+
export function personal(request: Request, isPublic: boolean, membersSignIn: boolean): boolean {
|
|
175
|
+
return !isPublic || (membersSignIn && bearerToken(request) !== undefined)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Every page, element and media key in an answer, for purge tags. Pure. */
|
|
179
|
+
export function keysIn(body: unknown, into: Set<string> = new Set()): Set<string> {
|
|
180
|
+
if (Array.isArray(body)) for (const item of body) keysIn(item, into)
|
|
181
|
+
else if (body && typeof body === 'object') {
|
|
182
|
+
const record = body as Record<string, unknown>
|
|
183
|
+
if (
|
|
184
|
+
typeof record.id === 'string' &&
|
|
185
|
+
(typeof record.contentType === 'string' || typeof record.mediaType === 'string')
|
|
186
|
+
)
|
|
187
|
+
into.add(record.id)
|
|
188
|
+
for (const value of Object.values(record))
|
|
189
|
+
if (value && typeof value === 'object') keysIn(value, into)
|
|
190
|
+
}
|
|
191
|
+
return into
|
|
192
|
+
}
|
|
193
|
+
|
|
104
194
|
/** The caller's key, compared exactly; a site without one has none to match. Pure. */
|
|
105
195
|
export const hasValidApiKey = (settings: DeliveryApiSettings, request: Request): boolean =>
|
|
106
196
|
settings.apiKey !== undefined && request.headers.get('api-key') === settings.apiKey
|
|
@@ -161,14 +251,71 @@ const expansionOf = (url: URL): { expand: ExpansionNode; include: ExpansionNode
|
|
|
161
251
|
export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
162
252
|
const { settings, cache } = ports
|
|
163
253
|
const prefix = ports.prefix.replace(/\/$/, '')
|
|
254
|
+
const caching = ports.caching ?? resolveCacheSettings()
|
|
255
|
+
|
|
256
|
+
/** What each public answer holds, so its lifetime and tags are those of its pages and media. */
|
|
257
|
+
const holds = new WeakMap<Response, { items: Cacheable[]; tags: string[] }>()
|
|
258
|
+
const holding = (
|
|
259
|
+
response: Response,
|
|
260
|
+
items: Cacheable[],
|
|
261
|
+
tags: string[] = [],
|
|
262
|
+
drawn?: { formDrawn(): boolean },
|
|
263
|
+
) => {
|
|
264
|
+
if (drawn?.formDrawn()) response.headers.set('cache-control', 'no-store')
|
|
265
|
+
holds.set(response, { items, tags })
|
|
266
|
+
return response
|
|
267
|
+
}
|
|
268
|
+
const page = (content: PublishedContent): Cacheable => ({
|
|
269
|
+
typeAlias: content.contentType.alias,
|
|
270
|
+
value: (alias) => content.value(alias),
|
|
271
|
+
})
|
|
272
|
+
const mediaItem = (media: PublishedMedia): Cacheable => ({
|
|
273
|
+
typeAlias: media.mediaType.alias,
|
|
274
|
+
value: (alias) => media.value(alias),
|
|
275
|
+
})
|
|
164
276
|
|
|
165
|
-
/**
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
277
|
+
/**
|
|
278
|
+
* A public answer's lifetime, ETag and tags; a `304` when the caller holds it.
|
|
279
|
+
* Anything that depends on who asks is never kept.
|
|
280
|
+
*/
|
|
281
|
+
async function finish(request: Request, response: Response, personal: boolean) {
|
|
282
|
+
if (personal) {
|
|
283
|
+
response.headers.set('cache-control', PRIVATE_NO_STORE)
|
|
284
|
+
return response
|
|
285
|
+
}
|
|
286
|
+
const held = holds.get(response)
|
|
287
|
+
if (!held || response.status !== 200) return response
|
|
288
|
+
const body = await response.text()
|
|
289
|
+
const lifetime =
|
|
290
|
+
response.headers.get('cache-control') === 'no-store'
|
|
291
|
+
? 'none'
|
|
292
|
+
: shortest(
|
|
293
|
+
held.items.map((item) => lifetimeFor(caching, item)),
|
|
294
|
+
caching.site,
|
|
295
|
+
)
|
|
296
|
+
const tags = caching.tagHeader ? [...held.tags, ...keysIn(JSON.parse(body))] : undefined
|
|
297
|
+
return cacheable(request, response, body, { lifetime, tags, tagHeader: caching.tagHeader })
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Everything a content request decides once: culture, member, rules, routes.
|
|
302
|
+
* A preview reads the draft cache, and an editor's sees only what they may read.
|
|
303
|
+
*/
|
|
304
|
+
async function contentRequest(
|
|
305
|
+
request: Request,
|
|
306
|
+
preview?: PreviewAccess,
|
|
307
|
+
/** A culture the address chose, which wins over `Accept-Language`. */
|
|
308
|
+
chosen?: string | null,
|
|
309
|
+
) {
|
|
310
|
+
const source = preview?.cache ?? cache
|
|
311
|
+
const asked =
|
|
312
|
+
chosen !== undefined && chosen !== null
|
|
313
|
+
? chosen
|
|
314
|
+
: requestedCulture(request.headers.get('accept-language'))
|
|
315
|
+
const culture = asked ?? (await source.defaultCulture())
|
|
316
|
+
const known = asked === undefined || (await source.hasCulture(asked))
|
|
317
|
+
const nav = await source.navigation(culture)
|
|
318
|
+
const hide = await source.hidesTopLevel()
|
|
172
319
|
const roots = nav.root()
|
|
173
320
|
const rtl = isRightToLeft(culture)
|
|
174
321
|
|
|
@@ -178,7 +325,7 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
|
178
325
|
const loadedRules = new Map((await ports.protection()).map((rule) => [rule.nodeId, rule]))
|
|
179
326
|
|
|
180
327
|
const routeIn = async (inCulture: string | null) => {
|
|
181
|
-
const view = await
|
|
328
|
+
const view = await source.navigation(inCulture)
|
|
182
329
|
const first = view.root()[0]
|
|
183
330
|
const cultureRtl = isRightToLeft(inCulture)
|
|
184
331
|
return (content: PublishedContent): ApiRoute | undefined => {
|
|
@@ -198,11 +345,31 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
|
198
345
|
}
|
|
199
346
|
const route = await routeIn(culture)
|
|
200
347
|
|
|
348
|
+
const chainOf = (content: PublishedContent) => [
|
|
349
|
+
...[...nav.ancestors(content)].reverse().map((c) => c.key),
|
|
350
|
+
content.key,
|
|
351
|
+
]
|
|
352
|
+
const readable = (content: PublishedContent) =>
|
|
353
|
+
!preview?.mayRead || preview.mayRead(chainOf(content))
|
|
354
|
+
|
|
355
|
+
// A form carries a token signed for when it was drawn, so an answer holding one
|
|
356
|
+
// is never kept: a stale draw time would let a bot past the timing guard.
|
|
357
|
+
let formDrawn = false
|
|
358
|
+
const shapeForm = ports.forms ? await ports.forms.shaper(culture, request) : undefined
|
|
359
|
+
|
|
201
360
|
const ctx: OutputContext = {
|
|
361
|
+
form: shapeForm
|
|
362
|
+
? (form) => {
|
|
363
|
+
formDrawn = true
|
|
364
|
+
return shapeForm(form)
|
|
365
|
+
}
|
|
366
|
+
: undefined,
|
|
202
367
|
route,
|
|
203
368
|
content: (key) => nav.byKey(key),
|
|
204
369
|
allowedType: (alias) => isAllowedContentType(settings, alias),
|
|
205
|
-
|
|
370
|
+
// A page the previewing editor may not read keeps its route in a picker, never its properties.
|
|
371
|
+
access: (content) =>
|
|
372
|
+
readable(content) ? accessTo(content.path, loadedRules, member) : 'forbidden',
|
|
206
373
|
}
|
|
207
374
|
|
|
208
375
|
/** Below a node by URL segments, exactly as stored. */
|
|
@@ -254,6 +421,7 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
|
254
421
|
content &&
|
|
255
422
|
known &&
|
|
256
423
|
isAllowedContentType(settings, content.contentType.alias) &&
|
|
424
|
+
readable(content) &&
|
|
257
425
|
route(content)
|
|
258
426
|
? content
|
|
259
427
|
: undefined
|
|
@@ -263,16 +431,23 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
|
263
431
|
if (expansion instanceof Response) return expansion
|
|
264
432
|
const routes = new Map<string, (c: PublishedContent) => ApiRoute | undefined>()
|
|
265
433
|
for (const c of content.cultures) routes.set(c, await routeIn(c))
|
|
266
|
-
|
|
434
|
+
const body = apiContentResponse(
|
|
267
435
|
content,
|
|
268
436
|
ctx,
|
|
269
437
|
(c) => routes.get(c)?.(content),
|
|
270
438
|
expansion.expand,
|
|
271
439
|
expansion.include,
|
|
272
440
|
)
|
|
441
|
+
// Asked for, so answers that do not want them stay the size Umbraco's are.
|
|
442
|
+
if (body && ports.seo && url.searchParams.get('seo') === 'true')
|
|
443
|
+
return { ...body, seo: await ports.seo(content, request) }
|
|
444
|
+
return body
|
|
273
445
|
}
|
|
274
446
|
|
|
275
447
|
return {
|
|
448
|
+
source,
|
|
449
|
+
shapeForm,
|
|
450
|
+
formDrawn: () => formDrawn,
|
|
276
451
|
culture,
|
|
277
452
|
known,
|
|
278
453
|
nav,
|
|
@@ -299,7 +474,7 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
|
299
474
|
if (access !== 'allowed') return bare(access === 'forbidden' ? 403 : 401)
|
|
300
475
|
const body = await r.respond(found, url)
|
|
301
476
|
if (body instanceof Response) return body
|
|
302
|
-
return body ? json(body) : bare(404)
|
|
477
|
+
return body ? holding(json(body), [page(found)], [], r) : bare(404)
|
|
303
478
|
}
|
|
304
479
|
|
|
305
480
|
async function contentItems(r: ContentRequest, url: URL) {
|
|
@@ -319,7 +494,7 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
|
319
494
|
if (body instanceof Response) return body
|
|
320
495
|
if (body) out.push(body)
|
|
321
496
|
}
|
|
322
|
-
return json(out)
|
|
497
|
+
return holding(json(out), found.map(page), [], r)
|
|
323
498
|
}
|
|
324
499
|
|
|
325
500
|
async function contentQuery(r: ContentRequest, url: URL) {
|
|
@@ -334,7 +509,7 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
|
334
509
|
const take = intParam(url, 'take', 10)
|
|
335
510
|
if (take instanceof Response) return take
|
|
336
511
|
|
|
337
|
-
const all = r.known ? await
|
|
512
|
+
const all = r.known ? await r.source.contentIn(r.culture) : []
|
|
338
513
|
const resolveTarget = (target: string): PublishedContent | 'roots' | undefined => {
|
|
339
514
|
if (!target) return undefined
|
|
340
515
|
if (target === ROOT_KEY) return 'roots'
|
|
@@ -384,12 +559,20 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
|
384
559
|
)
|
|
385
560
|
: visible
|
|
386
561
|
const items = []
|
|
387
|
-
|
|
562
|
+
const shown = ordered.slice(skip, skip + take)
|
|
563
|
+
for (const content of shown) {
|
|
388
564
|
const body = await r.respond(content, url)
|
|
389
565
|
if (body instanceof Response) return body
|
|
390
566
|
if (body) items.push(body)
|
|
391
567
|
}
|
|
392
|
-
|
|
568
|
+
// A new page under the one fetched from changes this list, so it carries that page's tag.
|
|
569
|
+
const from = selector.kind === 'all' ? undefined : resolveTarget(selector.target)
|
|
570
|
+
return holding(
|
|
571
|
+
json({ total: ordered.length, items }),
|
|
572
|
+
shown.map(page),
|
|
573
|
+
from && from !== 'roots' ? [from.key] : [],
|
|
574
|
+
r,
|
|
575
|
+
)
|
|
393
576
|
}
|
|
394
577
|
|
|
395
578
|
/** Media's tree, by parent, and each item's path of lowercased names. */
|
|
@@ -426,16 +609,16 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
|
426
609
|
if (rest === 'items') {
|
|
427
610
|
const ids = [...new Set(url.searchParams.getAll('id').map((id) => id.toLowerCase()))]
|
|
428
611
|
for (const id of ids) if (!GUID.test(id)) return invalid('id', id)
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
)
|
|
612
|
+
const found = ids.flatMap((id) => {
|
|
613
|
+
const media = tree.byKey.get(id)
|
|
614
|
+
return media ? [media] : []
|
|
615
|
+
})
|
|
616
|
+
return holding(Response.json(found.map(answer)), found.map(mediaItem))
|
|
434
617
|
}
|
|
435
618
|
if (rest.startsWith('item/')) {
|
|
436
619
|
const target = rest.slice('item/'.length)
|
|
437
620
|
const found = GUID.test(target) ? tree.byKey.get(target.toLowerCase()) : tree.byPath(target)
|
|
438
|
-
return found ? Response.json(answer(found)) : bare(404)
|
|
621
|
+
return found ? holding(Response.json(answer(found)), [mediaItem(found)]) : bare(404)
|
|
439
622
|
}
|
|
440
623
|
if (rest !== '') return undefined
|
|
441
624
|
const query = parseMediaQuery({
|
|
@@ -466,10 +649,11 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
|
466
649
|
compareBy([query.sort]) as unknown as (a: PublishedMedia, b: PublishedMedia) => number,
|
|
467
650
|
)
|
|
468
651
|
: filtered
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
652
|
+
const shown = ordered.slice(skip, skip + take)
|
|
653
|
+
return holding(
|
|
654
|
+
Response.json({ total: ordered.length, items: shown.map(answer) }),
|
|
655
|
+
shown.map(mediaItem),
|
|
656
|
+
)
|
|
473
657
|
}
|
|
474
658
|
|
|
475
659
|
/**
|
|
@@ -499,54 +683,288 @@ export function createDeliveryApi(ports: DeliveryApiPorts): DeliveryApi {
|
|
|
499
683
|
access: branchAccess(r.rules, member),
|
|
500
684
|
})
|
|
501
685
|
const items = []
|
|
686
|
+
const shown: PublishedContent[] = []
|
|
502
687
|
for (const hit of hits.items) {
|
|
503
688
|
const content = r.servable(r.nav.byKey(hit.key))
|
|
504
689
|
if (!content || r.ctx.access(content) !== 'allowed') continue
|
|
505
690
|
const body = await r.respond(content, url)
|
|
506
691
|
if (body instanceof Response) return body
|
|
507
|
-
if (body)
|
|
692
|
+
if (body) {
|
|
693
|
+
shown.push(content)
|
|
508
694
|
items.push({ ...body, score: hit.score, excerpt: excerptHtml(excerpt(hit.text, term)) })
|
|
695
|
+
}
|
|
509
696
|
}
|
|
510
|
-
return json({ total: hits.total, items })
|
|
697
|
+
return holding(json({ total: hits.total, items }), shown.map(page), [], r)
|
|
511
698
|
}
|
|
512
699
|
|
|
700
|
+
const cors = corsPolicy(settings)
|
|
701
|
+
const corsOn = cors.origins.size > 0 || cors.any
|
|
702
|
+
|
|
513
703
|
return {
|
|
704
|
+
problems: cors.problems,
|
|
514
705
|
async handle(request) {
|
|
515
706
|
const url = new URL(request.url)
|
|
516
707
|
if (!url.pathname.startsWith(`${prefix}/`)) return undefined
|
|
517
708
|
const rest = url.pathname.slice(prefix.length + 1)
|
|
709
|
+
const methods = corsOn ? corsMethodsFor(rest) : undefined
|
|
710
|
+
if (!methods) return route(request, url, rest)
|
|
711
|
+
if (isPreflight(request)) return preflightResponse(cors, request, methods)
|
|
712
|
+
const response = await route(request, url, rest)
|
|
713
|
+
return response && withCors(cors, request, response)
|
|
714
|
+
},
|
|
715
|
+
}
|
|
518
716
|
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
if (/^v2\/search\/?$/.test(rest)) {
|
|
523
|
-
if (request.method !== 'GET' && request.method !== 'HEAD') return bare(405)
|
|
524
|
-
if (!contentAccess(settings, request)) return bare(401)
|
|
525
|
-
return contentSearch(await contentRequest(request), url)
|
|
526
|
-
}
|
|
717
|
+
async function route(request: Request, url: URL, rest: string) {
|
|
718
|
+
const security = /^v1\/security\/member\/(.+)$/.exec(rest)
|
|
719
|
+
if (security) return ports.security?.(request, security[1] as string)
|
|
527
720
|
|
|
528
|
-
|
|
529
|
-
if (!match) return undefined
|
|
721
|
+
if (/^v2\/search\/?$/.test(rest)) {
|
|
530
722
|
if (request.method !== 'GET' && request.method !== 'HEAD') return bare(405)
|
|
531
|
-
|
|
532
|
-
const
|
|
723
|
+
if (!contentAccess(settings, request)) return bare(401)
|
|
724
|
+
const response = await contentSearch(await contentRequest(request), url)
|
|
725
|
+
return finish(
|
|
726
|
+
request,
|
|
727
|
+
response,
|
|
728
|
+
personal(request, settings.publicAccess, memberAuthorizationEnabled(settings)),
|
|
729
|
+
)
|
|
730
|
+
}
|
|
533
731
|
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
732
|
+
const menuMatch = /^v2\/menus\/([^/]+)\/?$/.exec(rest)
|
|
733
|
+
if (menuMatch) {
|
|
734
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') return bare(405)
|
|
735
|
+
const preview = isPreview(request) ? await previewAccess(request) : undefined
|
|
736
|
+
if (preview === null) return bare(401)
|
|
737
|
+
if (!preview && !contentAccess(settings, request)) return bare(401)
|
|
738
|
+
const response = await menuAnswer(
|
|
739
|
+
request,
|
|
740
|
+
decodeURIComponent(menuMatch[1] as string),
|
|
741
|
+
preview,
|
|
742
|
+
)
|
|
743
|
+
if (preview) {
|
|
744
|
+
response.headers.set('cache-control', 'no-store')
|
|
745
|
+
return response
|
|
746
|
+
}
|
|
747
|
+
return finish(
|
|
748
|
+
request,
|
|
749
|
+
response,
|
|
750
|
+
personal(request, settings.publicAccess, memberAuthorizationEnabled(settings)),
|
|
751
|
+
)
|
|
752
|
+
}
|
|
539
753
|
|
|
754
|
+
const formMatch = /^v2\/forms\/([^/]+)\/?$/.exec(rest)
|
|
755
|
+
if (formMatch) {
|
|
756
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') return bare(405)
|
|
540
757
|
if (!contentAccess(settings, request)) return bare(401)
|
|
758
|
+
const form = ports.forms?.byKey(decodeURIComponent(formMatch[1] as string))
|
|
759
|
+
if (!form) return bare(404)
|
|
541
760
|
const r = await contentRequest(request)
|
|
542
|
-
|
|
543
|
-
if (
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
761
|
+
const shaped = r.shapeForm?.(form)
|
|
762
|
+
if (!shaped) return bare(404)
|
|
763
|
+
// Drawn now, with a token for now: never kept, so the timing guard means what it says.
|
|
764
|
+
return Response.json(shaped, { headers: { vary: CONTENT_VARY, 'cache-control': 'no-store' } })
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
if (/^v2\/sitemap\/?$/.test(rest)) {
|
|
768
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') return bare(405)
|
|
769
|
+
if (!contentAccess(settings, request)) return bare(401)
|
|
770
|
+
const items = await ports.sitemap?.(request, url.searchParams.get('host') || url.host)
|
|
771
|
+
if (!items) return bare(404)
|
|
772
|
+
return finish(
|
|
773
|
+
request,
|
|
774
|
+
holding(json({ total: items.length, items }), []),
|
|
775
|
+
personal(request, settings.publicAccess, memberAuthorizationEnabled(settings)),
|
|
776
|
+
)
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
if (/^v2\/route\/?$/.test(rest)) {
|
|
780
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') return bare(405)
|
|
781
|
+
const preview = isPreview(request) ? await previewAccess(request) : undefined
|
|
782
|
+
if (preview === null) return bare(401)
|
|
783
|
+
if (!preview && !contentAccess(settings, request)) return bare(401)
|
|
784
|
+
const response = await routeLookup(request, url, preview)
|
|
785
|
+
if (preview) {
|
|
786
|
+
response.headers.set('cache-control', 'no-store')
|
|
787
|
+
return response
|
|
548
788
|
}
|
|
549
|
-
return
|
|
550
|
-
|
|
789
|
+
return finish(
|
|
790
|
+
request,
|
|
791
|
+
response,
|
|
792
|
+
personal(request, settings.publicAccess, memberAuthorizationEnabled(settings)),
|
|
793
|
+
)
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
const match = /^v2\/(content|media)(?:\/(.*))?$/.exec(rest)
|
|
797
|
+
if (!match) return undefined
|
|
798
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') return bare(405)
|
|
799
|
+
const area = match[1]
|
|
800
|
+
const tail = (match[2] ?? '').replace(/\/$/, '')
|
|
801
|
+
|
|
802
|
+
if (area === 'media') {
|
|
803
|
+
const response =
|
|
804
|
+
(await handleMedia(request, url, tail === '' && match[2] === undefined ? '' : tail)) ??
|
|
805
|
+
bare(404)
|
|
806
|
+
return finish(
|
|
807
|
+
request,
|
|
808
|
+
response,
|
|
809
|
+
personal(
|
|
810
|
+
request,
|
|
811
|
+
settings.publicAccess && settings.media.publicAccess,
|
|
812
|
+
memberAuthorizationEnabled(settings),
|
|
813
|
+
),
|
|
814
|
+
)
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
const preview = isPreview(request) ? await previewAccess(request) : undefined
|
|
818
|
+
if (preview === null) return bare(401)
|
|
819
|
+
if (!preview && !contentAccess(settings, request)) return bare(401)
|
|
820
|
+
const response = await contentRoute(request, url, match[2], tail, preview)
|
|
821
|
+
// A draft is never kept by a cache between here and the app.
|
|
822
|
+
if (preview) {
|
|
823
|
+
response.headers.set('cache-control', 'no-store')
|
|
824
|
+
return response
|
|
825
|
+
}
|
|
826
|
+
return finish(
|
|
827
|
+
request,
|
|
828
|
+
response,
|
|
829
|
+
personal(request, settings.publicAccess, memberAuthorizationEnabled(settings)),
|
|
830
|
+
)
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
/**
|
|
834
|
+
* `v2/route?path=&host=` (story 054): what the site would answer at an address
|
|
835
|
+
* — the page, a redirect, or not found with the site's not-found page — so an
|
|
836
|
+
* app's router behaves as the rendered site does. A Crombolo addition.
|
|
837
|
+
*/
|
|
838
|
+
async function routeLookup(
|
|
839
|
+
request: Request,
|
|
840
|
+
url: URL,
|
|
841
|
+
preview: PreviewAccess | undefined,
|
|
842
|
+
): Promise<Response> {
|
|
843
|
+
const path = url.searchParams.get('path')
|
|
844
|
+
if (!path) return invalid('path', '')
|
|
845
|
+
const host = url.searchParams.get('host') || url.host
|
|
846
|
+
const pathname = path.startsWith('/') ? path : `/${path}`
|
|
847
|
+
const found = await (preview?.cache ?? cache).resolve(host, pathname)
|
|
848
|
+
// A page that sends its visitors elsewhere (`umbracoRedirect`), as the site's 302 does.
|
|
849
|
+
if (found?.redirect) return redirectAnswer(found.redirect, 302)
|
|
850
|
+
if (found) {
|
|
851
|
+
const r = await contentRequest(request, preview, found.culture)
|
|
852
|
+
const content = r.servable(r.nav.byKey(found.content.key))
|
|
853
|
+
if (content) {
|
|
854
|
+
const access = r.ctx.access(content)
|
|
855
|
+
if (access !== 'allowed') return bare(access === 'forbidden' ? 403 : 401)
|
|
856
|
+
const item = await r.respond(content, url)
|
|
857
|
+
if (item instanceof Response) return item
|
|
858
|
+
if (item)
|
|
859
|
+
return holding(
|
|
860
|
+
json({ kind: 'page', culture: found.culture, item }),
|
|
861
|
+
[page(content)],
|
|
862
|
+
[],
|
|
863
|
+
r,
|
|
864
|
+
)
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
// Only once no page answered, so a redirect never hides live content.
|
|
868
|
+
const redirect = await cache.redirect(host, pathname)
|
|
869
|
+
if (redirect) return redirectAnswer(redirect.location, redirect.statusCode)
|
|
870
|
+
const missing = await ports.notFound?.(host, pathname)
|
|
871
|
+
let item: Record<string, unknown> | null = null
|
|
872
|
+
if (missing) {
|
|
873
|
+
const r = await contentRequest(request, preview, missing.culture)
|
|
874
|
+
const content = r.servable(r.nav.byKey(missing.key))
|
|
875
|
+
const body =
|
|
876
|
+
content && r.ctx.access(content) === 'allowed' ? await r.respond(content, url) : null
|
|
877
|
+
if (body && !(body instanceof Response)) item = body
|
|
878
|
+
}
|
|
879
|
+
return Response.json(
|
|
880
|
+
{ kind: 'notFound', item },
|
|
881
|
+
{ status: 404, headers: { vary: CONTENT_VARY } },
|
|
882
|
+
)
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
/** A redirect as data. Never kept, as the site's are not: renaming back must not strand anyone. */
|
|
886
|
+
/**
|
|
887
|
+
* `v2/menus/{alias}` (story 141): a menu's items in the request's culture. A
|
|
888
|
+
* page the caller may not open, or of a type the API does not serve, is left
|
|
889
|
+
* out with the items below it, as a members-only page is from a query.
|
|
890
|
+
*/
|
|
891
|
+
async function menuAnswer(
|
|
892
|
+
request: Request,
|
|
893
|
+
alias: string,
|
|
894
|
+
preview: PreviewAccess | undefined,
|
|
895
|
+
): Promise<Response> {
|
|
896
|
+
const r = await contentRequest(request, preview)
|
|
897
|
+
const menu = r.known ? await r.source.menu(alias, r.culture) : undefined
|
|
898
|
+
if (!menu) return bare(404)
|
|
899
|
+
const pages: PublishedContent[] = []
|
|
900
|
+
const shape = (items: readonly MenuItem[]): Record<string, unknown>[] =>
|
|
901
|
+
items.flatMap((item) => {
|
|
902
|
+
let route: ApiRoute | undefined
|
|
903
|
+
if (item.kind === 'page') {
|
|
904
|
+
const content = item.content ? r.nav.byKey(item.content.key) : undefined
|
|
905
|
+
if (!content || !r.servable(content) || r.ctx.access(content) !== 'allowed') return []
|
|
906
|
+
route = r.ctx.route(content)
|
|
907
|
+
pages.push(content)
|
|
908
|
+
}
|
|
909
|
+
return [
|
|
910
|
+
{
|
|
911
|
+
label: item.label,
|
|
912
|
+
kind: item.kind,
|
|
913
|
+
id: item.key,
|
|
914
|
+
url: item.kind === 'page' ? null : item.url,
|
|
915
|
+
route: route ?? null,
|
|
916
|
+
target: item.target,
|
|
917
|
+
children: shape(item.children),
|
|
918
|
+
},
|
|
919
|
+
]
|
|
920
|
+
})
|
|
921
|
+
const items = shape(menu.items)
|
|
922
|
+
return holding(json({ alias: menu.alias, items }), pages.map(page), [
|
|
923
|
+
menu.key,
|
|
924
|
+
...pages.map((p) => p.key),
|
|
925
|
+
])
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
function redirectAnswer(location: string, statusCode: number): Response {
|
|
929
|
+
return Response.json(
|
|
930
|
+
{
|
|
931
|
+
kind: 'redirect',
|
|
932
|
+
location,
|
|
933
|
+
statusCode,
|
|
934
|
+
permanent: statusCode === 301 || statusCode === 308,
|
|
935
|
+
},
|
|
936
|
+
{ headers: { vary: CONTENT_VARY, 'cache-control': 'no-store' } },
|
|
937
|
+
)
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
/** Drafts for a preview with the key or a preview token; null when it may not preview. */
|
|
941
|
+
async function previewAccess(request: Request): Promise<PreviewAccess | null> {
|
|
942
|
+
if (!settings.enabled) return null
|
|
943
|
+
const keyed = hasValidApiKey(settings, request)
|
|
944
|
+
const access = await ports.preview?.(request, keyed)
|
|
945
|
+
if (access) return access
|
|
946
|
+
// Without drafts to read, a keyed preview answers from what is published, as it always has.
|
|
947
|
+
return keyed && !ports.preview ? { cache } : null
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
async function contentRoute(
|
|
951
|
+
request: Request,
|
|
952
|
+
url: URL,
|
|
953
|
+
rest: string | undefined,
|
|
954
|
+
tail: string,
|
|
955
|
+
preview: PreviewAccess | undefined,
|
|
956
|
+
): Promise<Response> {
|
|
957
|
+
const r = await contentRequest(request, preview)
|
|
958
|
+
if (r.badStartItem) return Response.json('The Start-Item could not be found', { status: 404 })
|
|
959
|
+
if (tail === '' && rest === undefined) return contentQuery(r, url)
|
|
960
|
+
if (tail === 'items') return contentItems(r, url)
|
|
961
|
+
if (rest?.startsWith('item')) {
|
|
962
|
+
const target = rest.replace(/^item\/?/, '').replace(/\/$/, '')
|
|
963
|
+
// Umbraco's address for a page in preview, whether or not it has a route.
|
|
964
|
+
const previewKey = preview ? PREVIEW_PATH.exec(target)?.[1] : undefined
|
|
965
|
+
if (previewKey) return contentItem(r, r.nav.byKey(previewKey.toLowerCase()), url)
|
|
966
|
+
return contentItem(r, GUID.test(target) ? r.nav.byKey(target) : r.byPath(target), url)
|
|
967
|
+
}
|
|
968
|
+
return bare(404)
|
|
551
969
|
}
|
|
552
970
|
}
|
package/src/index.ts
CHANGED
package/src/output.ts
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
* holds: content, media, links, blocks and each editor's value, in Umbraco
|
|
4
4
|
* 18.2's shapes. docs/delivery-api.md, "Output".
|
|
5
5
|
*/
|
|
6
|
+
|
|
7
|
+
import type { SchemaForm } from '@crombolo/core'
|
|
6
8
|
import {
|
|
7
9
|
type BlockGridItem,
|
|
8
10
|
type BlockItem,
|
|
@@ -17,6 +19,7 @@ import {
|
|
|
17
19
|
RawHtml,
|
|
18
20
|
} from '@crombolo/render'
|
|
19
21
|
import { type ExpansionNode, keeps, nextNode } from './expansion.ts'
|
|
22
|
+
import { apiFormReference } from './forms.ts'
|
|
20
23
|
import type { Access } from './protection.ts'
|
|
21
24
|
|
|
22
25
|
export interface ApiRoute {
|
|
@@ -34,6 +37,8 @@ export interface OutputContext {
|
|
|
34
37
|
allowedType(alias: string): boolean
|
|
35
38
|
/** Whether the caller may see a page's properties when a reference to it is expanded. */
|
|
36
39
|
access(content: PublishedContent): Access
|
|
40
|
+
/** An expanded form picker's form, as `v2/forms/{key}` answers it (story 056). */
|
|
41
|
+
form?(form: SchemaForm): Record<string, unknown>
|
|
37
42
|
}
|
|
38
43
|
|
|
39
44
|
const iso = (date: Date): string => date.toISOString()
|
|
@@ -283,6 +288,11 @@ export function deliveryValue(
|
|
|
283
288
|
switch (property.editorAlias) {
|
|
284
289
|
case 'Umbraco.MemberPicker':
|
|
285
290
|
return '(unsupported)'
|
|
291
|
+
// Never the stored definition, whose workflows hold the site's addresses and settings.
|
|
292
|
+
case 'Crombolo.FormPicker': {
|
|
293
|
+
const form = converted as SchemaForm
|
|
294
|
+
return expand !== undefined && ctx.form ? ctx.form(form) : apiFormReference(form)
|
|
295
|
+
}
|
|
286
296
|
case 'Umbraco.RichText':
|
|
287
297
|
return { markup: plain(converted), blocks: [] }
|
|
288
298
|
case 'Umbraco.ContentPicker': {
|
package/src/settings.ts
CHANGED
|
@@ -22,6 +22,17 @@ export interface DeliveryApiSettings {
|
|
|
22
22
|
/** Never served; ignored when the allow list has entries. */
|
|
23
23
|
disallowedContentTypeAliases: string[]
|
|
24
24
|
media: { enabled: boolean; publicAccess: boolean }
|
|
25
|
+
/**
|
|
26
|
+
* Origins whose pages may call the API from the browser, e.g.
|
|
27
|
+
* `https://app.example.com`; `*` for any, only while the API is public.
|
|
28
|
+
*/
|
|
29
|
+
cors: { allowedOrigins: string[] }
|
|
30
|
+
/**
|
|
31
|
+
* Previewing drafts in an app (story 053): where the backoffice's Preview
|
|
32
|
+
* button sends an editor, with `{path}`, `{id}`, `{culture}` and `{token}`
|
|
33
|
+
* filled in; per content type alias in `urls`, which wins over `url`.
|
|
34
|
+
*/
|
|
35
|
+
preview: { url: string | undefined; urls: Record<string, string>; tokenMinutes: number }
|
|
25
36
|
memberAuthorization: {
|
|
26
37
|
authorizationCodeFlow: {
|
|
27
38
|
enabled: boolean
|
|
@@ -69,6 +80,24 @@ export function resolveDeliveryApiSettings(options: DeliveryApiOptions = {}): De
|
|
|
69
80
|
enabled: options.media?.enabled ?? false,
|
|
70
81
|
publicAccess: options.media?.publicAccess ?? true,
|
|
71
82
|
},
|
|
83
|
+
cors: {
|
|
84
|
+
allowedOrigins: [...(options.cors?.allowedOrigins ?? [])].filter(
|
|
85
|
+
(origin): origin is string => typeof origin === 'string' && origin.trim() !== '',
|
|
86
|
+
),
|
|
87
|
+
},
|
|
88
|
+
preview: {
|
|
89
|
+
url: options.preview?.url?.trim() || undefined,
|
|
90
|
+
urls: Object.fromEntries(
|
|
91
|
+
Object.entries(options.preview?.urls ?? {}).filter(
|
|
92
|
+
(entry): entry is [string, string] =>
|
|
93
|
+
typeof entry[1] === 'string' && entry[1].trim() !== '',
|
|
94
|
+
),
|
|
95
|
+
),
|
|
96
|
+
tokenMinutes:
|
|
97
|
+
Number.isFinite(options.preview?.tokenMinutes) && (options.preview?.tokenMinutes ?? 0) > 0
|
|
98
|
+
? (options.preview?.tokenMinutes as number)
|
|
99
|
+
: 60,
|
|
100
|
+
},
|
|
72
101
|
memberAuthorization: {
|
|
73
102
|
authorizationCodeFlow: {
|
|
74
103
|
enabled: code.enabled ?? false,
|
|
@@ -135,3 +164,50 @@ export function memberAuthorizationProblems(settings: DeliveryApiSettings): stri
|
|
|
135
164
|
}
|
|
136
165
|
return problems
|
|
137
166
|
}
|
|
167
|
+
|
|
168
|
+
/** A preview URL must say where the app is: a scheme and host. Pure. */
|
|
169
|
+
const isAppUrl = (url: string) => /^https?:\/\/[^/]+/i.test(url)
|
|
170
|
+
|
|
171
|
+
/** Preview URLs that cannot be used, said once at boot and then ignored. Pure. */
|
|
172
|
+
export function previewProblems(settings: DeliveryApiSettings): string[] {
|
|
173
|
+
const named = [
|
|
174
|
+
...(settings.preview.url ? [['preview.url', settings.preview.url]] : []),
|
|
175
|
+
...Object.entries(settings.preview.urls).map(([alias, url]) => [`preview.urls.${alias}`, url]),
|
|
176
|
+
] as Array<[string, string]>
|
|
177
|
+
return named
|
|
178
|
+
.filter(([, url]) => !isAppUrl(url))
|
|
179
|
+
.map(
|
|
180
|
+
([name, url]) =>
|
|
181
|
+
`The ${name} "${url}" is ignored: it must start with the app's address, such as https://app.example.com.`,
|
|
182
|
+
)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The preview URL for a page of this type, or none; a malformed one is never used. Pure. */
|
|
186
|
+
export function previewUrlFor(
|
|
187
|
+
settings: DeliveryApiSettings,
|
|
188
|
+
contentTypeAlias: string,
|
|
189
|
+
): string | undefined {
|
|
190
|
+
const own = Object.entries(settings.preview.urls).find(
|
|
191
|
+
([alias]) => alias.toLowerCase() === contentTypeAlias.toLowerCase(),
|
|
192
|
+
)?.[1]
|
|
193
|
+
const url = own ?? settings.preview.url
|
|
194
|
+
return url && isAppUrl(url) ? url : undefined
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Whether any page type previews in an app, so the backoffice offers it. Pure. */
|
|
198
|
+
export const previewsInApp = (settings: DeliveryApiSettings): boolean =>
|
|
199
|
+
[settings.preview.url, ...Object.values(settings.preview.urls)].some(
|
|
200
|
+
(url) => url !== undefined && isAppUrl(url),
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
/** The URL with its placeholders filled, each value escaped for where it sits. Pure. */
|
|
204
|
+
export function fillPreviewUrl(
|
|
205
|
+
template: string,
|
|
206
|
+
values: { path: string; id: string; culture: string | null; token: string },
|
|
207
|
+
): string {
|
|
208
|
+
return template
|
|
209
|
+
.replaceAll('{path}', values.path.split('/').map(encodeURIComponent).join('/'))
|
|
210
|
+
.replaceAll('{id}', encodeURIComponent(values.id))
|
|
211
|
+
.replaceAll('{culture}', encodeURIComponent(values.culture ?? ''))
|
|
212
|
+
.replaceAll('{token}', encodeURIComponent(values.token))
|
|
213
|
+
}
|