@plone/aurora 1.0.0-alpha.5

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.
Files changed (41) hide show
  1. package/.release-it.json +29 -0
  2. package/.stylelintrc +8 -0
  3. package/CHANGELOG.md +211 -0
  4. package/LICENSE.md +21 -0
  5. package/Makefile +82 -0
  6. package/README.md +33 -0
  7. package/acceptance/tests/basic.test.ts +14 -0
  8. package/app/config/index.test.ts +19 -0
  9. package/app/config/index.ts +15 -0
  10. package/app/config/server/content-migrations.server.test.ts +184 -0
  11. package/app/config/server/content-migrations.server.ts +59 -0
  12. package/app/config/server/migrations.server.ts +137 -0
  13. package/app/config/server.server.test.ts +33 -0
  14. package/app/config/server.server.ts +52 -0
  15. package/app/config/types.ts +42 -0
  16. package/app/entry.client.tsx +51 -0
  17. package/app/entry.server.tsx +81 -0
  18. package/app/i18n.ts +11 -0
  19. package/app/i18next.server.ts +26 -0
  20. package/app/middleware.server.test.ts +1088 -0
  21. package/app/middleware.server.ts +241 -0
  22. package/app/okroute.test.tsx +9 -0
  23. package/app/okroute.tsx +5 -0
  24. package/app/reset-fetcher.test.tsx +13 -0
  25. package/app/reset-fetcher.tsx +7 -0
  26. package/app/root.test.tsx +300 -0
  27. package/app/root.tsx +178 -0
  28. package/app/routes.ts +20 -0
  29. package/news/.gitkeep +0 -0
  30. package/package.json +103 -0
  31. package/public/favicon.ico +0 -0
  32. package/public/icon.svg +13 -0
  33. package/react-router.config.ts +5 -0
  34. package/registry-publicui.config.ts +11 -0
  35. package/registry.config.ts +13 -0
  36. package/tests/setup.ts +6 -0
  37. package/tests/testHelpers.tsx +29 -0
  38. package/towncrier.toml +33 -0
  39. package/tsconfig.json +35 -0
  40. package/vite.config.ts +111 -0
  41. package/vitest.config.ts +32 -0
