@websolutespa/bom-next 4.0.0-next.13 → 4.0.0-next.15

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 (67) hide show
  1. package/CHANGELOG.md +23 -3
  2. package/README.md +132 -118
  3. package/dist/exports/proxy.d.ts +4 -3
  4. package/dist/exports/proxy.js +4 -3
  5. package/dist/exports/server.d.ts +2 -1
  6. package/dist/exports/server.js +2 -1
  7. package/dist/index.d.ts +7 -3
  8. package/dist/index.js +5 -1
  9. package/dist/lib/cors.d.ts +25 -0
  10. package/dist/lib/cors.d.ts.map +1 -0
  11. package/dist/lib/cors.js +42 -0
  12. package/dist/lib/cors.js.map +1 -0
  13. package/dist/lib/seed-env.d.ts +13 -0
  14. package/dist/lib/seed-env.d.ts.map +1 -0
  15. package/dist/lib/seed-env.js +18 -0
  16. package/dist/lib/seed-env.js.map +1 -0
  17. package/dist/lib/spam.d.ts +38 -0
  18. package/dist/lib/spam.d.ts.map +1 -0
  19. package/dist/lib/spam.js +43 -0
  20. package/dist/lib/spam.js.map +1 -0
  21. package/dist/lib/ttl-cache.js +5 -2
  22. package/dist/lib/ttl-cache.js.map +1 -1
  23. package/dist/lib/user.d.ts +16 -0
  24. package/dist/lib/user.d.ts.map +1 -0
  25. package/dist/lib/user.js +21 -0
  26. package/dist/lib/user.js.map +1 -0
  27. package/dist/proxy/api-cors.d.ts +24 -0
  28. package/dist/proxy/api-cors.d.ts.map +1 -0
  29. package/dist/proxy/api-cors.js +35 -0
  30. package/dist/proxy/api-cors.js.map +1 -0
  31. package/dist/proxy/route-auto-detection.d.ts +3 -1
  32. package/dist/proxy/route-auto-detection.d.ts.map +1 -1
  33. package/dist/proxy/route-auto-detection.js +20 -4
  34. package/dist/proxy/route-auto-detection.js.map +1 -1
  35. package/dist/proxy/route-proxy.d.ts +2 -1
  36. package/dist/proxy/route-proxy.d.ts.map +1 -1
  37. package/dist/proxy/route-proxy.js +8 -4
  38. package/dist/proxy/route-proxy.js.map +1 -1
  39. package/dist/server/handlers/auth.handler.d.ts.map +1 -1
  40. package/dist/server/handlers/auth.handler.js +6 -4
  41. package/dist/server/handlers/auth.handler.js.map +1 -1
  42. package/dist/server/rate-limit.d.ts +37 -0
  43. package/dist/server/rate-limit.d.ts.map +1 -0
  44. package/dist/server/rate-limit.js +55 -0
  45. package/dist/server/rate-limit.js.map +1 -0
  46. package/package.json +1 -1
  47. package/src/exports/proxy.ts +5 -4
  48. package/src/exports/server.ts +23 -22
  49. package/src/index.ts +20 -16
  50. package/src/lib/cors.test.ts +29 -0
  51. package/src/lib/cors.ts +55 -0
  52. package/src/lib/seed-env.ts +17 -0
  53. package/src/lib/spam.test.ts +39 -0
  54. package/src/lib/spam.ts +59 -0
  55. package/src/lib/ttl-cache.test.ts +57 -0
  56. package/src/lib/ttl-cache.ts +75 -72
  57. package/src/lib/user.test.ts +21 -0
  58. package/src/lib/user.ts +25 -0
  59. package/src/proxy/api-cors.test.ts +30 -0
  60. package/src/proxy/api-cors.ts +42 -0
  61. package/src/proxy/route-auto-detection.test.ts +98 -55
  62. package/src/proxy/route-auto-detection.ts +247 -222
  63. package/src/proxy/route-proxy.test.ts +140 -104
  64. package/src/proxy/route-proxy.ts +295 -291
  65. package/src/server/handlers/auth.handler.ts +31 -32
  66. package/src/server/rate-limit.test.ts +90 -0
  67. package/src/server/rate-limit.ts +95 -0
package/CHANGELOG.md CHANGED
@@ -1,11 +1,33 @@
1
1
  # @websolutespa/bom-next
2
2
 
