@plone/aurora 1.0.0-alpha.19 → 1.0.0-alpha.21

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.
@@ -18,6 +18,41 @@ export const ploneUserContext = createContext<
18
18
  >(null);
19
19
  export const ploneClearAuthCookieContext = createContext<boolean>(false);
20
20
 
21
+ /**
22
+ * Where the site root sends a visitor on a multilingual site: the default
23
+ * language root — what Plone's language-switcher view on the site root and
24
+ * Volto's MultilingualRedirector do. The root is managed through its
25
+ * contents view, never visited. The target is the site's default language,
26
+ * not the negotiated interface locale (the locale says nothing about the
27
+ * content tree), and only a language token is accepted as a target.
28
+ */
29
+ export function multilingualRootRedirect(
30
+ pathname: string,
31
+ site: Awaited<ReturnType<PloneClient['getSite']>>['data'] | undefined,
32
+ ): string | undefined {
33
+ if (pathname !== '/' || !site?.features?.multilingual) return undefined;
34
+ const language = site['plone.default_language'];
35
+ return typeof language === 'string' &&
36
+ /^[a-z]{2,3}(-[a-z]{2,4})?$/.test(language)
37
+ ? `/${language}`
38
+ : undefined;
39
+ }
40
+
41
+ /**
42
+ * Where a 401 sends a visitor who is not signed in: the login page, with the
43
+ * requested path as `return_url`, as Volto's Unauthorized view does. No
44
+ * redirect when the request is for the login page itself — the root
45
+ * middleware runs for `/login` with an empty splat, and on a site whose root
46
+ * is private that would loop.
47
+ */
48
+ export function unauthorizedLoginRedirect(
49
+ path: string,
50
+ pathname: string = path,
51
+ ): string | undefined {
52
+ if (pathname === '/login') return undefined;
53
+ return `/login?return_url=${encodeURIComponent(path)}`;
54
+ }
55
+
21
56
  function getAuthorizedResourceHeaders(
22
57
  request: Request,
23
58
  token?: string,
@@ -33,11 +68,62 @@ function getAuthorizedResourceHeaders(
33
68
  return headers;
34
69
  }
35
70
 
71
+ /**
72
+ * Returns the `PloneClient` class registered as the `ploneClient` utility,
73
+ * extended with the methods of every registered `clientEndpoints` utility.
74
+ */
75
+ export function getPloneClientClass() {
76
+ const PloneClient = config
77
+ .getUtility({
78
+ name: 'ploneClient',
79
+ type: 'client',
80
+ })
81
+ .method();
82
+
83
+ const endpoints = config
84
+ .getUtilities({ type: 'clientEndpoints' })
85
+ .map((utility) => utility.method());
86
+
87
+ return endpoints.length > 0
88
+ ? PloneClient.extend(Object.assign({}, ...endpoints))
89
+ : PloneClient;
90
+ }
91
+
92
+ /**
93
+ * Whether a route pattern names a resource: one of its segments starts with
94
+ * a single `@`, like `@search/*` or `@@contents/@delete/*`. Views use `@@`.
95
+ */
96
+ export function isResourcePattern(pattern: string) {
97
+ return pattern.split('/').some((segment) => /^@(?!@)/.test(segment));
98
+ }
99
+
100
+ // The health check keeps its conventional path, `/ok`, instead of `@ok`.
101
+ const HEALTH_CHECK_PATTERN = 'ok';
102
+
103
+ /**
104
+ * Whether the route matched by a request doesn't need the Plone content,
105
+ * site and user: resource routes (see `isResourcePattern`) and the health
106
+ * check don't, any other route does.
107
+ */
108
+ export function routeSkipsContent(pattern: string) {
109
+ return (
110
+ pattern.replace(/^\/+/, '') === HEALTH_CHECK_PATTERN ||
111
+ isResourcePattern(pattern)
112
+ );
113
+ }
114
+
115
+ // Module-level, so the configuration is applied once per process. During
116
+ // development, editing the configuration re-evaluates this module through
117
+ // HMR, which resets the flag and applies the new configuration.
118
+ let serverConfigInstalled = false;
119
+
36
120
  export const installServerMiddleware: Route.MiddlewareFunction = async (
37
121
  { request, context },
38
122
  next,
39
123
  ) => {
124
+ if (serverConfigInstalled) return;
40
125
  installServer();
126
+ serverConfigInstalled = true;
41
127
  };
42
128
 
43
129
  export const PloneClientMiddleware: Route.MiddlewareFunction = async (
@@ -46,12 +132,7 @@ export const PloneClientMiddleware: Route.MiddlewareFunction = async (
46
132
  ) => {
47
133
  const token = await getAuthFromRequest(request);
48
134
 
49
- const PloneClient = config
50
- .getUtility({
51
- name: 'ploneClient',
52
- type: 'client',
53
- })
54
- .method();
135
+ const PloneClient = getPloneClientClass();
55
136
 
56
137
  const cli = PloneClient.initialize({
57
138
  apiPath: config.settings.apiPath,
@@ -99,15 +180,24 @@ export const getAPIResourceWithAuth: Route.MiddlewareFunction = async (
99
180
  ) {
100
181
  const token = await getAuthFromRequest(request);
101
182
  const url = `${config.settings.apiPath}${path}`;
183
+ const resourceHeaders = (authToken?: string) => {
184
+ const headers = new Headers(
185
+ getAuthorizedResourceHeaders(request, authToken),
186
+ );
187
+ // The REST API's portrait endpoint is selected through JSON content
188
+ // negotiation, even though its response is an image.
189
+ if (/\/@portrait\//.test(path)) headers.set('Accept', 'application/json');
190
+ return headers;
191
+ };
102
192
  const response = await fetch(url, {
103
193
  method: 'GET',
104
- headers: getAuthorizedResourceHeaders(request, token),
194
+ headers: resourceHeaders(token),
105
195
  });
106
196
 
107
197
  if (token && response.status === 401) {
108
198
  const anonymousResponse = await fetch(url, {
109
199
  method: 'GET',
110
- headers: getAuthorizedResourceHeaders(request),
200
+ headers: resourceHeaders(),
111
201
  });
112
202
 
113
203
  if (anonymousResponse.ok) {
@@ -133,18 +223,94 @@ export const getAPIResourceWithAuth: Route.MiddlewareFunction = async (
133
223
  }
134
224
  };
135
225
 
226
+ /**
227
+ * Splits a request path into a content path and a `contentResource` utility
228
+ * below it: `/news/@blocks-schema/teaser` gives `/news`, `@blocks-schema`
229
+ * and `teaser`. The first `@`-prefixed segment after the content path that
230
+ * names a registered utility wins. Returns undefined when none matches.
231
+ */
232
+ export function matchContentResource(path: string) {
233
+ const segments = path.split('/').filter(Boolean);
234
+
235
+ for (let index = 1; index < segments.length; index++) {
236
+ const name = segments[index];
237
+ if (!/^@(?!@)/.test(name)) continue;
238
+ const utility = config.getUtility({ name, type: 'contentResource' });
239
+ if (!utility.method) continue;
240
+
241
+ return {
242
+ method: utility.method,
243
+ path: `/${segments.slice(0, index).join('/')}`,
244
+ subpath: segments.slice(index + 1).join('/') || undefined,
245
+ };
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Answers the requests for a resource below a content path, like
251
+ * `/news/@blocks-schema`, with the `contentResource` utility named after the
252
+ * resource. React Router can't match a route below a splat, so they are
253
+ * handled here, before the content of the path is fetched.
254
+ */
255
+ export const contentResourceMiddleware: Route.MiddlewareFunction = async ({
256
+ request,
257
+ params,
258
+ }) => {
259
+ const match = matchContentResource(`/${params['*'] || ''}`);
260
+ if (!match) return;
261
+
262
+ return match.method({
263
+ request,
264
+ path: match.path,
265
+ subpath: match.subpath,
266
+ });
267
+ };
268
+
269
+ function matchesExpanderPath(path: string, match: string) {
270
+ const prefix = match.replace(/\/+$/, '');
271
+ return prefix === '' || path === prefix || path.startsWith(`${prefix}/`);
272
+ }
273
+
274
+ /**
275
+ * Returns the components to expand in the content request of `path`, as
276
+ * declared in `config.settings.apiExpanders` (see `defaultApiExpanders` in
277
+ * `config/server.server.ts` for the core ones). Expanders flagged
278
+ * `authenticated` apply only to signed-in users, so that anonymous requests,
279
+ * and their cache keys, stay unchanged.
280
+ */
281
+ export function getContentExpand(path: string, authenticated: boolean) {
282
+ const expand: string[] = [];
283
+
284
+ for (const expander of config.settings.apiExpanders ?? []) {
285
+ // Volto-shaped expanders (`GET_CONTENT`) do not apply to Plone Aurora.
286
+ if (!('expand' in expander)) continue;
287
+ if (expander.authenticated && !authenticated) continue;
288
+ if (!matchesExpanderPath(path, expander.match)) continue;
289
+ for (const name of expander.expand) {
290
+ if (!expand.includes(name)) expand.push(name);
291
+ }
292
+ }
293
+
294
+ return expand;
295
+ }
296
+
136
297
  export const fetchPloneContent: Route.MiddlewareFunction = async (
137
- { request, params, context },
298
+ { request, params, context, pattern, url },
138
299
  next,
139
300
  ) => {
140
- const expand = ['navroot', 'breadcrumbs', 'navigation', 'actions'];
301
+ if (routeSkipsContent(pattern)) return;
302
+
141
303
  const token = await getAuthFromRequest(request);
142
304
 
143
305
  let cli = context.get(ploneClientContext);
144
306
 
145
307
  const path = `/${params['*'] || ''}`;
308
+ // The request's path as the router matched it (a `.data` suffix already
309
+ // stripped) — not the splat, which is empty for /login as well as for /.
310
+ const pathname = (url ?? new URL(request.url)).pathname;
146
311
 
147
312
  let userId = '';
313
+ let tokenExpired = false;
148
314
  if (token) {
149
315
  try {
150
316
  const decodedToken = jwtDecode<{
@@ -153,10 +319,13 @@ export const fetchPloneContent: Route.MiddlewareFunction = async (
153
319
  fullname: string | null;
154
320
  }>(token);
155
321
  userId = decodedToken.sub || '';
322
+ tokenExpired =
323
+ typeof decodedToken.exp === 'number' &&
324
+ decodedToken.exp * 1000 < Date.now();
156
325
  } catch {}
157
326
  }
158
327
 
159
- if (userId) expand.push('types');
328
+ const expand = getContentExpand(path, !!userId);
160
329
 
161
330
  const setPloneContext = (
162
331
  content: Awaited<ReturnType<PloneClient['getContent']>>,
@@ -178,6 +347,12 @@ export const fetchPloneContent: Route.MiddlewareFunction = async (
178
347
  ]);
179
348
 
180
349
  setPloneContext(content, site, user?.data ?? null);
350
+
351
+ // On a multilingual site the root is managed, not visited: a request
352
+ // for / — a full load or a client-side navigation — goes to the default
353
+ // language root.
354
+ const rootRedirect = multilingualRootRedirect(pathname, site.data);
355
+ if (rootRedirect) return redirect(rootRedirect);
181
356
  } catch (error: any) {
182
357
  if (error.status >= 300 && error.status < 400 && error.location) {
183
358
  return redirect(error.location, {
@@ -185,12 +360,7 @@ export const fetchPloneContent: Route.MiddlewareFunction = async (
185
360
  });
186
361
  }
187
362
  if (token && error?.status === 401) {
188
- const PloneClient = config
189
- .getUtility({
190
- name: 'ploneClient',
191
- type: 'client',
192
- })
193
- .method();
363
+ const PloneClient = getPloneClientClass();
194
364
  cli = PloneClient.initialize({
195
365
  apiPath: config.settings.apiPath,
196
366
  });
@@ -200,15 +370,29 @@ export const fetchPloneContent: Route.MiddlewareFunction = async (
200
370
  const [content, site] = await Promise.all([
201
371
  cli.getContent({
202
372
  path,
203
- expand: expand.filter((item) => item !== 'types'),
373
+ expand: getContentExpand(path, false),
204
374
  }),
205
375
  cli.getSite(),
206
376
  ]);
207
377
 
208
378
  setPloneContext(content, site, null);
209
379
  context.set(ploneClearAuthCookieContext, true);
380
+
381
+ // The same root rule after an expired cookie's anonymous retry; the
382
+ // redirect leaves before the root loader, so it clears the cookie
383
+ // itself.
384
+ const rootRedirect = multilingualRootRedirect(pathname, site.data);
385
+ if (rootRedirect) return clearAuthOnResponse(redirect(rootRedirect));
210
386
  return;
211
387
  } catch (anonymousError: any) {
388
+ // An expired token is no sign-in at all (Aurora's cookie expires with
389
+ // the token): the visitor logs in again and comes back here. A live
390
+ // token without permission keeps the 401 page.
391
+ const loginRedirect =
392
+ tokenExpired && anonymousError?.status === 401
393
+ ? unauthorizedLoginRedirect(path, pathname)
394
+ : undefined;
395
+ if (loginRedirect) return clearAuthOnResponse(redirect(loginRedirect));
212
396
  throw data('Content Not Found', {
213
397
  status:
214
398
  typeof anonymousError.status === 'number'
@@ -218,6 +402,12 @@ export const fetchPloneContent: Route.MiddlewareFunction = async (
218
402
  }
219
403
  }
220
404
 
405
+ const loginRedirect =
406
+ !token && error?.status === 401
407
+ ? unauthorizedLoginRedirect(path, pathname)
408
+ : undefined;
409
+ if (loginRedirect) return redirect(loginRedirect);
410
+
221
411
  throw data('Content Not Found', {
222
412
  status: typeof error.status === 'number' ? error.status : 500,
223
413
  });
@@ -225,9 +415,11 @@ export const fetchPloneContent: Route.MiddlewareFunction = async (
225
415
  };
226
416
 
227
417
  export const linkMiddleware: Route.MiddlewareFunction = async (
228
- { context },
418
+ { context, pattern },
229
419
  next,
230
420
  ) => {
421
+ if (routeSkipsContent(pattern)) return;
422
+
231
423
  const content = context.get(ploneContentContext);
232
424
 
233
425
  if (
package/app/root.tsx CHANGED
@@ -8,6 +8,7 @@ import {
8
8
  ploneClearAuthCookieContext,
9
9
  fetchPloneContent,
10
10
  getAPIResourceWithAuth,
11
+ contentResourceMiddleware,
11
12
  installServerMiddleware,
12
13
  PloneClientMiddleware,
13
14
  otherResources,
@@ -25,6 +26,7 @@ export const middleware = [
25
26
  PloneClientMiddleware,
26
27
  otherResources,
27
28
  getAPIResourceWithAuth,
29
+ contentResourceMiddleware,
28
30
  fetchPloneContent,
29
31
  linkMiddleware,
30
32
  ];
package/app/routes.ts CHANGED
@@ -10,7 +10,7 @@ import addonsInfo from '../.plone/registry.addonsInfo.json';
10
10
 
11
11
  const routes: RouteConfig = [
12
12
  route('ok', 'okroute.tsx', { id: 'ok' }),
13
- route('reset-fetcher', 'reset-fetcher.tsx', { id: 'reset-fetcher' }),
13
+ route('@reset-fetcher', 'reset-fetcher.tsx', { id: 'reset-fetcher' }),
14
14
  ...getAddonRoutesConfig(
15
15
  (addonsRoutes as ReactRouterRouteEntry[]) || [],
16
16
  addonsInfo,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@plone/aurora",
3
3
  "description": "Plone Aurora is the next-generation frontend for Plone CMS",
4
- "version": "1.0.0-alpha.19",
4
+ "version": "1.0.0-alpha.21",
5
5
  "maintainers": [
6
6
  {
7
7
  "name": "Plone Foundation",
@@ -32,43 +32,44 @@
32
32
  },
33
33
  "type": "module",
34
34
  "dependencies": {
35
- "@react-router/node": "8.2.0",
36
- "@react-router/serve": "8.2.0",
35
+ "@plone/agave": "1.0.0-alpha.9",
36
+ "@plone/blocks": "1.0.0-alpha.19",
37
+ "@plone/client": "2.0.0-alpha.10",
38
+ "@plone/cmsui": "1.0.0-alpha.14",
39
+ "@plone/components": "5.0.0-alpha.6",
40
+ "@plone/icons": "1.0.0-alpha.3",
41
+ "@plone/contents": "1.0.0-alpha.4",
42
+ "@plone/helpers": "2.0.0-alpha.11",
43
+ "@plone/layout": "1.0.0-alpha.16",
44
+ "@plone/plate": "1.0.0-alpha.26",
45
+ "@plone/publicui": "1.0.0-alpha.9",
46
+ "@plone/quanta": "1.0.0-alpha.3",
47
+ "@plone/react-router": "2.0.0-alpha.8",
48
+ "@plone/registry": "4.0.0-alpha.7",
49
+ "@plone/theming": "1.0.0-alpha.10",
50
+ "@react-router/node": "8.5.0",
51
+ "@react-router/serve": "8.5.0",
37
52
  "i18next": "^26.3.6",
38
53
  "i18next-browser-languagedetector": "^8.0.4",
39
54
  "i18next-fs-backend": "^2.6.0",
40
55
  "i18next-http-backend": "^3.0.2",
41
56
  "isbot": "^5.1.27",
42
57
  "jwt-decode": "^4.0.0",
43
- "react": "^19.2.0",
44
- "react-dom": "^19.2.0",
58
+ "react": "^19.2.7",
59
+ "react-dom": "^19.2.7",
45
60
  "react-i18next": "^15.4.1",
46
- "react-router": "8.2.0",
47
- "remix-i18next": "^8.0.0",
48
- "@plone/agave": "1.0.0-alpha.9",
49
- "@plone/blocks": "1.0.0-alpha.18",
50
- "@plone/client": "2.0.0-alpha.8",
51
- "@plone/cmsui": "1.0.0-alpha.12",
52
- "@plone/components": "5.0.0-alpha.5",
53
- "@plone/icons": "1.0.0-alpha.1",
54
- "@plone/contents": "1.0.0-alpha.3",
55
- "@plone/helpers": "2.0.0-alpha.9",
56
- "@plone/plate": "1.0.0-alpha.25",
57
- "@plone/layout": "1.0.0-alpha.14",
58
- "@plone/publicui": "1.0.0-alpha.8",
59
- "@plone/react-router": "2.0.0-alpha.7",
60
- "@plone/registry": "4.0.0-alpha.5",
61
- "@plone/theming": "1.0.0-alpha.9",
62
- "@plone/quanta": "1.0.0-alpha.2"
61
+ "react-router": "8.5.0",
62
+ "remix-i18next": "^8.0.0"
63
63
  },
64
64
  "devDependencies": {
65
65
  "@babel/core": "^7.28.5",
66
66
  "@babel/preset-typescript": "^7.27.1",
67
- "@react-router/dev": "8.2.0",
67
+ "@plone/types": "3.0.0-alpha.9",
68
+ "@react-router/dev": "8.5.0",
68
69
  "@tailwindcss/vite": "^4.2.2",
69
70
  "@testing-library/jest-dom": "^6.6.3",
70
71
  "@testing-library/react": "^16.2.0",
71
- "@types/node": "^24",
72
+ "@types/node": "^26",
72
73
  "@types/react": "^19.2.0",
73
74
  "@types/react-dom": "^19.2.0",
74
75
  "@vitest/coverage-v8": "^4.1.4",
@@ -79,8 +80,7 @@
79
80
  "vite": "^8.0.8",
80
81
  "vite-plugin-babel": "1.7.3",
81
82
  "vite-plugin-devtools-json": "^1.0.0",
82
- "vitest": "^4.1.0",
83
- "@plone/types": "3.0.0-alpha.7"
83
+ "vitest": "^4.1.0"
84
84
  },
85
85
  "engines": {
86
86
  "node": ">=22.22.0"
@@ -1,5 +1,23 @@
1
1
  import type { Config } from '@react-router/dev/config';
2
2
 
3
+ // React Router aborts an action whose `Origin` header doesn't match the origin
4
+ // of the request URL. Behind a proxy that terminates TLS, `react-router-serve`
5
+ // sees the request as `http` while the browser sends an `https` origin, so every
6
+ // action (login included) fails with a 400. The hosts listed here, comma
7
+ // separated and with `*`/`**` wildcards, are accepted as action origins. The
8
+ // list is read when building, and unset it allows only same-origin actions.
9
+ const allowedActionOrigins =
10
+ process.env.REACT_ROUTER_ALLOWED_ACTION_ORIGINS?.split(',')
11
+ .map((origin) => origin.trim())
12
+ .filter(Boolean);
13
+
3
14
  export default {
4
15
  ssr: true,
16
+ // The build directory may be named by the environment, so a deployment can build
17
+ // ASIDE into a versioned directory (for example build.live-<stamp>) and then swap a
18
+ // symlink, instead of writing into the directory a running server is serving from —
19
+ // `react-router build` removes its build directory before it writes. Unset, the
20
+ // default `build` is unchanged.
21
+ buildDirectory: process.env.REACT_ROUTER_BUILD_DIR || 'build',
22
+ ...(allowedActionOrigins?.length ? { allowedActionOrigins } : {}),
5
23
  } satisfies Config;
package/vite.config.ts CHANGED
@@ -68,15 +68,12 @@ export default defineConfig(({ command, mode, isSsrBuild }) => {
68
68
  '@plone/components > clsx',
69
69
  '@plone/components > react-aria',
70
70
  '@plone/components > react-aria-components',
71
- '@plone/components > react-aria-components/DropZone',
72
71
  '@plone/icons > @react-aria/utils',
73
72
  '@plone/icons > @react-spectrum/utils',
74
73
  '@plone/icons > clsx',
75
74
  '@plone/icons > tailwind-variants',
76
75
  '@plone/quanta > @internationalized/date',
77
- '@plone/quanta > @react-aria/utils',
78
76
  '@plone/quanta > clsx',
79
- '@plone/quanta > react-aria',
80
77
  '@plone/quanta > react-aria-components',
81
78
  '@plone/quanta > react-aria-components/DropZone',
82
79
  '@plone/quanta > react-aria-components/Form',
@@ -85,11 +82,11 @@ export default defineConfig(({ command, mode, isSsrBuild }) => {
85
82
  '@plone/quanta > react-aria-components/Table',
86
83
  '@plone/quanta > react-aria-components/Tooltip',
87
84
  '@plone/quanta > react-aria-components/composeRenderProps',
88
- '@plone/quanta > react-stately',
89
85
  '@plone/quanta > tailwind-merge',
90
86
  '@plone/quanta > tailwind-variants',
91
87
  '@plone/helpers > jotai',
92
88
  '@plone/helpers > jotai/utils',
89
+ '@plone/helpers > jotai/vanilla',
93
90
  '@plone/helpers > jotai-optics',
94
91
  ],
95
92
  },