@@ -0,0 +1,1088 @@
1
+ import { expect, describe, it, vi, afterEach } from 'vitest';
2
+ import config from '@plone/registry';
3
+ import { RouterContextProvider } from 'react-router';
4
+ import { jwtDecode } from 'jwt-decode';
5
+ import { getAuthFromRequest } from '@plone/react-router';
6
+ import {
7
+ fetchPloneContent,
8
+ getAPIResourceWithAuth,
9
+ installServerMiddleware,
10
+ linkMiddleware,
11
+ ploneClearAuthCookieContext,
12
+ PloneClientMiddleware,
13
+ otherResources,
14
+ ploneClientContext,
15
+ ploneContentContext,
16
+ ploneSiteContext,
17
+ ploneUserContext,
18
+ } from './middleware.server';
19
+
20
+ vi.mock('jwt-decode');
21
+ vi.mock('@plone/react-router', async (importOriginal) => {
22
+ const actual = await importOriginal<typeof import('@plone/react-router')>();
23
+ return {
24
+ ...actual,
25
+ getAuthFromRequest: vi.fn(),
26
+ };
27
+ });
28
+
29
+ describe('middleware', () => {
30
+ const initializePloneClientContext = async (
31
+ request: Request,
32
+ context: RouterContextProvider,
33
+ ) => {
34
+ await PloneClientMiddleware(
35
+ {
36
+ request,
37
+ context,
38
+ params: {},
39
+ pattern: '/',
40
+ url: new URL(request.url),
41
+ },
42
+ vi.fn(),
43
+ );
44
+ };
45
+
46
+ const registerPloneClientFactory = (ploneClient: Record<string, unknown>) => {
47
+ config.registerUtility({
48
+ name: 'ploneClient',
49
+ type: 'client',
50
+ method: () =>
51
+ ({
52
+ prototype: {},
53
+ initialize: vi.fn().mockReturnValue(ploneClient),
54
+ }) as any,
55
+ });
56
+ };
57
+
58
+ afterEach(() => {
59
+ vi.resetAllMocks();
60
+ vi.restoreAllMocks();
61
+ });
62
+
63
+ describe('installServerMiddleware', () => {
64
+ it('installs the basic config correctly', async () => {
65
+ const request = new Request('http://example.com');
66
+ const context = new RouterContextProvider();
67
+ const nextMock = vi.fn();
68
+
69
+ await installServerMiddleware(
70
+ {
71
+ request,
72
+ context,
73
+ params: {},
74
+ pattern: '/',
75
+ url: new URL(request.url),
76
+ },
77
+ nextMock,
78
+ );
79
+
80
+ expect(config.settings).toStrictEqual(
81
+ expect.objectContaining({
82
+ supportedLanguages: ['en'],
83
+ defaultLanguage: 'en',
84
+ apiPath: 'http://localhost:8080/Plone',
85
+ }),
86
+ );
87
+ expect(
88
+ config
89
+ .getUtility({
90
+ name: 'ploneClient',
91
+ type: 'client',
92
+ })
93
+ .method(),
94
+ ).toHaveProperty('initialize');
95
+ });
96
+ });
97
+
98
+ describe('PloneClientMiddleware', () => {
99
+ it('initializes the PloneClient and sets it in context', async () => {
100
+ const request = new Request('http://example.com');
101
+ const context = new RouterContextProvider();
102
+ const nextMock = vi.fn();
103
+
104
+ vi.mocked(getAuthFromRequest).mockResolvedValue(undefined);
105
+ config.settings.apiPath = 'http://localhost:8080/Plone';
106
+ config.registerUtility({
107
+ name: 'ploneClient',
108
+ type: 'client',
109
+ method: () =>
110
+ ({
111
+ prototype: {},
112
+ initialize: vi.fn().mockReturnValue({
113
+ config: { apiPath: 'http://localhost:8080/Plone' },
114
+ }),
115
+ }) as any,
116
+ });
117
+
118
+ await PloneClientMiddleware(
119
+ {
120
+ request,
121
+ context,
122
+ params: {},
123
+ pattern: '/',
124
+ url: new URL(request.url),
125
+ },
126
+ nextMock,
127
+ );
128
+
129
+ expect(context.get(ploneClientContext)).toBeDefined();
130
+ });
131
+
132
+ it('initializes PloneClient with token when available', async () => {
133
+ const request = new Request('http://example.com');
134
+ const context = new RouterContextProvider();
135
+ const nextMock = vi.fn();
136
+
137
+ vi.mocked(getAuthFromRequest).mockResolvedValue('valid.jwt.token');
138
+ config.settings.apiPath = 'http://localhost:8080/Plone';
139
+ const initializeMock = vi.fn().mockReturnValue({});
140
+ config.registerUtility({
141
+ name: 'ploneClient',
142
+ type: 'client',
143
+ method: () =>
144
+ ({
145
+ prototype: {},
146
+ initialize: initializeMock,
147
+ }) as any,
148
+ });
149
+
150
+ await PloneClientMiddleware(
151
+ {
152
+ request,
153
+ context,
154
+ params: {},
155
+ pattern: '/',
156
+ url: new URL(request.url),
157
+ },
158
+ nextMock,
159
+ );
160
+
161
+ expect(initializeMock).toHaveBeenCalledWith({
162
+ apiPath: 'http://localhost:8080/Plone',
163
+ token: 'valid.jwt.token',
164
+ });
165
+ });
166
+ });
167
+
168
+ describe('otherResources', () => {
169
+ it('ignore regular internal content requests', async () => {
170
+ const request = new Request('http://example.com');
171
+ const context = new RouterContextProvider();
172
+ const params = { '*': '' };
173
+ const nextMock = vi.fn();
174
+
175
+ await otherResources(
176
+ {
177
+ request,
178
+ params,
179
+ context,
180
+ pattern: '/',
181
+ url: new URL(request.url),
182
+ },
183
+ nextMock,
184
+ );
185
+ });
186
+
187
+ it('blocks requests to special urls: css', async () => {
188
+ const request = new Request('http://example.com');
189
+ const context = new RouterContextProvider();
190
+ const params = { '*': 'style.css' };
191
+ const nextMock = vi.fn();
192
+
193
+ try {
194
+ await otherResources(
195
+ {
196
+ request,
197
+ params,
198
+ context,
199
+ pattern: '/style.css',
200
+ url: new URL(request.url),
201
+ },
202
+ nextMock,
203
+ );
204
+ } catch (err: any) {
205
+ expect(err.init.status).toEqual(404);
206
+ }
207
+ });
208
+
209
+ it('blocks requests to special urls: css.map', async () => {
210
+ const request = new Request('http://example.com');
211
+ const context = new RouterContextProvider();
212
+ const params = { '*': 'style.css.map' };
213
+ const nextMock = vi.fn();
214
+
215
+ try {
216
+ await otherResources(
217
+ {
218
+ request,
219
+ params,
220
+ context,
221
+ pattern: '/style.css.map',
222
+ url: new URL(request.url),
223
+ },
224
+ nextMock,
225
+ );
226
+ } catch (err: any) {
227
+ expect(err.init.status).toEqual(404);
228
+ }
229
+ });
230
+
231
+ // it('blocks requests to special urls: favicon.ico', async () => {
232
+ // const request = new Request('http://example.com');
233
+ // const context = new RouterContextProvider();
234
+ // const params = { '*': 'favicon.ico' };
235
+ // const nextMock = vi.fn();
236
+
237
+ // try {
238
+ // await otherResources({ request, params, context }, nextMock);
239
+ // } catch (err: any) {
240
+ // expect(err.init.status).toEqual(404);
241
+ // }
242
+
243
+ // // This is needed in v7.4.0 even if it should not be mandatory
244
+ // // Relevant issue: https://github.com/remix-run/react-router/issues/13274
245
+ // expect(nextMock).not.toHaveBeenCalled();
246
+ // });
247
+
248
+ // it('blocks requests to special urls: full https links', async () => {
249
+ // const request = new Request('http://example.com');
250
+ // const context = new RouterContextProvider();
251
+ // const params = { '*': 'https://another.site' };
252
+ // const nextMock = vi.fn();
253
+
254
+ // try {
255
+ // await otherResources({ request, params, context }, nextMock);
256
+ // } catch (err: any) {
257
+ // expect(err.init.status).toEqual(404);
258
+ // }
259
+
260
+ // // This is needed in v7.4.0 even if it should not be mandatory
261
+ // // Relevant issue: https://github.com/remix-run/react-router/issues/13274
262
+ // expect(nextMock).not.toHaveBeenCalled();
263
+ // });
264
+
265
+ it('blocks requests to special urls: expand', async () => {
266
+ const request = new Request('http://example.com');
267
+ const context = new RouterContextProvider();
268
+ const params = { '*': '?expand=breadcrumbs' };
269
+ const nextMock = vi.fn();
270
+
271
+ try {
272
+ await otherResources(
273
+ {
274
+ request,
275
+ params,
276
+ context,
277
+ pattern: '/?expand=breadcrumbs',
278
+ url: new URL(request.url),
279
+ },
280
+ nextMock,
281
+ );
282
+ } catch (err: any) {
283
+ expect(err.init.status).toEqual(404);
284
+ }
285
+ });
286
+
287
+ it('blocks requests to special urls: assets', async () => {
288
+ const request = new Request('http://example.com');
289
+ const context = new RouterContextProvider();
290
+ const params = { '*': 'assets/image.png' };
291
+ const nextMock = vi.fn();
292
+
293
+ try {
294
+ await otherResources(
295
+ {
296
+ request,
297
+ params,
298
+ context,
299
+ pattern: '/assets/image.png',
300
+ url: new URL(request.url),
301
+ },
302
+ nextMock,
303
+ );
304
+ } catch (err: any) {
305
+ expect(err.init.status).toEqual(404);
306
+ }
307
+ });
308
+
309
+ it('blocks requests to .well-known paths', async () => {
310
+ const request = new Request('http://example.com');
311
+ const context = new RouterContextProvider();
312
+ const params = {
313
+ '*': '.well-known/appspecific/com.chrome.devtools.json',
314
+ };
315
+ const nextMock = vi.fn();
316
+
317
+ try {
318
+ await otherResources(
319
+ {
320
+ request,
321
+ params,
322
+ context,
323
+ pattern: '/.well-known/appspecific/com.chrome.devtools.json',
324
+ url: new URL(request.url),
325
+ },
326
+ nextMock,
327
+ );
328
+ } catch (err: any) {
329
+ expect(err).toBeInstanceOf(Response);
330
+ expect(err.status).toEqual(200);
331
+ }
332
+ });
333
+ });
334
+
335
+ describe('getAPIResourceWithAuth', () => {
336
+ it('ignore regular internal content requests', async () => {
337
+ const request = new Request('http://example.com');
338
+ const context = new RouterContextProvider();
339
+ const params = { '*': '' };
340
+ const nextMock = vi.fn();
341
+
342
+ await getAPIResourceWithAuth(
343
+ {
344
+ request,
345
+ params,
346
+ context,
347
+ pattern: '/',
348
+ url: new URL(request.url),
349
+ },
350
+ nextMock,
351
+ );
352
+ });
353
+
354
+ it('intercepts requests to special urls: @@images', async () => {
355
+ const request = new Request('http://example.com');
356
+ const context = new RouterContextProvider();
357
+ const params = { '*': 'image.png/@@images/image' };
358
+ const nextMock = vi.fn();
359
+ const fetchMock = vi.fn().mockResolvedValue({
360
+ status: 200,
361
+ body: 'image',
362
+ });
363
+ global.fetch = fetchMock;
364
+
365
+ await getAPIResourceWithAuth(
366
+ {
367
+ request,
368
+ params,
369
+ context,
370
+ pattern: '/image.png/@@images/image',
371
+ url: new URL(request.url),
372
+ },
373
+ nextMock,
374
+ );
375
+
376
+ expect(fetchMock).toHaveBeenCalledWith(
377
+ 'http://localhost:8080/Plone/image.png/@@images/image',
378
+ expect.objectContaining({
379
+ method: 'GET',
380
+ headers: expect.any(Headers),
381
+ }),
382
+ );
383
+ expect(
384
+ (fetchMock.mock.calls[0]?.[1] as { headers: Headers }).headers.get(
385
+ 'Authorization',
386
+ ),
387
+ ).toBeNull();
388
+ });
389
+
390
+ it('intercepts requests to special urls: @@download', async () => {
391
+ const request = new Request('http://example.com');
392
+ const context = new RouterContextProvider();
393
+ const params = { '*': 'file.txt/@@download/file' };
394
+ const nextMock = vi.fn();
395
+ const fetchMock = vi.fn().mockResolvedValue({
396
+ status: 200,
397
+ body: 'file',
398
+ });
399
+ global.fetch = fetchMock;
400
+
401
+ await getAPIResourceWithAuth(
402
+ {
403
+ request,
404
+ params,
405
+ context,
406
+ pattern: '/file.txt/@@download/file',
407
+ url: new URL(request.url),
408
+ },
409
+ nextMock,
410
+ );
411
+
412
+ expect(fetchMock).toHaveBeenCalledWith(
413
+ 'http://localhost:8080/Plone/file.txt/@@download/file',
414
+ expect.objectContaining({
415
+ method: 'GET',
416
+ headers: expect.any(Headers),
417
+ }),
418
+ );
419
+ expect(
420
+ (fetchMock.mock.calls[0]?.[1] as { headers: Headers }).headers.get(
421
+ 'Authorization',
422
+ ),
423
+ ).toBeNull();
424
+ });
425
+
426
+ it('intercepts requests to special urls: @@site-logo', async () => {
427
+ const request = new Request('http://example.com');
428
+ const context = new RouterContextProvider();
429
+ const params = { '*': '@@site-logo/image' };
430
+ const nextMock = vi.fn();
431
+ const fetchMock = vi.fn().mockResolvedValue({
432
+ status: 200,
433
+ body: 'logo',
434
+ });
435
+ global.fetch = fetchMock;
436
+
437
+ await getAPIResourceWithAuth(
438
+ {
439
+ request,
440
+ params,
441
+ context,
442
+ pattern: '/@@site-logo/image',
443
+ url: new URL(request.url),
444
+ },
445
+ nextMock,
446
+ );
447
+
448
+ expect(fetchMock).toHaveBeenCalledWith(
449
+ 'http://localhost:8080/Plone/@@site-logo/image',
450
+ expect.objectContaining({
451
+ method: 'GET',
452
+ headers: expect.any(Headers),
453
+ }),
454
+ );
455
+ expect(
456
+ (fetchMock.mock.calls[0]?.[1] as { headers: Headers }).headers.get(
457
+ 'Authorization',
458
+ ),
459
+ ).toBeNull();
460
+ });
461
+
462
+ it('intercepts requests to special urls: @portrait', async () => {
463
+ const request = new Request('http://example.com');
464
+ const context = new RouterContextProvider();
465
+ const params = { '*': '@portrait/username' };
466
+ const nextMock = vi.fn();
467
+ const fetchMock = vi.fn().mockResolvedValue({
468
+ status: 200,
469
+ body: 'portrait',
470
+ });
471
+ global.fetch = fetchMock;
472
+
473
+ await getAPIResourceWithAuth(
474
+ {
475
+ request,
476
+ params,
477
+ context,
478
+ pattern: '/@portrait/username',
479
+ url: new URL(request.url),
480
+ },
481
+ nextMock,
482
+ );
483
+
484
+ expect(fetchMock).toHaveBeenCalledWith(
485
+ 'http://localhost:8080/Plone/@portrait/username',
486
+ expect.objectContaining({
487
+ method: 'GET',
488
+ headers: expect.any(Headers),
489
+ }),
490
+ );
491
+ expect(
492
+ (fetchMock.mock.calls[0]?.[1] as { headers: Headers }).headers.get(
493
+ 'Authorization',
494
+ ),
495
+ ).toBeNull();
496
+ });
497
+
498
+ it('retries resource requests anonymously after a 401 and clears the cookie', async () => {
499
+ const request = new Request('http://example.com', {
500
+ headers: {
501
+ Cookie: 'auth_seven=token',
502
+ },
503
+ });
504
+ const context = new RouterContextProvider();
505
+ const params = { '*': 'image.png/@@images/image' };
506
+ const nextMock = vi.fn();
507
+ const fetchMock = vi
508
+ .fn()
509
+ .mockResolvedValueOnce(
510
+ new Response('unauthorized', {
511
+ status: 401,
512
+ statusText: 'Unauthorized',
513
+ }),
514
+ )
515
+ .mockResolvedValueOnce(
516
+ new Response('image', {
517
+ status: 200,
518
+ headers: { 'Content-Type': 'image/png' },
519
+ }),
520
+ );
521
+ global.fetch = fetchMock;
522
+ vi.mocked(getAuthFromRequest).mockResolvedValue('expired.jwt.token');
523
+
524
+ const response = (await getAPIResourceWithAuth(
525
+ {
526
+ request,
527
+ params,
528
+ context,
529
+ pattern: '/image.png/@@images/image',
530
+ url: new URL(request.url),
531
+ },
532
+ nextMock,
533
+ )) as Response;
534
+
535
+ expect(fetchMock).toHaveBeenNthCalledWith(
536
+ 1,
537
+ 'http://localhost:8080/Plone/image.png/@@images/image',
538
+ expect.objectContaining({
539
+ headers: expect.any(Headers),
540
+ }),
541
+ );
542
+ expect(fetchMock).toHaveBeenNthCalledWith(
543
+ 2,
544
+ 'http://localhost:8080/Plone/image.png/@@images/image',
545
+ expect.objectContaining({
546
+ headers: expect.any(Headers),
547
+ }),
548
+ );
549
+ expect(
550
+ (fetchMock.mock.calls[0]?.[1] as { headers: Headers }).headers.get(
551
+ 'Authorization',
552
+ ),
553
+ ).toBe('Bearer expired.jwt.token');
554
+ expect(
555
+ (fetchMock.mock.calls[1]?.[1] as { headers: Headers }).headers.get(
556
+ 'Authorization',
557
+ ),
558
+ ).toBeNull();
559
+ expect(response.status).toBe(200);
560
+ expect(response.headers.get('Set-Cookie')).toContain('auth_seven=');
561
+ });
562
+ });
563
+
564
+ describe('fetchPloneContent', () => {
565
+ afterEach(() => {
566
+ delete config.utilities['ploneClient'];
567
+ });
568
+
569
+ it('fetches content and site and sets them in context', async () => {
570
+ const mockContent = {
571
+ data: { '@id': 'http://example.com/', title: 'Home' },
572
+ };
573
+ const mockSite = { data: { '@id': 'http://example.com/' } };
574
+ const getContentMock = vi.fn().mockResolvedValue(mockContent);
575
+ const getSiteMock = vi.fn().mockResolvedValue(mockSite);
576
+ config.settings.apiPath = 'http://example.com';
577
+ registerPloneClientFactory({
578
+ getContent: getContentMock,
579
+ getSite: getSiteMock,
580
+ });
581
+ const request = new Request('http://example.com');
582
+ const context = new RouterContextProvider();
583
+ const nextMock = vi.fn();
584
+
585
+ await initializePloneClientContext(request, context);
586
+
587
+ await fetchPloneContent(
588
+ {
589
+ request,
590
+ params: {},
591
+ context,
592
+ pattern: '/',
593
+ url: new URL(request.url),
594
+ },
595
+ nextMock,
596
+ );
597
+
598
+ expect(getContentMock).toHaveBeenCalledWith({
599
+ path: '/',
600
+ expand: ['navroot', 'breadcrumbs', 'navigation', 'actions'],
601
+ });
602
+ expect(getSiteMock).toHaveBeenCalled();
603
+ expect(context.get(ploneContentContext)).toEqual({
604
+ '@id': '/',
605
+ title: 'Home',
606
+ });
607
+ expect(context.get(ploneSiteContext)).toEqual({ '@id': '/' });
608
+ expect(context.get(ploneClientContext)).toBeDefined();
609
+ });
610
+
611
+ it('fetches content for a specific path', async () => {
612
+ const getContentMock = vi.fn().mockResolvedValue({ data: {} });
613
+ const getSiteMock = vi.fn().mockResolvedValue({ data: {} });
614
+ config.settings.apiPath = 'http://example.com';
615
+ registerPloneClientFactory({
616
+ getContent: getContentMock,
617
+ getSite: getSiteMock,
618
+ });
619
+ const request = new Request('http://example.com/test-content');
620
+ const context = new RouterContextProvider();
621
+ const nextMock = vi.fn();
622
+
623
+ await initializePloneClientContext(request, context);
624
+
625
+ await fetchPloneContent(
626
+ {
627
+ request,
628
+ params: { '*': 'test-content' },
629
+ context,
630
+ pattern: '/test-content',
631
+ url: new URL(request.url),
632
+ },
633
+ nextMock,
634
+ );
635
+
636
+ expect(getContentMock).toHaveBeenCalledWith({
637
+ path: '/test-content',
638
+ expand: ['navroot', 'breadcrumbs', 'navigation', 'actions'],
639
+ });
640
+ });
641
+
642
+ it('throws when content is not found', async () => {
643
+ const getContentMock = vi
644
+ .fn()
645
+ .mockRejectedValue({ data: undefined, status: 500 });
646
+ const getSiteMock = vi.fn().mockResolvedValue({ data: {} });
647
+ config.settings.apiPath = 'http://example.com';
648
+ registerPloneClientFactory({
649
+ getContent: getContentMock,
650
+ getSite: getSiteMock,
651
+ });
652
+ const request = new Request('http://example.com');
653
+ const context = new RouterContextProvider();
654
+ const nextMock = vi.fn();
655
+
656
+ await initializePloneClientContext(request, context);
657
+
658
+ try {
659
+ await fetchPloneContent(
660
+ {
661
+ request,
662
+ params: {},
663
+ context,
664
+ pattern: '/',
665
+ url: new URL(request.url),
666
+ },
667
+ nextMock,
668
+ );
669
+ } catch (err: any) {
670
+ expect(err.init.status).toEqual(500);
671
+ }
672
+ });
673
+
674
+ it('throws when site is not found', async () => {
675
+ const getContentMock = vi.fn().mockResolvedValue({ data: {} });
676
+ const getSiteMock = vi
677
+ .fn()
678
+ .mockRejectedValue({ data: undefined, status: 500 });
679
+ config.settings.apiPath = 'http://example.com';
680
+ registerPloneClientFactory({
681
+ getContent: getContentMock,
682
+ getSite: getSiteMock,
683
+ });
684
+ const request = new Request('http://example.com');
685
+ const context = new RouterContextProvider();
686
+ const nextMock = vi.fn();
687
+
688
+ await initializePloneClientContext(request, context);
689
+
690
+ try {
691
+ await fetchPloneContent(
692
+ {
693
+ request,
694
+ params: {},
695
+ context,
696
+ pattern: '/',
697
+ url: new URL(request.url),
698
+ },
699
+ nextMock,
700
+ );
701
+ } catch (err: any) {
702
+ expect(err.init.status).toEqual(500);
703
+ }
704
+ });
705
+
706
+ it('sets ploneUserContext to null when no token is provided', async () => {
707
+ const getContentMock = vi.fn().mockResolvedValue({ data: {} });
708
+ const getSiteMock = vi.fn().mockResolvedValue({ data: {} });
709
+ const getUserMock = vi.fn();
710
+ config.settings.apiPath = 'http://example.com';
711
+ registerPloneClientFactory({
712
+ getContent: getContentMock,
713
+ getSite: getSiteMock,
714
+ getUser: getUserMock,
715
+ });
716
+ const request = new Request('http://example.com');
717
+ const context = new RouterContextProvider();
718
+ const nextMock = vi.fn();
719
+
720
+ await initializePloneClientContext(request, context);
721
+
722
+ await fetchPloneContent(
723
+ {
724
+ request,
725
+ params: {},
726
+ context,
727
+ pattern: '/',
728
+ url: new URL(request.url),
729
+ },
730
+ nextMock,
731
+ );
732
+
733
+ expect(getUserMock).not.toHaveBeenCalled();
734
+ expect(context.get(ploneUserContext)).toBeNull();
735
+ });
736
+
737
+ it('fetches user and sets ploneUserContext when token is valid', async () => {
738
+ const mockUser = { data: { id: 'testuser', fullname: 'Test User' } };
739
+ const getContentMock = vi.fn().mockResolvedValue({ data: {} });
740
+ const getSiteMock = vi.fn().mockResolvedValue({ data: {} });
741
+ const getUserMock = vi.fn().mockResolvedValue(mockUser);
742
+ config.settings.apiPath = 'http://example.com';
743
+ registerPloneClientFactory({
744
+ getContent: getContentMock,
745
+ getSite: getSiteMock,
746
+ getUser: getUserMock,
747
+ });
748
+ vi.mocked(getAuthFromRequest).mockResolvedValue('valid.jwt.token');
749
+ vi.mocked(jwtDecode).mockReturnValue({
750
+ sub: 'testuser',
751
+ exp: 9999999999,
752
+ fullname: 'Test User',
753
+ });
754
+ const request = new Request('http://example.com');
755
+ const context = new RouterContextProvider();
756
+ const nextMock = vi.fn();
757
+
758
+ await initializePloneClientContext(request, context);
759
+
760
+ await fetchPloneContent(
761
+ {
762
+ request,
763
+ params: {},
764
+ context,
765
+ pattern: '/',
766
+ url: new URL(request.url),
767
+ },
768
+ nextMock,
769
+ );
770
+
771
+ expect(getUserMock).toHaveBeenCalledWith({ id: 'testuser' });
772
+ expect(context.get(ploneUserContext)).toEqual(mockUser.data);
773
+ expect(getContentMock).toHaveBeenCalledWith({
774
+ path: '/',
775
+ expand: ['navroot', 'breadcrumbs', 'navigation', 'actions', 'types'],
776
+ });
777
+ });
778
+
779
+ it('keeps content and site loading successful when user fetch fails', async () => {
780
+ const getContentMock = vi.fn().mockResolvedValue({ data: {} });
781
+ const getSiteMock = vi.fn().mockResolvedValue({ data: {} });
782
+ const getUserMock = vi.fn().mockRejectedValue(new Error('User failed'));
783
+ config.settings.apiPath = 'http://example.com';
784
+ registerPloneClientFactory({
785
+ getContent: getContentMock,
786
+ getSite: getSiteMock,
787
+ getUser: getUserMock,
788
+ });
789
+ vi.mocked(getAuthFromRequest).mockResolvedValue('valid.jwt.token');
790
+ vi.mocked(jwtDecode).mockReturnValue({
791
+ sub: 'testuser',
792
+ exp: 9999999999,
793
+ fullname: 'Test User',
794
+ });
795
+ const request = new Request('http://example.com');
796
+ const context = new RouterContextProvider();
797
+ const nextMock = vi.fn();
798
+
799
+ await initializePloneClientContext(request, context);
800
+
801
+ await fetchPloneContent(
802
+ {
803
+ request,
804
+ params: {},
805
+ context,
806
+ pattern: '/',
807
+ url: new URL(request.url),
808
+ },
809
+ nextMock,
810
+ );
811
+
812
+ expect(getContentMock).toHaveBeenCalledWith({
813
+ path: '/',
814
+ expand: ['navroot', 'breadcrumbs', 'navigation', 'actions', 'types'],
815
+ });
816
+ expect(getSiteMock).toHaveBeenCalled();
817
+ expect(getUserMock).toHaveBeenCalledWith({ id: 'testuser' });
818
+ expect(context.get(ploneUserContext)).toBeNull();
819
+ });
820
+
821
+ it('does not fetch user when token has no sub field', async () => {
822
+ const getContentMock = vi.fn().mockResolvedValue({ data: {} });
823
+ const getSiteMock = vi.fn().mockResolvedValue({ data: {} });
824
+ const getUserMock = vi.fn();
825
+ config.settings.apiPath = 'http://example.com';
826
+ registerPloneClientFactory({
827
+ getContent: getContentMock,
828
+ getSite: getSiteMock,
829
+ getUser: getUserMock,
830
+ });
831
+ vi.mocked(getAuthFromRequest).mockResolvedValue('token.without.sub');
832
+ vi.mocked(jwtDecode).mockReturnValue({ exp: 9999999999 });
833
+ const request = new Request('http://example.com');
834
+ const context = new RouterContextProvider();
835
+ const nextMock = vi.fn();
836
+
837
+ await initializePloneClientContext(request, context);
838
+
839
+ await fetchPloneContent(
840
+ {
841
+ request,
842
+ params: {},
843
+ context,
844
+ pattern: '/',
845
+ url: new URL(request.url),
846
+ },
847
+ nextMock,
848
+ );
849
+
850
+ expect(getUserMock).not.toHaveBeenCalled();
851
+ expect(context.get(ploneUserContext)).toBeNull();
852
+ expect(getContentMock).toHaveBeenCalledWith({
853
+ path: '/',
854
+ expand: ['navroot', 'breadcrumbs', 'navigation', 'actions'],
855
+ });
856
+ });
857
+
858
+ it('handles JWT decode errors gracefully and proceeds without user', async () => {
859
+ const getContentMock = vi.fn().mockResolvedValue({ data: {} });
860
+ const getSiteMock = vi.fn().mockResolvedValue({ data: {} });
861
+ const getUserMock = vi.fn();
862
+ config.settings.apiPath = 'http://example.com';
863
+ registerPloneClientFactory({
864
+ getContent: getContentMock,
865
+ getSite: getSiteMock,
866
+ getUser: getUserMock,
867
+ });
868
+ vi.mocked(getAuthFromRequest).mockResolvedValue('malformed.token');
869
+ vi.mocked(jwtDecode).mockImplementation(() => {
870
+ throw new Error('Invalid token');
871
+ });
872
+ const request = new Request('http://example.com');
873
+ const context = new RouterContextProvider();
874
+ const nextMock = vi.fn();
875
+
876
+ await initializePloneClientContext(request, context);
877
+
878
+ await fetchPloneContent(
879
+ {
880
+ request,
881
+ params: {},
882
+ context,
883
+ pattern: '/',
884
+ url: new URL(request.url),
885
+ },
886
+ nextMock,
887
+ );
888
+
889
+ expect(getUserMock).not.toHaveBeenCalled();
890
+ expect(context.get(ploneUserContext)).toBeNull();
891
+ });
892
+
893
+ it('retries anonymously after a 401 and clears the auth cookie context', async () => {
894
+ const authContent = vi
895
+ .fn()
896
+ .mockRejectedValueOnce({ data: undefined, status: 401 });
897
+ const authSite = vi.fn().mockResolvedValue({ data: {} });
898
+ const anonymousContent = vi.fn().mockResolvedValueOnce({
899
+ data: { '@id': 'http://example.com/', title: 'Home' },
900
+ });
901
+ const anonymousSite = vi
902
+ .fn()
903
+ .mockResolvedValueOnce({ data: { '@id': 'http://example.com/' } });
904
+ config.settings.apiPath = 'http://example.com';
905
+ const initializeMock = vi
906
+ .fn()
907
+ .mockReturnValueOnce({
908
+ getContent: authContent,
909
+ getSite: authSite,
910
+ getUser: vi.fn().mockResolvedValue(null),
911
+ })
912
+ .mockReturnValueOnce({
913
+ getContent: anonymousContent,
914
+ getSite: anonymousSite,
915
+ getUser: vi.fn().mockResolvedValue(null),
916
+ });
917
+ config.registerUtility({
918
+ name: 'ploneClient',
919
+ type: 'client',
920
+ method: () =>
921
+ ({
922
+ prototype: {},
923
+ initialize: initializeMock,
924
+ }) as any,
925
+ });
926
+ vi.mocked(getAuthFromRequest).mockResolvedValue('expired.jwt.token');
927
+ vi.mocked(jwtDecode).mockReturnValue({
928
+ sub: 'testuser',
929
+ exp: 9999999999,
930
+ fullname: 'Test User',
931
+ });
932
+ const request = new Request('http://example.com');
933
+ const context = new RouterContextProvider();
934
+ const nextMock = vi.fn();
935
+
936
+ await initializePloneClientContext(request, context);
937
+
938
+ await fetchPloneContent(
939
+ {
940
+ request,
941
+ params: {},
942
+ context,
943
+ pattern: '/',
944
+ url: new URL(request.url),
945
+ },
946
+ nextMock,
947
+ );
948
+
949
+ expect(anonymousContent).toHaveBeenCalledWith({
950
+ path: '/',
951
+ expand: ['navroot', 'breadcrumbs', 'navigation', 'actions'],
952
+ });
953
+ expect(context.get(ploneContentContext)).toEqual({
954
+ '@id': '/',
955
+ title: 'Home',
956
+ });
957
+ expect(context.get(ploneUserContext)).toBeNull();
958
+ expect(context.get(ploneClearAuthCookieContext)).toBe(true);
959
+ });
960
+
961
+ it('redirects when getContent throws a 3xx error with location', async () => {
962
+ const getContentMock = vi
963
+ .fn()
964
+ .mockRejectedValue({ status: 301, location: '/new-path' });
965
+ const getSiteMock = vi.fn().mockResolvedValue({ data: {} });
966
+ config.settings.apiPath = 'http://example.com';
967
+ registerPloneClientFactory({
968
+ getContent: getContentMock,
969
+ getSite: getSiteMock,
970
+ });
971
+ const request = new Request('http://example.com');
972
+ const context = new RouterContextProvider();
973
+ const nextMock = vi.fn();
974
+
975
+ await initializePloneClientContext(request, context);
976
+
977
+ const result = await fetchPloneContent(
978
+ {
979
+ request,
980
+ params: {},
981
+ context,
982
+ pattern: '/',
983
+ url: new URL(request.url),
984
+ },
985
+ nextMock,
986
+ );
987
+
988
+ expect(result).toBeInstanceOf(Response);
989
+ expect((result as Response).status).toBe(301);
990
+ expect((result as Response).headers.get('Location')).toBe('/new-path');
991
+ });
992
+
993
+ it('throws content error when error has 3xx status but no location', async () => {
994
+ const getContentMock = vi.fn().mockRejectedValue({ status: 301 });
995
+ const getSiteMock = vi.fn().mockResolvedValue({ data: {} });
996
+ config.settings.apiPath = 'http://example.com';
997
+ registerPloneClientFactory({
998
+ getContent: getContentMock,
999
+ getSite: getSiteMock,
1000
+ });
1001
+ const request = new Request('http://example.com');
1002
+ const context = new RouterContextProvider();
1003
+ const nextMock = vi.fn();
1004
+
1005
+ await initializePloneClientContext(request, context);
1006
+
1007
+ await expect(() =>
1008
+ fetchPloneContent(
1009
+ {
1010
+ request,
1011
+ params: {},
1012
+ context,
1013
+ pattern: '/',
1014
+ url: new URL(request.url),
1015
+ },
1016
+ nextMock,
1017
+ ),
1018
+ ).rejects.toMatchObject({ init: { status: 301 } });
1019
+ });
1020
+ });
1021
+
1022
+ describe('linkMiddleware', () => {
1023
+ const makeArgs = (context: RouterContextProvider) => ({
1024
+ request: new Request('http://example.com/link'),
1025
+ context,
1026
+ params: {},
1027
+ pattern: '/link',
1028
+ url: new URL('http://example.com/link'),
1029
+ });
1030
+
1031
+ it('redirects to remoteUrl when content is a Link without edit permission', async () => {
1032
+ const context = new RouterContextProvider();
1033
+ context.set(ploneContentContext, {
1034
+ '@type': 'Link',
1035
+ remoteUrl: 'https://external.example.com',
1036
+ '@components': {
1037
+ actions: {
1038
+ // @ts-expect-error
1039
+ object: [{ id: 'view' }, { id: 'history' }],
1040
+ },
1041
+ },
1042
+ });
1043
+
1044
+ const result = await linkMiddleware(makeArgs(context), vi.fn());
1045
+
1046
+ expect(result).toBeInstanceOf(Response);
1047
+ expect((result as Response).status).toBe(302);
1048
+ expect((result as Response).headers.get('Location')).toBe(
1049
+ 'https://external.example.com',
1050
+ );
1051
+ });
1052
+
1053
+ it('does not redirect when content is a Link with edit permission', async () => {
1054
+ const context = new RouterContextProvider();
1055
+ context.set(ploneContentContext, {
1056
+ '@type': 'Link',
1057
+ remoteUrl: 'https://external.example.com',
1058
+ '@components': {
1059
+ actions: {
1060
+ // @ts-expect-error
1061
+ object: [{ id: 'view' }, { id: 'edit' }],
1062
+ },
1063
+ },
1064
+ });
1065
+
1066
+ const result = await linkMiddleware(makeArgs(context), vi.fn());
1067
+
1068
+ expect(result).toBeUndefined();
1069
+ });
1070
+
1071
+ it('does not redirect when content is not a Link type', async () => {
1072
+ const context = new RouterContextProvider();
1073
+ context.set(ploneContentContext, {
1074
+ '@type': 'Document',
1075
+ '@components': {
1076
+ actions: {
1077
+ // @ts-expect-error
1078
+ object: [{ id: 'view' }],
1079
+ },
1080
+ },
1081
+ });
1082
+
1083
+ const result = await linkMiddleware(makeArgs(context), vi.fn());
1084
+
1085
+ expect(result).toBeUndefined();
1086
+ });
1087
+ });
1088
+ });