3
+ ## 4.0.0-next.15
4
+
5
+ ### Patch Changes
6
+
7
+ - Use monotonic timing for TTL cache
8
+
9
+ ## 4.0.0-next.14
10
+
11
+ ### Minor Changes
12
+
13
+ - e88fd77: - **`isEndUser(user)`** (main entry, isomorphic): a site end user has the `user` role and comes from the `end_users` collection (or carries the end user's name fields); a back-office user given the `user` role is not one. `/api/auth/me` uses the same rule.
14
+ - **`createRateLimiter({ prefix, limit, windowSeconds })`** (`/server`): fixed-window limiter for public endpoints such as form actions. Counts in Redis (`<REDIS_PREFIX>:rate:...`, shared by every instance) when `REDIS_URL` is set and ready, in a bounded per-process map otherwise; a Redis error falls back to memory.
15
+ - e88fd77: Security helpers shared by every site, moved from the bom-sample app:
16
+ - CORS: `getAllowedOrigins`, `getCsrfOrigins`, `getCorsHeaders` (main entry) and `createApiCorsProxy` (`/proxy`), an allowlist echoed with credentials instead of `Access-Control-Allow-Origin: *`.
17
+ - Anti-spam: `SPAM_FIELDS`, `getSpamReason`, `ANTI_SPAM_DEFAULTS`, `getClientIp` (main entry, isomorphic).
18
+ - Seed credentials: `requireSeedEnv(key)` (main entry), no literal fallback.
19
+
20
+ ### Patch Changes
21
+
22
+ - f13b6ab: Route proxy fixes.
23
+ - Draft Mode: public URLs are resolved as usual (editors see drafts on them) instead of falling through to a 404; unresolved paths, such as the internal preview path, are still left to Next. A project workaround that drops `__prerender_bypass` on public URLs can be removed.
24
+ - `routeAutoDetection`: a `detectedRoute` cookie redirects only when it names a current root route; a stale one (e.g. a removed market) runs detection again and is overwritten. Root routes are cached per instance for `BOM_ROUTE_CACHE_TTL` seconds.
25
+
3
26
  ## 4.0.0-next.13
4
27
 
5
28
  ### Minor Changes
6
29
 
7
30
  - **Security: Draft Mode only for editors.** `previewHandler` turned Next.js Draft Mode on for any visitor (its secret check was commented out), and draft renders then showed unpublished pages to anyone.
8
-
9
31
  - New `getPreviewHandler(config, { roles })` for `src/app/api/-preview/route.ts`: it turns Draft Mode on for a logged-in editor (admin, contributor, editor: the admin session cookie, or the `_token` Bowl adds to the admin's preview URL, for an admin on another origin) or for `secret` equal to `MIXER_SECRET`; everyone else gets 401 and no cookie. The redirect accepts path segments only.
10
32
  - `previewHandler(request)` is deprecated: without the config it cannot authenticate a user, so it now requires `secret` (`MIXER_SECRET`). Switch the route to `export const GET = getPreviewHandler(config)`.
11
33
  - Draft reads: Bowl now serves drafts to the editing roles only, so `getPayload` reads a draft render without an editor session as an editor identity (`previewer`), and only while Draft Mode is really on; a `draft: true` read outside Draft Mode reads the published site. `PREVIEW_ROLES` and `previewer` are exported.
@@ -16,7 +38,6 @@
16
38
  ### Patch Changes
17
39
 
18
40
  - Shared Redis cache across instances and cold starts.
19
-
20
41
  - **Lifetime of shared entries.** `cache-handlers/isr` stores the route lifetime (`cacheControl`) with every entry and returns it from `get`. Next.js 16.4 knows the lifetime only of the paths an instance rendered or prerendered, and treated an entry written by another instance as revalidate 1 s: every instance served it stale once and re-rendered it. Entries written before this release fall back to their stored `revalidate`.
21
42
  - **One client per process.** The Redis client lives on `globalThis`, so the handler (loaded by Next.js from node_modules) and the bundled server code share one connection, and concurrent first calls no longer create two clients.
22
43
  - **Cold start.** `registerIntrumentation()` connects the client before the first request (at most the 2 s connect timeout while Redis is down; skipped during `next build`), so the first page of a new instance reads Redis instead of rendering. The cache panel inspector waits for the connection the same way instead of reporting `none`. New export `connectRedisClient(timeout)` from `@websolutespa/bom-next/cache-handlers/isr`.
@@ -26,7 +47,6 @@
26
47
  ### Minor Changes
27
48
 
28
49
  - 67f9535: Site side of the Next.js cache panel, named cached functions, and support for both caching models (classic ISR and Cache Components).
29
-
30
50
  - **Page tags.** `createPageContext` and `createLayoutContext` tag every rendered page from its route: market, locale, collection, document, route, category ancestors and the layout collections. Decorators that list other documents call `tagPage([collectionTag('…')])`.
31
51
  - **Cache endpoint.** `getCacheHandler()` (`/api/-cache`, Bearer `MIXER_SECRET`) reports the cached pages, functions and process caches of the instance (file system, Redis, or none on Vercel) and applies cache actions. `revalidate` maps to `revalidateTag(tag, 'max')`, `invalidate` to `revalidateTag(tag, { expire: 0 })`; actions can also revalidate paths, clear process caches and warm pages after the response. `registerIntrumentation()` registers it in process for the Bowl admin, so sites need no change.
32
52
  - **Next.js 16.4 route cache.** The inspector reads both `.next/server/app` and the runtime route cache (`.next/server/route-cache/<kind>/<sha256(source route)>/$/<path>`).
package/README.md CHANGED
@@ -1,118 +1,132 @@
1
- # @websolutespa/bom-next
2
-
3
- [![npm version](https://badge.fury.io/js/%40websolutespa%2Fbom-next.svg)](https://badge.fury.io/js/%40websolutespa%2Fbom-next)
4
-
5
- [![status alpha](https://img.shields.io/badge/status-alpha-red.svg)](https://shields.io/)
6
-
7
- Next module of the [BOM Repository](https://github.com/websolutespa/bom) by [websolute](https://www.websolute.com/).
8
-
9
- ---
10
-
11
- ##### _this library is for internal usage and not production ready_
12
-
13
- ## Page context
14
-
15
- ```ts
16
- import { createPageContext, getMetadata } from '@websolutespa/bom-next/server';
17
-
18
- export const generateMetadata = getMetadata('post_detail', config);
19
-
20
- const { page, layout, label, link } = await createPageContext(market, locale, 'post_detail', id, {
21
- config,
22
- depth: 2, // default DEFAULT_PAGE_DEPTH
23
- select: { title: true, abstract: true, media: true, components: true },
24
- populate: { media: { url: true, alt: true, width: true, height: true, type: true } },
25
- });
26
-
27
- const { layout } = await createLayoutContext(market, locale, { config }); // depth: DEFAULT_LAYOUT_DEPTH (1)
28
- ```
29
-
30
- | option | default | |
31
- | ---------- | -------------- | ------------------------------------------------------------------------------------------------------------------ |
32
- | `depth` | `2` | `0` ids only, `1` direct relations/uploads (including those inside blocks), `2` relations of relations |
33
- | `select` | – | Payload select; envelope fields (`id`, `slug`, `title`, `category`, `markets`, `meta`, `template`) are always read |
34
- | `populate` | – | per-collection select for populated documents |
35
- | `draft` | `'auto'` | `true` / `false`, or `'auto'` to read Next `draftMode()` |
36
- | `layout` | `{ depth: 1 }` | layout options, or `false` to skip the layout |
37
-
38
- Page and layout reads are memoized per request, so `getMetadata` and the page component share them when called with the same options.
39
- To bind `config` once: `export const { createPageContext, createLayoutContext, getMetadata } = createContextHelpers({ config, defaults: { depth: 2 } });`
40
-
41
- ## Metadata
42
-
43
- `getPageMetadata` (and `getMetadata`, its `config`-first form) returns a `generateMetadata` function that renders on the server: plain-text title and description, canonical (keeping `?pagination[page]=N` after the first page), `alternates.languages` with one `locale-COUNTRY` entry per market country plus `x-default`, robots, keywords, Open Graph and Twitter.
44
-
45
- ```ts
46
- import { getPageMetadata, JsonLd, buildPageStructuredData } from '@websolutespa/bom-next/server';
47
-
48
- export const generateMetadata = getPageMetadata('post_detail', {
49
- config,
50
- metadata: {
51
- brand: { name: 'Example', logo: '/logo.png', twitterName: '@example' },
52
- extend: (metadata, { page }) => ({ ...metadata, title: `${metadata.title} | Example` }),
53
- },
54
- });
55
-
56
- // JSON-LD in the page component
57
- <JsonLd data={buildPageStructuredData(page, layout, { brand: { name: 'Example' } })} />
58
- ```
59
-
60
- `buildPageMetadata(page, layout, options)` is the same builder for custom routes. URLs are resolved against `NEXT_PUBLIC_URL` unless `baseUrl` is passed. Robots come from `meta.robots`, or `meta.robot` (the `@payloadcms/plugin-seo` field), on indexable pages only. `indexable` (`boolean` or `(page) => boolean`) decides; the default, `isIndexableDeployment()`, makes pages indexable only with `PRODUCTION=true` and without `NOINDEX=true`, so staging and preview deployments answer `noindex, nofollow`. Set `PRODUCTION=true` in production.
61
-
62
- The client `MetaDataProvider` only computes values for `useMetaData`; the `next/head` based `Meta`, `OpenGraph` and `StructuredData` components of the mixer packages render nothing in the App Router.
63
-
64
- `layout.homeHref` is the root page href for the current market and locale; prefer it to `layout.topLevelHrefs.<slug>`, which is keyed by collection slug or template.
65
-
66
- ## Routing proxy
67
-
68
- `createRouteProxy` resolves each request through `/api/-route` and caches the result per instance: found routes for `BOM_ROUTE_CACHE_TTL` seconds (default `30`, `0` disables), misses and redirects for at most 10 seconds. Draft requests and server errors are never cached. CMS redirects send the browser to the target returned by the resolver.
69
-
70
- `routeAutoDetection` redirects `/` straight from the `detectedRoute` cookie when present; otherwise it detects the market (GeoIP, 2 s timeout, cached per IP for one hour) and the locale.
71
-
72
- The server context (`getContext`) reads routes from the Bowl route store and caches the rest per market, locale and user for `MEMORY_CACHE_DURATION` seconds (default 300). Any route store change, local or from another instance through Redis, clears it. Draft contexts are never cached.
73
-
74
- ## Preview
75
-
76
- `getPreviewHandler(config)` is the `/api/-preview` route (`export const GET = getPreviewHandler(config)`). It turns Next.js Draft Mode on and redirects to the page, only for an editor (`PREVIEW_ROLES`: admin, contributor, editor; the admin session cookie, or the `_token` Bowl adds to the admin's preview URL) or with `secret` equal to `MIXER_SECRET`; anyone else gets 401 and no cookie. Templates pass `draft: (await draftMode()).isEnabled` to `createPageContext`; draft renders without an editor session read as `previewer` (an editing role), and only while Draft Mode is on, because Bowl serves drafts to the editing roles only. The old `previewHandler(request)` is deprecated and accepts only the secret.
77
-
78
- ## Cache
79
-
80
- Pages are tagged from their route by `createPageContext` and `createLayoutContext`, and invalidated by the Bowl change hooks and the Bowl cache panel (`/admin/cache`). The site exposes its side of the panel with one route:
81
-
82
- ```ts
83
- // src/app/api/-cache/route.ts
84
- import { getCacheHandler } from '@websolutespa/bom-next/server';
85
-
86
- export const { GET, POST } = getCacheHandler();
87
- export const dynamic = 'force-dynamic';
88
- ```
89
-
90
- - `tagPage(tags)` adds tags to the page being rendered, for example a decorator that lists another collection: `tagPage([collectionTag('post_detail')])`.
91
- - `bomCached(name, fn, { life, tags, resultTags })` caches a data function by name. `life` is a BOM profile (`bom-layout`, `bom-page`, `bom-listing`, `bom-static`, see `bomProfiles`) or an inline profile. `documentTags(collection, result)` tags a result by its documents. Every entry carries `bom:fn:<name>`, so the panel lists and revalidates it.
92
- - `withBom(nextConfig)` (`@websolutespa/bom-next/config`) wires the caching model:
93
- - **Classic ISR** (default): `bomCached` uses `unstable_cache`, templates keep `generateStaticParams` and `export const revalidate`.
94
- - **`cacheComponents: true`**: `bomCached` and `tagPage` use `'use cache'`, `cacheLife` and `cacheTag`; the BOM profiles are registered as `cacheLife` profiles, `cacheHandlers.default` is the BOM `'use cache'` handler, and `createPageContext` reads public pages and layouts through cached functions. Templates must drop `export const revalidate`. `getStaticParams` returns at least one route per template (Cache Components refuses an empty list), so every template needs one published page at build time.
95
- - **`REDIS_URL` at build time**: `cacheHandler` is the shared Redis handler (`@websolutespa/bom-next/cache-handlers/isr`), which applies `revalidateTag(tag, 'max')` as stale-while-revalidate across instances; `'use cache'` entries share its tag keys.
96
- - `registerIntrumentation()` registers the in-process cache executor; Bowl uses `/api/-cache` (Bearer `MIXER_SECRET`) when it runs in another process.
97
-
98
- The cache panel reads the file-system cache (`.next/server/app` and the Next.js 16.4 runtime route cache under `.next/server/route-cache`), the Redis handlers' meta keys, or nothing on Vercel. `next dev` has no ISR cache: check the panel after `next build && next start`.
99
-
100
- ## Environment
101
-
102
- Per-request diagnostics (proxy, local API calls, context cache) are logged in development only (`NODE_ENV` unset or `development`).
103
-
104
- | Variable | Default | |
105
- | ----------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------ |
106
- | `BOM_ROUTE_CACHE_TTL` | `30` | proxy route cache lifetime in seconds, `0` disables it |
107
- | `MEMORY_CACHE_DURATION` | `300` | server context cache lifetime in seconds |
108
- | `BOM_USE_CACHE_MAX_BYTES` | `67108864` | memory limit of the in-process `'use cache'` handler (Cache Components without Redis) |
109
- | `MIXER_SECRET` | – | Bearer token of `/api/-revalidate` and `/api/-cache` |
110
- | `REDIS_URL`, `REDIS_PREFIX` | – | shared Redis cache handlers (set at build time for `withBom`) and key prefix |
111
- | `UI_REGISTRY_SOURCE_DIR` | `packages/ui/src` | registry source directory |
112
- | `UI_REGISTRY_COMPONENTS_JSON` | nearest `components.json` | shadcn config whose aliases (e.g. `@/ui/lib/utils`) are mapped to registry imports |
113
- | `UI_REGISTRY_SOURCE_ALIAS` | – | extra import prefix pointing at the registry source, e.g. `@/ui/` |
114
- | `UI_REGISTRY_SKIP_UNRESOLVED` | – | `1` hides registry items that import app code; otherwise they are listed with `meta.unresolvedImports` |
115
-
116
- ## User
117
-
118
- `UserProvider` reads `/api/auth/me` once per page load, shared by every mount and client navigation. Pass `initialUser` (a user or `null`) when the server already knows it to skip the request; `setUser` and `invalidateUser()` keep the cached value current after login or logout.
1
+ # @websolutespa/bom-next
2
+
3
+ [![npm version](https://badge.fury.io/js/%40websolutespa%2Fbom-next.svg)](https://badge.fury.io/js/%40websolutespa%2Fbom-next)
4
+
5
+ [![status alpha](https://img.shields.io/badge/status-alpha-red.svg)](https://shields.io/)
6
+
7
+ Next module of the [BOM Repository](https://github.com/websolutespa/bom) by [websolute](https://www.websolute.com/).
8
+
9
+ ---
10
+
11
+ ##### _this library is for internal usage and not production ready_
12
+
13
+ ## Page context
14
+
15
+ ```ts
16
+ import { createPageContext, getMetadata } from '@websolutespa/bom-next/server';
17
+
18
+ export const generateMetadata = getMetadata('post_detail', config);
19
+
20
+ const { page, layout, label, link } = await createPageContext(market, locale, 'post_detail', id, {
21
+ config,
22
+ depth: 2, // default DEFAULT_PAGE_DEPTH
23
+ select: { title: true, abstract: true, media: true, components: true },
24
+ populate: { media: { url: true, alt: true, width: true, height: true, type: true } },
25
+ });
26
+
27
+ const { layout } = await createLayoutContext(market, locale, { config }); // depth: DEFAULT_LAYOUT_DEPTH (1)
28
+ ```
29
+
30
+ | option | default | |
31
+ | ---------- | -------------- | ------------------------------------------------------------------------------------------------------------------ |
32
+ | `depth` | `2` | `0` ids only, `1` direct relations/uploads (including those inside blocks), `2` relations of relations |
33
+ | `select` | – | Payload select; envelope fields (`id`, `slug`, `title`, `category`, `markets`, `meta`, `template`) are always read |
34
+ | `populate` | – | per-collection select for populated documents |
35
+ | `draft` | `'auto'` | `true` / `false`, or `'auto'` to read Next `draftMode()` |
36
+ | `layout` | `{ depth: 1 }` | layout options, or `false` to skip the layout |
37
+
38
+ Page and layout reads are memoized per request, so `getMetadata` and the page component share them when called with the same options.
39
+ To bind `config` once: `export const { createPageContext, createLayoutContext, getMetadata } = createContextHelpers({ config, defaults: { depth: 2 } });`
40
+
41
+ ## Metadata
42
+
43
+ `getPageMetadata` (and `getMetadata`, its `config`-first form) returns a `generateMetadata` function that renders on the server: plain-text title and description, canonical (keeping `?pagination[page]=N` after the first page), `alternates.languages` with one `locale-COUNTRY` entry per market country plus `x-default`, robots, keywords, Open Graph and Twitter.
44
+
45
+ ```ts
46
+ import { getPageMetadata, JsonLd, buildPageStructuredData } from '@websolutespa/bom-next/server';
47
+
48
+ export const generateMetadata = getPageMetadata('post_detail', {
49
+ config,
50
+ metadata: {
51
+ brand: { name: 'Example', logo: '/logo.png', twitterName: '@example' },
52
+ extend: (metadata, { page }) => ({ ...metadata, title: `${metadata.title} | Example` }),
53
+ },
54
+ });
55
+
56
+ // JSON-LD in the page component
57
+ <JsonLd data={buildPageStructuredData(page, layout, { brand: { name: 'Example' } })} />
58
+ ```
59
+
60
+ `buildPageMetadata(page, layout, options)` is the same builder for custom routes. URLs are resolved against `NEXT_PUBLIC_URL` unless `baseUrl` is passed. Robots come from `meta.robots`, or `meta.robot` (the `@payloadcms/plugin-seo` field), on indexable pages only. `indexable` (`boolean` or `(page) => boolean`) decides; the default, `isIndexableDeployment()`, makes pages indexable only with `PRODUCTION=true` and without `NOINDEX=true`, so staging and preview deployments answer `noindex, nofollow`. Set `PRODUCTION=true` in production.
61
+
62
+ The client `MetaDataProvider` only computes values for `useMetaData`; the `next/head` based `Meta`, `OpenGraph` and `StructuredData` components of the mixer packages render nothing in the App Router.
63
+
64
+ `layout.homeHref` is the root page href for the current market and locale; prefer it to `layout.topLevelHrefs.<slug>`, which is keyed by collection slug or template.
65
+
66
+ ## Routing proxy
67
+
68
+ `createRouteProxy` resolves each request through `/api/-route` and caches the result per instance: found routes for `BOM_ROUTE_CACHE_TTL` seconds (default `30`, `0` disables), misses and redirects for at most 10 seconds. Server errors are never cached. In Draft Mode public URLs are resolved as usual, while unresolved paths (such as the internal preview path) are left to Next instead of the 404 page. CMS redirects send the browser to the target returned by the resolver.
69
+
70
+ `routeAutoDetection` redirects `/` straight from the `detectedRoute` cookie when it names a current root route (root routes are cached like route resolutions, `BOM_ROUTE_CACHE_TTL`); otherwise it detects the market (GeoIP, 2 s timeout, cached per IP for one hour) and the locale.
71
+
72
+ The server context (`getContext`) reads routes from the Bowl route store and caches the rest per market, locale and user for `MEMORY_CACHE_DURATION` seconds (default 300). Any route store change, local or from another instance through Redis, clears it. Draft contexts are never cached.
73
+
74
+ ## Preview
75
+
76
+ `getPreviewHandler(config)` is the `/api/-preview` route (`export const GET = getPreviewHandler(config)`). It turns Next.js Draft Mode on and redirects to the page, only for an editor (`PREVIEW_ROLES`: admin, contributor, editor; the admin session cookie, or the `_token` Bowl adds to the admin's preview URL) or with `secret` equal to `MIXER_SECRET`; anyone else gets 401 and no cookie. Templates pass `draft: (await draftMode()).isEnabled` to `createPageContext`; draft renders without an editor session read as `previewer` (an editing role), and only while Draft Mode is on, because Bowl serves drafts to the editing roles only. The old `previewHandler(request)` is deprecated and accepts only the secret.
77
+
78
+ ## Cache
79
+
80
+ Pages are tagged from their route by `createPageContext` and `createLayoutContext`, and invalidated by the Bowl change hooks and the Bowl cache panel (`/admin/cache`). The site exposes its side of the panel with one route:
81
+
82
+ ```ts
83
+ // src/app/api/-cache/route.ts
84
+ import { getCacheHandler } from '@websolutespa/bom-next/server';
85
+
86
+ export const { GET, POST } = getCacheHandler();
87
+ export const dynamic = 'force-dynamic';
88
+ ```
89
+
90
+ - `tagPage(tags)` adds tags to the page being rendered, for example a decorator that lists another collection: `tagPage([collectionTag('post_detail')])`.
91
+ - `bomCached(name, fn, { life, tags, resultTags })` caches a data function by name. `life` is a BOM profile (`bom-layout`, `bom-page`, `bom-listing`, `bom-static`, see `bomProfiles`) or an inline profile. `documentTags(collection, result)` tags a result by its documents. Every entry carries `bom:fn:<name>`, so the panel lists and revalidates it.
92
+ - `withBom(nextConfig)` (`@websolutespa/bom-next/config`) wires the caching model:
93
+ - **Classic ISR** (default): `bomCached` uses `unstable_cache`, templates keep `generateStaticParams` and `export const revalidate`.
94
+ - **`cacheComponents: true`**: `bomCached` and `tagPage` use `'use cache'`, `cacheLife` and `cacheTag`; the BOM profiles are registered as `cacheLife` profiles, `cacheHandlers.default` is the BOM `'use cache'` handler, and `createPageContext` reads public pages and layouts through cached functions. Templates must drop `export const revalidate`. `getStaticParams` returns at least one route per template (Cache Components refuses an empty list), so every template needs one published page at build time.
95
+ - **`REDIS_URL` at build time**: `cacheHandler` is the shared Redis handler (`@websolutespa/bom-next/cache-handlers/isr`), which applies `revalidateTag(tag, 'max')` as stale-while-revalidate across instances; `'use cache'` entries share its tag keys.
96
+ - `registerIntrumentation()` registers the in-process cache executor; Bowl uses `/api/-cache` (Bearer `MIXER_SECRET`) when it runs in another process.
97
+
98
+ The cache panel reads the file-system cache (`.next/server/app` and the Next.js 16.4 runtime route cache under `.next/server/route-cache`), the Redis handlers' meta keys, or nothing on Vercel. `next dev` has no ISR cache: check the panel after `next build && next start`.
99
+
100
+ ## Environment
101
+
102
+ Per-request diagnostics (proxy, local API calls, context cache) are logged in development only (`NODE_ENV` unset or `development`).
103
+
104
+ | Variable | Default | |
105
+ | ----------------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------ |
106
+ | `BOM_ROUTE_CACHE_TTL` | `30` | proxy route cache lifetime in seconds, `0` disables it |
107
+ | `MEMORY_CACHE_DURATION` | `300` | server context cache lifetime in seconds |
108
+ | `BOM_USE_CACHE_MAX_BYTES` | `67108864` | memory limit of the in-process `'use cache'` handler (Cache Components without Redis) |
109
+ | `MIXER_SECRET` | – | Bearer token of `/api/-revalidate` and `/api/-cache` |
110
+ | `REDIS_URL`, `REDIS_PREFIX` | – | shared Redis cache handlers (set at build time for `withBom`) and key prefix |
111
+ | `UI_REGISTRY_SOURCE_DIR` | `packages/ui/src` | registry source directory |
112
+ | `UI_REGISTRY_COMPONENTS_JSON` | nearest `components.json` | shadcn config whose aliases (e.g. `@/ui/lib/utils`) are mapped to registry imports |
113
+ | `UI_REGISTRY_SOURCE_ALIAS` | – | extra import prefix pointing at the registry source, e.g. `@/ui/` |
114
+ | `UI_REGISTRY_SKIP_UNRESOLVED` | – | `1` hides registry items that import app code; otherwise they are listed with `meta.unresolvedImports` |
115
+
116
+ ## User
117
+
118
+ `UserProvider` reads `/api/auth/me` once per page load, shared by every mount and client navigation. Pass `initialUser` (a user or `null`) when the server already knows it to skip the request; `setUser` and `invalidateUser()` keep the cached value current after login or logout.
119
+
120
+ `isEndUser(user)` (main entry, isomorphic) tells a site end user from a back-office user: the `user` role and the `end_users` collection (or the end user's name fields when the collection is unknown). Use it to guard the end users' reserved area; `/api/auth/me` answers with the same rule.
121
+
122
+ ## Rate limit
123
+
124
+ `createRateLimiter({ prefix, limit, windowSeconds })` (`/server`) is a fixed-window limiter for public endpoints such as form actions: `await limiter.hit(ip)` returns `{ allowed, remaining, reset, backend }`. With `REDIS_URL` the counters live in Redis (`<REDIS_PREFIX>:rate:<prefix>:<key>:<window>`), shared by every instance; without it, or while Redis is down, a bounded per-process map is used.
125
+
126
+ ## Security helpers
127
+
128
+ Generic pieces of a site's public surface, so every project gets the same safe defaults:
129
+
130
+ - **CORS** (main entry): `getAllowedOrigins()` (`NEXT_PUBLIC_URL` + `PAYLOAD_PUBLIC_CORS_URLS`, `*` ignored) and `getCsrfOrigins()` for the `cors` and `csrf` options of `payload.config.ts`; `getCorsHeaders(origin, allowed)`. `createApiCorsProxy()` (`/proxy`) applies them to `/api/*` as the first step of the proxy chain (add `/api/:path*` to the matcher): an allowed origin is echoed with credentials, never `*`.
131
+ - **Anti-spam** (main entry, isomorphic): `SPAM_FIELDS` (honeypot `website`, render time `_t`), `getSpamReason(body, minFillMs)`, `ANTI_SPAM_DEFAULTS`, and `getClientIp(request)` as the key of `createRateLimiter`.
132
+ - **Seed credentials** (main entry): `requireSeedEnv(key)` reads a seed user's email or password from the environment and stops the seed with a hint when it is missing. Call it inside the fixture function, never at module level.
@@ -1,5 +1,6 @@
1
1
  import { Middleware, MiddlewareOptions, NextMiddlewareResult, createProxy, getRequestOrigin } from "../proxy/proxy.js";
2
- import { Proxy, ResolvedRoute, RouteInterceptorProxy, RouteMiddleware, RouteMiddlewareOptions, RouteResolverResponse, clearRouteProxyCache, createRouteProxy, getRouteResolverPath } from "../proxy/route-proxy.js";
2
+ import { Proxy, ResolvedRoute, RouteInterceptorProxy, RouteMiddleware, RouteMiddlewareOptions, RouteResolverResponse, clearRouteProxyCache, createRouteProxy, getRouteCacheTtl, getRouteResolverPath } from "../proxy/route-proxy.js";
3
3
  import { protectedRouteProxy } from "../proxy/protected-route.js";
4
- import { detectCountry, detectLocale, isValidDetectedRoute, routeAutoDetection } from "../proxy/route-auto-detection.js";
5
- export { Middleware, MiddlewareOptions, NextMiddlewareResult, Proxy, ResolvedRoute, RouteInterceptorProxy, RouteMiddleware, RouteMiddlewareOptions, RouteResolverResponse, clearRouteProxyCache, createProxy, createRouteProxy, detectCountry, detectLocale, getRequestOrigin, getRouteResolverPath, isValidDetectedRoute, protectedRouteProxy, routeAutoDetection };
4
+ import { ApiCorsProxyOptions, createApiCorsProxy } from "../proxy/api-cors.js";
5
+ import { clearRootRoutesCache, detectCountry, detectLocale, isValidDetectedRoute, routeAutoDetection } from "../proxy/route-auto-detection.js";
6
+ export { ApiCorsProxyOptions, Middleware, MiddlewareOptions, NextMiddlewareResult, Proxy, ResolvedRoute, RouteInterceptorProxy, RouteMiddleware, RouteMiddlewareOptions, RouteResolverResponse, clearRootRoutesCache, clearRouteProxyCache, createApiCorsProxy, createProxy, createRouteProxy, detectCountry, detectLocale, getRequestOrigin, getRouteCacheTtl, getRouteResolverPath, isValidDetectedRoute, protectedRouteProxy, routeAutoDetection };
@@ -1,5 +1,6 @@
1
1
  import { createProxy, getRequestOrigin } from "../proxy/proxy.js";
2
2
  import { protectedRouteProxy } from "../proxy/protected-route.js";
3
- import { detectCountry, detectLocale, isValidDetectedRoute, routeAutoDetection } from "../proxy/route-auto-detection.js";
4
- import { clearRouteProxyCache, createRouteProxy, getRouteResolverPath } from "../proxy/route-proxy.js";
5
- export { clearRouteProxyCache, createProxy, createRouteProxy, detectCountry, detectLocale, getRequestOrigin, getRouteResolverPath, isValidDetectedRoute, protectedRouteProxy, routeAutoDetection };
3
+ import { createApiCorsProxy } from "../proxy/api-cors.js";
4
+ import { clearRouteProxyCache, createRouteProxy, getRouteCacheTtl, getRouteResolverPath } from "../proxy/route-proxy.js";
5
+ import { clearRootRoutesCache, detectCountry, detectLocale, isValidDetectedRoute, routeAutoDetection } from "../proxy/route-auto-detection.js";
6
+ export { clearRootRoutesCache, clearRouteProxyCache, createApiCorsProxy, createProxy, createRouteProxy, detectCountry, detectLocale, getRequestOrigin, getRouteCacheTtl, getRouteResolverPath, isValidDetectedRoute, protectedRouteProxy, routeAutoDetection };
@@ -29,6 +29,7 @@ import { getLocalApi } from "../server/local-api.js";
29
29
  import { GetPageMetadataOptions, PageMetadataProps, getMetadata, getPageMetadata } from "../server/metadata.js";
30
30
  import { buildBaseOptions, buildReadOptions, clearMixerContextCache, filterRoutes, getAuthHeaders, getCacheKey, getContext, getMixerContext, getOptions, getPayload, getPayloadInstance, getRoutes, getSearchParams, resolveDraft, setContext } from "../server/mixer.js";
31
31
  import { PAGE_ENVELOPE_FIELDS, getPage, withEnvelopeSelect } from "../server/page.js";
32
+ import { RateLimitOptions, RateLimitResult, RateLimiter, RedisCounter, createRateLimiter } from "../server/rate-limit.js";
32
33
  import { getHrefBeforeRedirect, getNextUrl } from "../server/utils.js";
33
34
  import { getUtmz } from "../server/utmz.js";
34
- export { BomCacheLife, BomCacheProfile, BomCachedOptions, BomProfileName, CacheAction, CacheActionResult, CacheBackend, CacheInspector, CacheMode, CacheTagAction, CachedFunction, CachedPage, CdnPurgeHandler, GetPageMetadataOptions, ISiteMap, JsonLd, PAGE_ENVELOPE_FIELDS, PREVIEW_ROLES, PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataProps, PageMetadataSearchParams, PageStructuredDataOptions, ProcessCache, ProcessCacheStatus, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getLocalApi, getMetadata, getMixerContext, getNextUrl, getOptions, getPage, getPageAlternates, getPageContext, getPageMetadata, getPageXDefault, getPaginationQuery, getPayload, getPayloadInstance, getPreviewHandler, getRegistry, getRegistryItem, getRevalidateHandler, getRouteHandler, getRoutes, getSearchParams, getSiteMapIndex, getSiteMapXML, getSiteMapXSL, getStaticParams, getStaticParamsFromPayload, getStaticParams_, getUtmz, getVarsHandler, indexGetHandler, inheritParentMetadata, isIndexableDeployment, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
35
+ export { BomCacheLife, BomCacheProfile, BomCachedOptions, BomProfileName, CacheAction, CacheActionResult, CacheBackend, CacheInspector, CacheMode, CacheTagAction, CachedFunction, CachedPage, CdnPurgeHandler, GetPageMetadataOptions, ISiteMap, JsonLd, PAGE_ENVELOPE_FIELDS, PREVIEW_ROLES, PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataProps, PageMetadataSearchParams, PageStructuredDataOptions, ProcessCache, ProcessCacheStatus, RateLimitOptions, RateLimitResult, RateLimiter, RedisCounter, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, createRateLimiter, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getLocalApi, getMetadata, getMixerContext, getNextUrl, getOptions, getPage, getPageAlternates, getPageContext, getPageMetadata, getPageXDefault, getPaginationQuery, getPayload, getPayloadInstance, getPreviewHandler, getRegistry, getRegistryItem, getRevalidateHandler, getRouteHandler, getRoutes, getSearchParams, getSiteMapIndex, getSiteMapXML, getSiteMapXSL, getStaticParams, getStaticParamsFromPayload, getStaticParams_, getUtmz, getVarsHandler, indexGetHandler, inheritParentMetadata, isIndexableDeployment, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
@@ -29,5 +29,6 @@ import { getMetadata, getPageMetadata } from "../server/metadata.js";
29
29
  import { createContextHelpers } from "../server/helpers.js";
30
30
  import { JsonLd, buildPageStructuredData } from "../server/json-ld.js";
31
31
  import { decorateLazyComponents, withLazyProps } from "../server/lazy.js";
32
+ import { createRateLimiter } from "../server/rate-limit.js";
32
33
  import { getUtmz } from "../server/utmz.js";
33
- export { JsonLd, PAGE_ENVELOPE_FIELDS, PREVIEW_ROLES, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getLocalApi, getMetadata, getMixerContext, getNextUrl, getOptions, getPage, getPageAlternates, getPageContext, getPageMetadata, getPageXDefault, getPaginationQuery, getPayload, getPayloadInstance, getPreviewHandler, getRegistry, getRegistryItem, getRevalidateHandler, getRouteHandler, getRoutes, getSearchParams, getSiteMapIndex, getSiteMapXML, getSiteMapXSL, getStaticParams, getStaticParamsFromPayload, getStaticParams_, getUtmz, getVarsHandler, indexGetHandler, inheritParentMetadata, isIndexableDeployment, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
34
+ export { JsonLd, PAGE_ENVELOPE_FIELDS, PREVIEW_ROLES, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, createRateLimiter, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getLocalApi, getMetadata, getMixerContext, getNextUrl, getOptions, getPage, getPageAlternates, getPageContext, getPageMetadata, getPageXDefault, getPaginationQuery, getPayload, getPayloadInstance, getPreviewHandler, getRegistry, getRegistryItem, getRevalidateHandler, getRouteHandler, getRoutes, getSearchParams, getSiteMapIndex, getSiteMapXML, getSiteMapXSL, getStaticParams, getStaticParamsFromPayload, getStaticParams_, getUtmz, getVarsHandler, indexGetHandler, inheritParentMetadata, isIndexableDeployment, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
package/dist/index.d.ts CHANGED
@@ -11,8 +11,12 @@ import { getLink } from "./lib/link.js";
11
11
  import { IPaginationInfo, IPaginationItem, IPaginationOptions, getMoreItems, getPagedItems, getPaginationInfo, isPaginationInfo } from "./lib/pagination.js";
12
12
  import { getRouteLinkCategory, getRouteTemplate, newRouteLink, resolveRoute, routeToLink, routeToRouteLink } from "./lib/route.js";
13
13
  import { BuildStrategy, NextPhase, StoreStrategy, buildStrategy, nextPhase, storeCacheDuration, storeStrategy } from "./lib/store.js";
14
- import { getPublicUrl, resolveHref, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, trimTerminalSlash } from "./lib/utils.js";
15
- import { IMockCollection, IMockDocument, IMockGlobal, IMockLocale, IMockLocalized, IMockMedia, IMockMenu, IMockMenuItem, IMockPage, IMockStore } from "./mock.js";
14
+ import { CORS_HEADERS, CORS_METHODS, CorsEnv, getAllowedOrigins, getCorsHeaders, getCsrfOrigins } from "./lib/cors.js";
15
+ import { requireSeedEnv } from "./lib/seed-env.js";
16
+ import { ANTI_SPAM_DEFAULTS, AntiSpamOptions, SPAM_FIELDS, SpamReason, getClientIp, getSpamReason } from "./lib/spam.js";
16
17
  import { ErrorContext, RequestInfo } from "./instrumentation/types.js";
17
18
  import { BaseOptions, ComponentContext, ComponentProps, DraftOption, IContext, IEndUser, ILazyComponent, ILazyComponentFunc, ILazyComponentProps, ILazyFuncProps, ILazyModules, ILazyProps, ILazyStaticProps, ILazyStaticPropsFunc, ILazyableProps, ILazyedProps, INullableLazyableProps, IPageContext, IUser, LayoutContext, LayoutContextOptions, LayoutFor, LayoutOption, LayoutOptions, LocalProvider, MarketLocaleParams, MixerContext, NotFoundContext, NotFoundParams, PageContext, PageContextOptions, PageDocument, PageEnvelope, PageEnvelopeField, PageLayoutContext, PageParams, PageSelect, PartialPageProps, Populated, ReadOptions, ReadonlyHeaders, SearchParams, TypedPage, TypedPageContext, WithEnvelopeSelect } from "./types.js";
18
- export { ApiRequestOptions, BaseOptions, BuildStrategy, ComponentContext, ComponentProps, DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, DraftOption, ErrorContext, IAlternate, IBrand, IContext, IEndUser, ILazyComponent, ILazyComponentFunc, ILazyComponentProps, ILazyFuncProps, ILazyModules, ILazyProps, ILazyStaticProps, ILazyStaticPropsFunc, ILazyableProps, ILazyedProps, IMeta, IMetaData, IMockCollection, IMockDocument, IMockGlobal, IMockLocale, IMockLocalized, IMockMedia, IMockMenu, IMockMenuItem, IMockPage, IMockStore, INullableLazyableProps, IPageContext, IPaginationInfo, IPaginationItem, IPaginationOptions, IUser, LabelService, LayoutContext, LayoutContextOptions, LayoutDefaults, LayoutFor, LayoutOption, LayoutOptions, LocalProvider, MarketLocaleParams, MixerContext, NextPhase, NotFoundContext, NotFoundParams, OpenGraphArticle, OpenGraphAudio, OpenGraphBase, OpenGraphBook, OpenGraphBusiness, OpenGraphImage, OpenGraphMusic, OpenGraphPlace, OpenGraphProduct, OpenGraphProductGroup, OpenGraphProfile, OpenGraphRestaurant, OpenGraphType, OpenGraphVideo, OpenGraphWebsite, PREVIEW_ROLES, PageContext, PageContextOptions, PageDocument, PageEnvelope, PageEnvelopeField, PageLayoutContext, PageParams, PageSelect, PartialPageProps, Populated, ReadOptions, ReadonlyHeaders, RequestInfo, SearchParams, StoreStrategy, StructuredDataType, TwitterCardApp, TwitterCardBase, TwitterCardPlayer, TwitterCardSummary, TwitterCardSummaryLargeImage, TwitterCardType, TypedPage, TypedPageContext, WithEnvelopeSelect, buildBreadcrumb, buildStrategy, getLabelFromLabels, getLink, getLocalApiRequestOptions, getLocalApiUrl, getMoreItems, getPagedItems, getPaginationInfo, getPublicUrl, getRemoteApiRequestOptions, getRouteLinkCategory, getRouteTemplate, guest, interpolateText, isPaginationInfo, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut, newRouteLink, nextPhase, previewer, resolveHref, resolveRoute, routeToLink, routeToRouteLink, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, storeCacheDuration, storeStrategy, trimTerminalSlash };
19
+ import { END_USERS_COLLECTION, isEndUser } from "./lib/user.js";
20
+ import { getPublicUrl, resolveHref, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, trimTerminalSlash } from "./lib/utils.js";
21
+ import { IMockCollection, IMockDocument, IMockGlobal, IMockLocale, IMockLocalized, IMockMedia, IMockMenu, IMockMenuItem, IMockPage, IMockStore } from "./mock.js";
22
+ export { ANTI_SPAM_DEFAULTS, AntiSpamOptions, ApiRequestOptions, BaseOptions, BuildStrategy, CORS_HEADERS, CORS_METHODS, ComponentContext, ComponentProps, CorsEnv, DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, DraftOption, END_USERS_COLLECTION, ErrorContext, IAlternate, IBrand, IContext, IEndUser, ILazyComponent, ILazyComponentFunc, ILazyComponentProps, ILazyFuncProps, ILazyModules, ILazyProps, ILazyStaticProps, ILazyStaticPropsFunc, ILazyableProps, ILazyedProps, IMeta, IMetaData, IMockCollection, IMockDocument, IMockGlobal, IMockLocale, IMockLocalized, IMockMedia, IMockMenu, IMockMenuItem, IMockPage, IMockStore, INullableLazyableProps, IPageContext, IPaginationInfo, IPaginationItem, IPaginationOptions, IUser, LabelService, LayoutContext, LayoutContextOptions, LayoutDefaults, LayoutFor, LayoutOption, LayoutOptions, LocalProvider, MarketLocaleParams, MixerContext, NextPhase, NotFoundContext, NotFoundParams, OpenGraphArticle, OpenGraphAudio, OpenGraphBase, OpenGraphBook, OpenGraphBusiness, OpenGraphImage, OpenGraphMusic, OpenGraphPlace, OpenGraphProduct, OpenGraphProductGroup, OpenGraphProfile, OpenGraphRestaurant, OpenGraphType, OpenGraphVideo, OpenGraphWebsite, PREVIEW_ROLES, PageContext, PageContextOptions, PageDocument, PageEnvelope, PageEnvelopeField, PageLayoutContext, PageParams, PageSelect, PartialPageProps, Populated, ReadOptions, ReadonlyHeaders, RequestInfo, SPAM_FIELDS, SearchParams, SpamReason, StoreStrategy, StructuredDataType, TwitterCardApp, TwitterCardBase, TwitterCardPlayer, TwitterCardSummary, TwitterCardSummaryLargeImage, TwitterCardType, TypedPage, TypedPageContext, WithEnvelopeSelect, buildBreadcrumb, buildStrategy, getAllowedOrigins, getClientIp, getCorsHeaders, getCsrfOrigins, getLabelFromLabels, getLink, getLocalApiRequestOptions, getLocalApiUrl, getMoreItems, getPagedItems, getPaginationInfo, getPublicUrl, getRemoteApiRequestOptions, getRouteLinkCategory, getRouteTemplate, getSpamReason, guest, interpolateText, isEndUser, isPaginationInfo, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut, newRouteLink, nextPhase, previewer, requireSeedEnv, resolveHref, resolveRoute, routeToLink, routeToRouteLink, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, storeCacheDuration, storeStrategy, trimTerminalSlash };
package/dist/index.js CHANGED
@@ -7,5 +7,9 @@ import { LayoutDefaults } from "./lib/layout.defaults.js";
7
7
  import { getLink } from "./lib/link.js";
8
8
  import { getMoreItems, getPagedItems, getPaginationInfo, isPaginationInfo } from "./lib/pagination.js";
9
9
  import { BuildStrategy, NextPhase, StoreStrategy, buildStrategy, nextPhase, storeCacheDuration, storeStrategy } from "./lib/store.js";
10
+ import { CORS_HEADERS, CORS_METHODS, getAllowedOrigins, getCorsHeaders, getCsrfOrigins } from "./lib/cors.js";
11
+ import { requireSeedEnv } from "./lib/seed-env.js";
12
+ import { ANTI_SPAM_DEFAULTS, SPAM_FIELDS, getClientIp, getSpamReason } from "./lib/spam.js";
13
+ import { END_USERS_COLLECTION, isEndUser } from "./lib/user.js";
10
14
  import { getPublicUrl, resolveHref, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, trimTerminalSlash } from "./lib/utils.js";
11
- export { BuildStrategy, DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, LabelService, LayoutDefaults, NextPhase, PREVIEW_ROLES, StoreStrategy, buildBreadcrumb, buildStrategy, getLabelFromLabels, getLink, getLocalApiRequestOptions, getLocalApiUrl, getMoreItems, getPagedItems, getPaginationInfo, getPublicUrl, getRemoteApiRequestOptions, getRouteLinkCategory, getRouteTemplate, guest, interpolateText, isPaginationInfo, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut, newRouteLink, nextPhase, previewer, resolveHref, resolveRoute, routeToLink, routeToRouteLink, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, storeCacheDuration, storeStrategy, trimTerminalSlash };
15
+ export { ANTI_SPAM_DEFAULTS, BuildStrategy, CORS_HEADERS, CORS_METHODS, DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, END_USERS_COLLECTION, LabelService, LayoutDefaults, NextPhase, PREVIEW_ROLES, SPAM_FIELDS, StoreStrategy, buildBreadcrumb, buildStrategy, getAllowedOrigins, getClientIp, getCorsHeaders, getCsrfOrigins, getLabelFromLabels, getLink, getLocalApiRequestOptions, getLocalApiUrl, getMoreItems, getPagedItems, getPaginationInfo, getPublicUrl, getRemoteApiRequestOptions, getRouteLinkCategory, getRouteTemplate, getSpamReason, guest, interpolateText, isEndUser, isPaginationInfo, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut, newRouteLink, nextPhase, previewer, requireSeedEnv, resolveHref, resolveRoute, routeToLink, routeToRouteLink, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, storeCacheDuration, storeStrategy, trimTerminalSlash };
@@ -0,0 +1,25 @@
1
+ //#region src/lib/cors.d.ts
2
+ /**
3
+ * Cross-origin policy of a BOM site: its `/api/*` route handlers (see `createApiCorsProxy` in `/proxy`) and Payload
4
+ * (`cors` and `csrf` of `payload.config.ts`).
5
+ *
6
+ * Allowed origins: `NEXT_PUBLIC_URL` plus the comma separated `PAYLOAD_PUBLIC_CORS_URLS`. `*` is never honoured:
7
+ * these endpoints accept the session cookie (`payload-token`), and a wildcard origin with credentials would let any
8
+ * site act as the logged-in user. An allowed origin is echoed back with `Access-Control-Allow-Credentials: true`;
9
+ * any other origin gets no CORS headers, so the browser blocks the response.
10
+ */
11
+ type CorsEnv = Record<string, string | undefined>;
12
+ declare const CORS_METHODS = "GET,OPTIONS,PATCH,DELETE,POST,PUT";
13
+ declare const CORS_HEADERS = "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Authorization";
14
+ /** The allowed origins, normalized (`https://host[:port]`), without duplicates and without `*`. */
15
+ declare function getAllowedOrigins(env?: CorsEnv): string[];
16
+ /** The CSRF allowlist of Payload: `PAYLOAD_PUBLIC_CSRF_URLS` plus `NEXT_PUBLIC_URL`, same normalization. */
17
+ declare function getCsrfOrigins(env?: CorsEnv): string[];
18
+ /**
19
+ * The CORS response headers for a request `origin`: the echo of an allowed origin with credentials, or only
20
+ * `Vary: Origin` (responses differ per origin, so shared caches must key on it).
21
+ */
22
+ declare function getCorsHeaders(origin: string | null, allowed: string[]): Record<string, string>;
23
+ //#endregion
24
+ export { CORS_HEADERS, CORS_METHODS, CorsEnv, getAllowedOrigins, getCorsHeaders, getCsrfOrigins };
25
+ //# sourceMappingURL=cors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cors.d.ts","names":[],"sources":["../../src/lib/cors.ts"],"mappings":";;AASA;;;;;AAEA;;;KAFY,OAAA,GAAU,MAAA;AAAA,cAET,YAAA;AAAA,cACA,YAAA;;iBAgBG,iBAAA,CAAkB,GAAA,GAAK,OAAA;;iBAMvB,cAAA,CAAe,GAAA,GAAK,OAAA;AANpC;;;;AAAA,iBAiBgB,cAAA,CAAe,MAAA,iBAAuB,OAAA,aAAoB,MAAA"}
@@ -0,0 +1,42 @@
1
+ //#region src/lib/cors.ts
2
+ const CORS_METHODS = "GET,OPTIONS,PATCH,DELETE,POST,PUT";
3
+ const CORS_HEADERS = "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Authorization";
4
+ function toOrigin(value) {
5
+ const trimmed = value.trim();
6
+ if (!trimmed || trimmed === "*") return;
7
+ try {
8
+ return new URL(trimmed).origin;
9
+ } catch {
10
+ return;
11
+ }
12
+ }
13
+ /** The allowed origins, normalized (`https://host[:port]`), without duplicates and without `*`. */
14
+ function getAllowedOrigins(env = process.env) {
15
+ const values = [env.NEXT_PUBLIC_URL || "", ...(env.PAYLOAD_PUBLIC_CORS_URLS || "").split(",")];
16
+ return [...new Set(values.map(toOrigin).filter((x) => Boolean(x)))];
17
+ }
18
+ /** The CSRF allowlist of Payload: `PAYLOAD_PUBLIC_CSRF_URLS` plus `NEXT_PUBLIC_URL`, same normalization. */
19
+ function getCsrfOrigins(env = process.env) {
20
+ return getAllowedOrigins({
21
+ NEXT_PUBLIC_URL: env.NEXT_PUBLIC_URL,
22
+ PAYLOAD_PUBLIC_CORS_URLS: env.PAYLOAD_PUBLIC_CSRF_URLS
23
+ });
24
+ }
25
+ /**
26
+ * The CORS response headers for a request `origin`: the echo of an allowed origin with credentials, or only
27
+ * `Vary: Origin` (responses differ per origin, so shared caches must key on it).
28
+ */
29
+ function getCorsHeaders(origin, allowed) {
30
+ const headers = { Vary: "Origin" };
31
+ if (origin && allowed.includes(origin)) {
32
+ headers["Access-Control-Allow-Origin"] = origin;
33
+ headers["Access-Control-Allow-Credentials"] = "true";
34
+ headers["Access-Control-Allow-Methods"] = CORS_METHODS;
35
+ headers["Access-Control-Allow-Headers"] = CORS_HEADERS;
36
+ }
37
+ return headers;
38
+ }
39
+ //#endregion
40
+ export { CORS_HEADERS, CORS_METHODS, getAllowedOrigins, getCorsHeaders, getCsrfOrigins };
41
+
42
+ //# sourceMappingURL=cors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cors.js","names":[],"sources":["../../src/lib/cors.ts"],"sourcesContent":["/**\r\n * Cross-origin policy of a BOM site: its `/api/*` route handlers (see `createApiCorsProxy` in `/proxy`) and Payload\r\n * (`cors` and `csrf` of `payload.config.ts`).\r\n *\r\n * Allowed origins: `NEXT_PUBLIC_URL` plus the comma separated `PAYLOAD_PUBLIC_CORS_URLS`. `*` is never honoured:\r\n * these endpoints accept the session cookie (`payload-token`), and a wildcard origin with credentials would let any\r\n * site act as the logged-in user. An allowed origin is echoed back with `Access-Control-Allow-Credentials: true`;\r\n * any other origin gets no CORS headers, so the browser blocks the response.\r\n */\r\nexport type CorsEnv = Record<string, string | undefined>;\r\n\r\nexport const CORS_METHODS = 'GET,OPTIONS,PATCH,DELETE,POST,PUT';\r\nexport const CORS_HEADERS =\r\n 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Authorization';\r\n\r\nfunction toOrigin(value: string): string | undefined {\r\n const trimmed = value.trim();\r\n if (!trimmed || trimmed === '*') {\r\n return undefined;\r\n }\r\n try {\r\n return new URL(trimmed).origin;\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\n/** The allowed origins, normalized (`https://host[:port]`), without duplicates and without `*`. */\r\nexport function getAllowedOrigins(env: CorsEnv = process.env): string[] {\r\n const values = [env.NEXT_PUBLIC_URL || '', ...(env.PAYLOAD_PUBLIC_CORS_URLS || '').split(',')];\r\n return [...new Set(values.map(toOrigin).filter((x): x is string => Boolean(x)))];\r\n}\r\n\r\n/** The CSRF allowlist of Payload: `PAYLOAD_PUBLIC_CSRF_URLS` plus `NEXT_PUBLIC_URL`, same normalization. */\r\nexport function getCsrfOrigins(env: CorsEnv = process.env): string[] {\r\n return getAllowedOrigins({\r\n NEXT_PUBLIC_URL: env.NEXT_PUBLIC_URL,\r\n PAYLOAD_PUBLIC_CORS_URLS: env.PAYLOAD_PUBLIC_CSRF_URLS,\r\n });\r\n}\r\n\r\n/**\r\n * The CORS response headers for a request `origin`: the echo of an allowed origin with credentials, or only\r\n * `Vary: Origin` (responses differ per origin, so shared caches must key on it).\r\n */\r\nexport function getCorsHeaders(origin: string | null, allowed: string[]): Record<string, string> {\r\n const headers: Record<string, string> = { Vary: 'Origin' };\r\n if (origin && allowed.includes(origin)) {\r\n headers['Access-Control-Allow-Origin'] = origin;\r\n headers['Access-Control-Allow-Credentials'] = 'true';\r\n headers['Access-Control-Allow-Methods'] = CORS_METHODS;\r\n headers['Access-Control-Allow-Headers'] = CORS_HEADERS;\r\n }\r\n return headers;\r\n}\r\n"],"mappings":";AAWA,MAAa,eAAe;AAC5B,MAAa,eACX;AAEF,SAAS,SAAS,OAAmC;CACnD,MAAM,UAAU,MAAM,MAAM;AAC5B,KAAI,CAAC,WAAW,YAAY,IAC1B;AAEF,KAAI;AACF,SAAO,IAAI,IAAI,QAAQ,CAAC;SAClB;AACN;;;;AAKJ,SAAgB,kBAAkB,MAAe,QAAQ,KAAe;CACtE,MAAM,SAAS,CAAC,IAAI,mBAAmB,IAAI,IAAI,IAAI,4BAA4B,IAAI,MAAM,IAAI,CAAC;AAC9F,QAAO,CAAC,GAAG,IAAI,IAAI,OAAO,IAAI,SAAS,CAAC,QAAQ,MAAmB,QAAQ,EAAE,CAAC,CAAC,CAAC;;;AAIlF,SAAgB,eAAe,MAAe,QAAQ,KAAe;AACnE,QAAO,kBAAkB;EACvB,iBAAiB,IAAI;EACrB,0BAA0B,IAAI;EAC/B,CAAC;;;;;;AAOJ,SAAgB,eAAe,QAAuB,SAA2C;CAC/F,MAAM,UAAkC,EAAE,MAAM,UAAU;AAC1D,KAAI,UAAU,QAAQ,SAAS,OAAO,EAAE;AACtC,UAAQ,iCAAiC;AACzC,UAAQ,sCAAsC;AAC9C,UAAQ,kCAAkC;AAC1C,UAAQ,kCAAkC;;AAE5C,QAAO"}
@@ -0,0 +1,13 @@
1
+ //#region src/lib/seed-env.d.ts
2
+ /**
3
+ * Credentials of seeded users, read from the environment (`.env.local`, generated by create-bom; the key list is the
4
+ * project's `.env.example`). There is no fallback: a known default password would open every database seeded
5
+ * without the variable.
6
+ *
7
+ * Call it inside the fixture function the seed plugin calls (`users: () => users()`), never at module level: the
8
+ * seed calls fixtures only when it runs, so a deployment that does not seed starts without these variables.
9
+ */
10
+ declare function requireSeedEnv(key: string): string;
11
+ //#endregion
12
+ export { requireSeedEnv };
13
+ //# sourceMappingURL=seed-env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"seed-env.d.ts","names":[],"sources":["../../src/lib/seed-env.ts"],"mappings":";;AAQA;;;;;;;iBAAgB,cAAA,CAAe,GAAA"}
@@ -0,0 +1,18 @@
1
+ //#region src/lib/seed-env.ts
2
+ /**
3
+ * Credentials of seeded users, read from the environment (`.env.local`, generated by create-bom; the key list is the
4
+ * project's `.env.example`). There is no fallback: a known default password would open every database seeded
5
+ * without the variable.
6
+ *
7
+ * Call it inside the fixture function the seed plugin calls (`users: () => users()`), never at module level: the
8
+ * seed calls fixtures only when it runs, so a deployment that does not seed starts without these variables.
9
+ */
10
+ function requireSeedEnv(key) {
11
+ const value = process.env[key]?.trim();
12
+ if (!value) throw new Error(`Missing \`${key}\` in \`.env.local\`: create-bom writes it when it creates the project; otherwise copy the key from the \`# [secrets]\` section of \`.env.example\` and set its value.`);
13
+ return value;
14
+ }
15
+ //#endregion
16
+ export { requireSeedEnv };
17
+
18
+ //# sourceMappingURL=seed-env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"seed-env.js","names":[],"sources":["../../src/lib/seed-env.ts"],"sourcesContent":["/**\r\n * Credentials of seeded users, read from the environment (`.env.local`, generated by create-bom; the key list is the\r\n * project's `.env.example`). There is no fallback: a known default password would open every database seeded\r\n * without the variable.\r\n *\r\n * Call it inside the fixture function the seed plugin calls (`users: () => users()`), never at module level: the\r\n * seed calls fixtures only when it runs, so a deployment that does not seed starts without these variables.\r\n */\r\nexport function requireSeedEnv(key: string): string {\r\n const value = process.env[key]?.trim();\r\n if (!value) {\r\n throw new Error(\r\n `Missing \\`${key}\\` in \\`.env.local\\`: create-bom writes it when it creates the project; otherwise copy the key from the \\`# [secrets]\\` section of \\`.env.example\\` and set its value.`\r\n );\r\n }\r\n return value;\r\n}\r\n"],"mappings":";;;;;;;;;AAQA,SAAgB,eAAe,KAAqB;CAClD,MAAM,QAAQ,QAAQ,IAAI,MAAM,MAAM;AACtC,KAAI,CAAC,MACH,OAAM,IAAI,MACR,aAAa,IAAI,wKAClB;AAEH,QAAO"}
@@ -0,0 +1,38 @@
1
+ //#region src/lib/spam.d.ts
2
+ /**
3
+ * Anti-spam checks of public form endpoints, shared by the browser (the form posts the fields) and the route (it
4
+ * checks them on the raw body before validation). Isomorphic, no dependencies.
5
+ *
6
+ * - Honeypot: a text input hidden from people and from assistive technology; bots that fill every field fill it too.
7
+ * - Fill time: the time the form was rendered, posted back. A submit faster than a person can type is a bot, and a
8
+ * post without it did not come from the form.
9
+ *
10
+ * Cheap filters, not a guarantee: combine them with `createRateLimiter` (`/server`) per client IP
11
+ * ({@link getClientIp}), and a captcha verified on the server when an endpoint is targeted.
12
+ */
13
+ declare const SPAM_FIELDS: {
14
+ /** the honeypot input name: plausible for a bot, never used by a real form */readonly honeypot: "website"; /** epoch ms when the form was rendered */
15
+ readonly startedAt: "_t";
16
+ };
17
+ type AntiSpamOptions = {
18
+ /** minimum time between render and submit, default 3 s */minFillMs?: number; /** submits per IP and endpoint in `windowSeconds`, default 5 per 10 minutes */
19
+ rateLimit?: {
20
+ limit: number;
21
+ windowSeconds: number;
22
+ };
23
+ };
24
+ declare const ANTI_SPAM_DEFAULTS: Required<AntiSpamOptions>;
25
+ type SpamReason = 'honeypot' | 'fill-time';
26
+ /** Why a posted body is spam, or `undefined` when it passes the honeypot and fill time checks. */
27
+ declare function getSpamReason(body: unknown, minFillMs?: number, now?: number): SpamReason | undefined;
28
+ /**
29
+ * The client IP of a request, for rate limits: the first `x-forwarded-for` hop, then `x-real-ip`, else `unknown`.
30
+ * Behind a proxy that does not overwrite these headers a client can spoof them; a limit keyed on it still caps one
31
+ * client per forged value.
32
+ */
33
+ declare function getClientIp(request: {
34
+ headers: Headers;
35
+ }): string;
36
+ //#endregion
37
+ export { ANTI_SPAM_DEFAULTS, AntiSpamOptions, SPAM_FIELDS, SpamReason, getClientIp, getSpamReason };
38
+ //# sourceMappingURL=spam.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spam.d.ts","names":[],"sources":["../../src/lib/spam.ts"],"mappings":";;AAWA;;;;;AAOA;;;;;cAPa,WAAA;EAWG,uFANN,QAAA,aAMkC;EAAA,SANlC,SAAA;AAAA;AAAA,KAEE,eAAA;4DAEV,SAAA,WAKuD;EAHvD,SAAA;IAAc,KAAA;IAAe,aAAA;EAAA;AAAA;AAAA,cAGlB,kBAAA,EAAoB,QAAA,CAAS,eAAA;AAAA,KAK9B,UAAA;;iBAGI,aAAA,CACd,IAAA,WACA,SAAA,WACA,GAAA,YACC,UAAA;;;;;;iBAkBa,WAAA,CAAY,OAAA;EAAW,OAAA,EAAS,OAAA;AAAA"}