@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
@@ -0,0 +1,43 @@
1
+ //#region src/lib/spam.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
+ const SPAM_FIELDS = {
14
+ honeypot: "website",
15
+ startedAt: "_t"
16
+ };
17
+ const ANTI_SPAM_DEFAULTS = {
18
+ minFillMs: 3e3,
19
+ rateLimit: {
20
+ limit: 5,
21
+ windowSeconds: 600
22
+ }
23
+ };
24
+ /** Why a posted body is spam, or `undefined` when it passes the honeypot and fill time checks. */
25
+ function getSpamReason(body, minFillMs = ANTI_SPAM_DEFAULTS.minFillMs, now = Date.now()) {
26
+ const record = body && typeof body === "object" ? body : {};
27
+ const honeypot = record[SPAM_FIELDS.honeypot];
28
+ if (typeof honeypot === "string" ? honeypot.trim() !== "" : honeypot != null) return "honeypot";
29
+ const startedAt = Number(record[SPAM_FIELDS.startedAt]);
30
+ if (!Number.isFinite(startedAt) || startedAt > now || now - startedAt < minFillMs) return "fill-time";
31
+ }
32
+ /**
33
+ * The client IP of a request, for rate limits: the first `x-forwarded-for` hop, then `x-real-ip`, else `unknown`.
34
+ * Behind a proxy that does not overwrite these headers a client can spoof them; a limit keyed on it still caps one
35
+ * client per forged value.
36
+ */
37
+ function getClientIp(request) {
38
+ return request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip")?.trim() || "unknown";
39
+ }
40
+ //#endregion
41
+ export { ANTI_SPAM_DEFAULTS, SPAM_FIELDS, getClientIp, getSpamReason };
42
+
43
+ //# sourceMappingURL=spam.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spam.js","names":[],"sources":["../../src/lib/spam.ts"],"sourcesContent":["/**\r\n * Anti-spam checks of public form endpoints, shared by the browser (the form posts the fields) and the route (it\r\n * checks them on the raw body before validation). Isomorphic, no dependencies.\r\n *\r\n * - Honeypot: a text input hidden from people and from assistive technology; bots that fill every field fill it too.\r\n * - Fill time: the time the form was rendered, posted back. A submit faster than a person can type is a bot, and a\r\n * post without it did not come from the form.\r\n *\r\n * Cheap filters, not a guarantee: combine them with `createRateLimiter` (`/server`) per client IP\r\n * ({@link getClientIp}), and a captcha verified on the server when an endpoint is targeted.\r\n */\r\nexport const SPAM_FIELDS = {\r\n /** the honeypot input name: plausible for a bot, never used by a real form */\r\n honeypot: 'website',\r\n /** epoch ms when the form was rendered */\r\n startedAt: '_t',\r\n} as const;\r\n\r\nexport type AntiSpamOptions = {\r\n /** minimum time between render and submit, default 3 s */\r\n minFillMs?: number;\r\n /** submits per IP and endpoint in `windowSeconds`, default 5 per 10 minutes */\r\n rateLimit?: { limit: number; windowSeconds: number };\r\n};\r\n\r\nexport const ANTI_SPAM_DEFAULTS: Required<AntiSpamOptions> = {\r\n minFillMs: 3000,\r\n rateLimit: { limit: 5, windowSeconds: 600 },\r\n};\r\n\r\nexport type SpamReason = 'honeypot' | 'fill-time';\r\n\r\n/** Why a posted body is spam, or `undefined` when it passes the honeypot and fill time checks. */\r\nexport function getSpamReason(\r\n body: unknown,\r\n minFillMs: number = ANTI_SPAM_DEFAULTS.minFillMs,\r\n now: number = Date.now()\r\n): SpamReason | undefined {\r\n const record = (body && typeof body === 'object' ? body : {}) as Record<string, unknown>;\r\n const honeypot = record[SPAM_FIELDS.honeypot];\r\n if (typeof honeypot === 'string' ? honeypot.trim() !== '' : honeypot != null) {\r\n return 'honeypot';\r\n }\r\n const startedAt = Number(record[SPAM_FIELDS.startedAt]);\r\n if (!Number.isFinite(startedAt) || startedAt > now || now - startedAt < minFillMs) {\r\n return 'fill-time';\r\n }\r\n return undefined;\r\n}\r\n\r\n/**\r\n * The client IP of a request, for rate limits: the first `x-forwarded-for` hop, then `x-real-ip`, else `unknown`.\r\n * Behind a proxy that does not overwrite these headers a client can spoof them; a limit keyed on it still caps one\r\n * client per forged value.\r\n */\r\nexport function getClientIp(request: { headers: Headers }): string {\r\n const forwarded = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();\r\n return forwarded || request.headers.get('x-real-ip')?.trim() || 'unknown';\r\n}\r\n"],"mappings":";;;;;;;;;;;;AAWA,MAAa,cAAc;CAEzB,UAAU;CAEV,WAAW;CACZ;AASD,MAAa,qBAAgD;CAC3D,WAAW;CACX,WAAW;EAAE,OAAO;EAAG,eAAe;EAAK;CAC5C;;AAKD,SAAgB,cACd,MACA,YAAoB,mBAAmB,WACvC,MAAc,KAAK,KAAK,EACA;CACxB,MAAM,SAAU,QAAQ,OAAO,SAAS,WAAW,OAAO,EAAE;CAC5D,MAAM,WAAW,OAAO,YAAY;AACpC,KAAI,OAAO,aAAa,WAAW,SAAS,MAAM,KAAK,KAAK,YAAY,KACtE,QAAO;CAET,MAAM,YAAY,OAAO,OAAO,YAAY,WAAW;AACvD,KAAI,CAAC,OAAO,SAAS,UAAU,IAAI,YAAY,OAAO,MAAM,YAAY,UACtE,QAAO;;;;;;;AAUX,SAAgB,YAAY,SAAuC;AAEjE,QADkB,QAAQ,QAAQ,IAAI,kBAAkB,EAAE,MAAM,IAAI,CAAC,IAAI,MAAM,IAC3D,QAAQ,QAAQ,IAAI,YAAY,EAAE,MAAM,IAAI"}
@@ -4,6 +4,9 @@
4
4
  *
5
5
  * Values are stored as promises so concurrent requests for the same key share
6
6
  * one upstream call. Rejected promises are evicted immediately.
7
+ *
8
+ * Expiry uses `performance.now()` (monotonic, process-relative), not `Date.now()`: the cache is read while
9
+ * rendering, and with Cache Components Next.js fails a prerender that reads the current time.
7
10
  */
8
11
  var TtlCache = class {
9
12
  entries = /* @__PURE__ */ new Map();
@@ -14,7 +17,7 @@ var TtlCache = class {
14
17
  return this.entries.size;
15
18
  }
16
19
  async getOrSet(key, ttl, factory) {
17
- const now = Date.now();
20
+ const now = performance.now();
18
21
  const entry = this.entries.get(key);
19
22
  if (entry && entry.expires > now) {
20
23
  this.entries.delete(key);
@@ -31,7 +34,7 @@ var TtlCache = class {
31
34
  try {
32
35
  const resolved = await value;
33
36
  const duration = ttl(resolved);
34
- if (duration > 0 && this.entries.get(key) === pending) pending.expires = Date.now() + duration;
37
+ if (duration > 0 && this.entries.get(key) === pending) pending.expires = performance.now() + duration;
35
38
  else if (this.entries.get(key) === pending) this.entries.delete(key);
36
39
  return resolved;
37
40
  } catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"ttl-cache.js","names":[],"sources":["../../src/lib/ttl-cache.ts"],"sourcesContent":["type TtlCacheEntry<T> = {\n value: Promise<T>;\n expires: number;\n};\n\n/**\n * Small per-instance TTL cache with LRU eviction and in-flight de-duplication.\n *\n * Values are stored as promises so concurrent requests for the same key share\n * one upstream call. Rejected promises are evicted immediately.\n */\nexport class TtlCache<T> {\n private readonly entries = new Map<string, TtlCacheEntry<T>>();\n\n constructor(private readonly maxSize: number) {}\n\n get size() {\n return this.entries.size;\n }\n\n async getOrSet(key: string, ttl: (value: T) => number, factory: () => Promise<T>): Promise<T> {\n const now = Date.now();\n const entry = this.entries.get(key);\n if (entry && entry.expires > now) {\n // Re-insert to mark the entry as most recently used.\n this.entries.delete(key);\n this.entries.set(key, entry);\n return entry.value;\n }\n if (entry) {\n this.entries.delete(key);\n }\n const value = factory();\n // Until the value settles, keep it long enough to de-duplicate concurrent calls.\n const pending: TtlCacheEntry<T> = { value, expires: Number.POSITIVE_INFINITY };\n this.set(key, pending);\n try {\n const resolved = await value;\n const duration = ttl(resolved);\n if (duration > 0 && this.entries.get(key) === pending) {\n pending.expires = Date.now() + duration;\n } else if (this.entries.get(key) === pending) {\n this.entries.delete(key);\n }\n return resolved;\n } catch (error) {\n if (this.entries.get(key) === pending) {\n this.entries.delete(key);\n }\n throw error;\n }\n }\n\n delete(key: string) {\n this.entries.delete(key);\n }\n\n clear() {\n this.entries.clear();\n }\n\n private set(key: string, entry: TtlCacheEntry<T>) {\n if (this.entries.size >= this.maxSize) {\n // Maps iterate in insertion order, so the first key is the least recently used.\n const oldest = this.entries.keys().next().value;\n if (oldest !== undefined) {\n this.entries.delete(oldest);\n }\n }\n this.entries.set(key, entry);\n }\n}\n"],"mappings":";;;;;;;AAWA,IAAa,WAAb,MAAyB;CACvB,0BAA2B,IAAI,KAA+B;CAE9D,YAAY,SAAkC;AAAjB,OAAA,UAAA;;CAE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Small per-instance TTL cache with LRU eviction and in-flight de-duplication.\r\n *\r\n * Values are stored as promises so concurrent requests for the same key share\r\n * one upstream call. Rejected promises are evicted immediately.\r\n *\r\n * Expiry uses `performance.now()` (monotonic, process-relative), not `Date.now()`: the cache is read while\r\n * rendering, and with Cache Components Next.js fails a prerender that reads the current time.\r\n */\r\nexport class TtlCache<T> {\r\n private readonly entries = new Map<string, TtlCacheEntry<T>>();\r\n\r\n constructor(private readonly maxSize: number) {}\r\n\r\n get size() {\r\n return this.entries.size;\r\n }\r\n\r\n async getOrSet(key: string, ttl: (value: T) => number, factory: () => Promise<T>): Promise<T> {\r\n const now = performance.now();\r\n const entry = this.entries.get(key);\r\n if (entry && entry.expires > now) {\r\n // Re-insert to mark the entry as most recently used.\r\n this.entries.delete(key);\r\n this.entries.set(key, entry);\r\n return entry.value;\r\n }\r\n if (entry) {\r\n this.entries.delete(key);\r\n }\r\n const value = factory();\r\n // Until the value settles, keep it long enough to de-duplicate concurrent calls.\r\n const pending: TtlCacheEntry<T> = { value, expires: Number.POSITIVE_INFINITY };\r\n this.set(key, pending);\r\n try {\r\n const resolved = await value;\r\n const duration = ttl(resolved);\r\n if (duration > 0 && this.entries.get(key) === pending) {\r\n pending.expires = performance.now() + duration;\r\n } else if (this.entries.get(key) === pending) {\r\n this.entries.delete(key);\r\n }\r\n return resolved;\r\n } catch (error) {\r\n if (this.entries.get(key) === pending) {\r\n this.entries.delete(key);\r\n }\r\n throw error;\r\n }\r\n }\r\n\r\n delete(key: string) {\r\n this.entries.delete(key);\r\n }\r\n\r\n clear() {\r\n this.entries.clear();\r\n }\r\n\r\n private set(key: string, entry: TtlCacheEntry<T>) {\r\n if (this.entries.size >= this.maxSize) {\r\n // Maps iterate in insertion order, so the first key is the least recently used.\r\n const oldest = this.entries.keys().next().value;\r\n if (oldest !== undefined) {\r\n this.entries.delete(oldest);\r\n }\r\n }\r\n this.entries.set(key, entry);\r\n }\r\n}\r\n"],"mappings":";;;;;;;;;;AAcA,IA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3
+ //#region src/lib/user.d.ts
4
+ /** the slug of the Bowl collection of the site's registered users */
5
+ declare const END_USERS_COLLECTION = "end_users";
6
+ /**
7
+ * True when `user` is a site end user: a user with the `user` role that comes from the end users collection
8
+ * (`user.collection`, set by Payload auth) or carries the end user's name fields.
9
+ *
10
+ * A back-office user (collection `users`) that is also given the `user` role is not an end user: the role alone is
11
+ * not enough to open the end users' reserved area. Isomorphic: use it in layouts, pages and client components.
12
+ */
13
+ declare function isEndUser(user: unknown): user is IEndUser;
14
+ //#endregion
15
+ export { END_USERS_COLLECTION, isEndUser };
16
+ //# sourceMappingURL=user.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user.d.ts","names":[],"sources":["../../src/lib/user.ts"],"mappings":";;;;cAGa,oBAAA;AAAb;;;;;AASA;;AATA,iBASgB,SAAA,CAAU,IAAA,YAAgB,IAAA,IAAQ,QAAA"}
@@ -0,0 +1,21 @@
1
+ //#region src/lib/user.ts
2
+ /** the slug of the Bowl collection of the site's registered users */
3
+ const END_USERS_COLLECTION = "end_users";
4
+ /**
5
+ * True when `user` is a site end user: a user with the `user` role that comes from the end users collection
6
+ * (`user.collection`, set by Payload auth) or carries the end user's name fields.
7
+ *
8
+ * A back-office user (collection `users`) that is also given the `user` role is not an end user: the role alone is
9
+ * not enough to open the end users' reserved area. Isomorphic: use it in layouts, pages and client components.
10
+ */
11
+ function isEndUser(user) {
12
+ if (!user || typeof user !== "object") return false;
13
+ const { roles, collection } = user;
14
+ if (!Array.isArray(roles) || !roles.includes("user")) return false;
15
+ if (typeof collection === "string") return collection === END_USERS_COLLECTION;
16
+ return "firstName" in user;
17
+ }
18
+ //#endregion
19
+ export { END_USERS_COLLECTION, isEndUser };
20
+
21
+ //# sourceMappingURL=user.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user.js","names":[],"sources":["../../src/lib/user.ts"],"sourcesContent":["import type { IEndUser } from '../types';\r\n\r\n/** the slug of the Bowl collection of the site's registered users */\r\nexport const END_USERS_COLLECTION = 'end_users';\r\n\r\n/**\r\n * True when `user` is a site end user: a user with the `user` role that comes from the end users collection\r\n * (`user.collection`, set by Payload auth) or carries the end user's name fields.\r\n *\r\n * A back-office user (collection `users`) that is also given the `user` role is not an end user: the role alone is\r\n * not enough to open the end users' reserved area. Isomorphic: use it in layouts, pages and client components.\r\n */\r\nexport function isEndUser(user: unknown): user is IEndUser {\r\n if (!user || typeof user !== 'object') {\r\n return false;\r\n }\r\n const { roles, collection } = user as { roles?: unknown; collection?: unknown };\r\n if (!Array.isArray(roles) || !roles.includes('user')) {\r\n return false;\r\n }\r\n if (typeof collection === 'string') {\r\n return collection === END_USERS_COLLECTION;\r\n }\r\n return 'firstName' in user;\r\n}\r\n"],"mappings":";;AAGA,MAAa,uBAAuB;;;;;;;;AASpC,SAAgB,UAAU,MAAiC;AACzD,KAAI,CAAC,QAAQ,OAAO,SAAS,SAC3B,QAAO;CAET,MAAM,EAAE,OAAO,eAAe;AAC9B,KAAI,CAAC,MAAM,QAAQ,MAAM,IAAI,CAAC,MAAM,SAAS,OAAO,CAClD,QAAO;AAET,KAAI,OAAO,eAAe,SACxB,QAAO,eAAe;AAExB,QAAO,eAAe"}
@@ -0,0 +1,24 @@
1
+ import { Middleware } from "./proxy.js";
2
+
3
+ //#region src/proxy/api-cors.d.ts
4
+ type ApiCorsProxyOptions = {
5
+ /** origins allowed with credentials, default `getAllowedOrigins()` (NEXT_PUBLIC_URL + PAYLOAD_PUBLIC_CORS_URLS) */allowedOrigins?: string[]; /** path prefix of the API route handlers, default `/api/` */
6
+ prefix?: string;
7
+ };
8
+ /**
9
+ * Proxy step that applies the CORS policy (`src/lib/cors.ts`) to the API route handlers and ends the chain for them:
10
+ * an allowed origin is echoed with credentials, a preflight is answered here (204), any other origin gets no CORS
11
+ * headers. Other paths fall through to the next step. Put it first, and add `/api/:path*` to the proxy matcher:
12
+ *
13
+ * ```ts
14
+ * const proxyChain = createProxy(createApiCorsProxy(), routeAutoDetection, createRouteProxy(protectedRouteProxy));
15
+ * export const config = { matcher: ['/((?!admin|api|...).*)', '/api/:path*'] };
16
+ * ```
17
+ *
18
+ * It replaces static `Access-Control-Allow-Origin: *` headers in `next.config`, which combined with
19
+ * `Access-Control-Allow-Credentials: true` are invalid and unsafe.
20
+ */
21
+ declare function createApiCorsProxy(options?: ApiCorsProxyOptions): Middleware;
22
+ //#endregion
23
+ export { ApiCorsProxyOptions, createApiCorsProxy };
24
+ //# sourceMappingURL=api-cors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-cors.d.ts","names":[],"sources":["../../src/proxy/api-cors.ts"],"mappings":";;;KAIY,mBAAA;qHAEV,cAAA,aAF6B;EAI7B,MAAA;AAAA;;AAgBF;;;;;;;;;;;;iBAAgB,kBAAA,CAAmB,OAAA,GAAS,mBAAA,GAA2B,UAAA"}
@@ -0,0 +1,35 @@
1
+ import { getAllowedOrigins, getCorsHeaders } from "../lib/cors.js";
2
+ import { NextResponse } from "next/server";
3
+ //#region src/proxy/api-cors.ts
4
+ /**
5
+ * Proxy step that applies the CORS policy (`src/lib/cors.ts`) to the API route handlers and ends the chain for them:
6
+ * an allowed origin is echoed with credentials, a preflight is answered here (204), any other origin gets no CORS
7
+ * headers. Other paths fall through to the next step. Put it first, and add `/api/:path*` to the proxy matcher:
8
+ *
9
+ * ```ts
10
+ * const proxyChain = createProxy(createApiCorsProxy(), routeAutoDetection, createRouteProxy(protectedRouteProxy));
11
+ * export const config = { matcher: ['/((?!admin|api|...).*)', '/api/:path*'] };
12
+ * ```
13
+ *
14
+ * It replaces static `Access-Control-Allow-Origin: *` headers in `next.config`, which combined with
15
+ * `Access-Control-Allow-Credentials: true` are invalid and unsafe.
16
+ */
17
+ function createApiCorsProxy(options = {}) {
18
+ const allowed = options.allowedOrigins ?? getAllowedOrigins();
19
+ const prefix = options.prefix ?? "/api/";
20
+ return function apiCorsProxy({ request }) {
21
+ if (!request.nextUrl.pathname.startsWith(prefix)) return;
22
+ const headers = getCorsHeaders(request.headers.get("origin"), allowed);
23
+ if (request.method === "OPTIONS") return new NextResponse(null, {
24
+ status: 204,
25
+ headers
26
+ });
27
+ const response = NextResponse.next();
28
+ for (const [key, value] of Object.entries(headers)) response.headers.set(key, value);
29
+ return response;
30
+ };
31
+ }
32
+ //#endregion
33
+ export { createApiCorsProxy };
34
+
35
+ //# sourceMappingURL=api-cors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-cors.js","names":[],"sources":["../../src/proxy/api-cors.ts"],"sourcesContent":["import { NextResponse } from 'next/server';\r\nimport { getAllowedOrigins, getCorsHeaders } from '../lib/cors';\r\nimport type { Middleware } from './proxy';\r\n\r\nexport type ApiCorsProxyOptions = {\r\n /** origins allowed with credentials, default `getAllowedOrigins()` (NEXT_PUBLIC_URL + PAYLOAD_PUBLIC_CORS_URLS) */\r\n allowedOrigins?: string[];\r\n /** path prefix of the API route handlers, default `/api/` */\r\n prefix?: string;\r\n};\r\n\r\n/**\r\n * Proxy step that applies the CORS policy (`src/lib/cors.ts`) to the API route handlers and ends the chain for them:\r\n * an allowed origin is echoed with credentials, a preflight is answered here (204), any other origin gets no CORS\r\n * headers. Other paths fall through to the next step. Put it first, and add `/api/:path*` to the proxy matcher:\r\n *\r\n * ```ts\r\n * const proxyChain = createProxy(createApiCorsProxy(), routeAutoDetection, createRouteProxy(protectedRouteProxy));\r\n * export const config = { matcher: ['/((?!admin|api|...).*)', '/api/:path*'] };\r\n * ```\r\n *\r\n * It replaces static `Access-Control-Allow-Origin: *` headers in `next.config`, which combined with\r\n * `Access-Control-Allow-Credentials: true` are invalid and unsafe.\r\n */\r\nexport function createApiCorsProxy(options: ApiCorsProxyOptions = {}): Middleware {\r\n const allowed = options.allowedOrigins ?? getAllowedOrigins();\r\n const prefix = options.prefix ?? '/api/';\r\n return function apiCorsProxy({ request }) {\r\n if (!request.nextUrl.pathname.startsWith(prefix)) {\r\n return undefined;\r\n }\r\n const headers = getCorsHeaders(request.headers.get('origin'), allowed);\r\n if (request.method === 'OPTIONS') {\r\n return new NextResponse(null, { status: 204, headers });\r\n }\r\n const response = NextResponse.next();\r\n for (const [key, value] of Object.entries(headers)) {\r\n response.headers.set(key, value);\r\n }\r\n return response;\r\n };\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;AAwBA,SAAgB,mBAAmB,UAA+B,EAAE,EAAc;CAChF,MAAM,UAAU,QAAQ,kBAAkB,mBAAmB;CAC7D,MAAM,SAAS,QAAQ,UAAU;AACjC,QAAO,SAAS,aAAa,EAAE,WAAW;AACxC,MAAI,CAAC,QAAQ,QAAQ,SAAS,WAAW,OAAO,CAC9C;EAEF,MAAM,UAAU,eAAe,QAAQ,QAAQ,IAAI,SAAS,EAAE,QAAQ;AACtE,MAAI,QAAQ,WAAW,UACrB,QAAO,IAAI,aAAa,MAAM;GAAE,QAAQ;GAAK;GAAS,CAAC;EAEzD,MAAM,WAAW,aAAa,MAAM;AACpC,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,CAChD,UAAS,QAAQ,IAAI,KAAK,MAAM;AAElC,SAAO"}
@@ -8,8 +8,10 @@ declare function detectLocale(request: NextRequest, defaultLocale?: string): Pro
8
8
  * else (absolute or protocol-relative URLs) is ignored to avoid open redirects.
9
9
  */
10
10
  declare function isValidDetectedRoute(value?: string): value is string;
11
+ /** Drops cached root routes for this instance, e.g. from a test. */
12
+ declare function clearRootRoutesCache(): void;
11
13
  declare function detectCountry(request: NextRequest, defaultMarket?: string): Promise<string | undefined>;
12
14
  declare const routeAutoDetection: Middleware;
13
15
  //#endregion
14
- export { detectCountry, detectLocale, isValidDetectedRoute, routeAutoDetection };
16
+ export { clearRootRoutesCache, detectCountry, detectLocale, isValidDetectedRoute, routeAutoDetection };
15
17
  //# sourceMappingURL=route-auto-detection.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"route-auto-detection.d.ts","names":[],"sources":["../../src/proxy/route-auto-detection.ts"],"mappings":";;;;iBAMsB,YAAA,CAAa,OAAA,EAAS,WAAA,EAAa,aAAA,YAAsB,OAAA;;AAA/E;;;iBAiDgB,oBAAA,CAAqB,KAAA,YAAiB,KAAA;AAAA,iBAuBhC,aAAA,CAAc,OAAA,EAAS,WAAA,EAAa,aAAA,YAAsB,OAAA;AAAA,cA8CnE,kBAAA,EAAoB,UAAA"}
1
+ {"version":3,"file":"route-auto-detection.d.ts","names":[],"sources":["../../src/proxy/route-auto-detection.ts"],"mappings":";;;;iBAQsB,YAAA,CAAa,OAAA,EAAS,WAAA,EAAa,aAAA,YAAsB,OAAA;;AAA/E;;;iBAiDgB,oBAAA,CAAqB,KAAA,YAAiB,KAAA;;iBAgCtC,oBAAA,CAAA;AAAA,iBAeM,aAAA,CAAc,OAAA,EAAS,WAAA,EAAa,aAAA,YAAsB,OAAA;AAAA,cA8CnE,kBAAA,EAAoB,UAAA"}
@@ -1,6 +1,8 @@
1
1
  import { debug } from "../lib/debug.js";
2
2
  import { localApiGet } from "../lib/http.js";
3
3
  import { getRequestOrigin } from "./proxy.js";
4
+ import { TtlCache } from "../lib/ttl-cache.js";
5
+ import { getRouteCacheTtl } from "./route-proxy.js";
4
6
  import { asEquatable, defaultLocale, defaultMarket } from "@websolutespa/bom-core";
5
7
  import { NextResponse } from "next/server";
6
8
  //#region src/proxy/route-auto-detection.ts
@@ -46,6 +48,20 @@ function isValidDetectedRoute(value) {
46
48
  }
47
49
  return !decoded.split(/[/?#]/).some((segment) => segment === "." || segment === "..") && !decoded.includes("\\");
48
50
  }
51
+ const ROOT_ROUTES_CACHE_MAX = 100;
52
+ const globalForRootRoutes = globalThis;
53
+ const rootRoutesCache = globalForRootRoutes._bomRootRoutesCache ??= new TtlCache(ROOT_ROUTES_CACHE_MAX);
54
+ /** Drops cached root routes for this instance, e.g. from a test. */
55
+ function clearRootRoutesCache() {
56
+ rootRoutesCache.clear();
57
+ }
58
+ /** Root routes per origin, cached for `BOM_ROUTE_CACHE_TTL` seconds like the route proxy. */
59
+ async function getRootRoutes(origin) {
60
+ const load = () => localApiGet("/-route?where[isRoot][equals]=true", {}, void 0, origin);
61
+ const ttl = getRouteCacheTtl();
62
+ if (!ttl) return load();
63
+ return rootRoutesCache.getOrSet(origin, () => ttl, load);
64
+ }
49
65
  async function detectCountry(request, defaultMarket) {
50
66
  let ip = request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip");
51
67
  if (ip) ip = ip.split(",")[0].trim();
@@ -76,10 +92,10 @@ const routeAutoDetection = async ({ request }) => {
76
92
  const url = request.nextUrl;
77
93
  const origin = getRequestOrigin(request);
78
94
  if (url.pathname === "/") {
79
- const cookie = request.cookies.get("detectedRoute");
80
- if (isValidDetectedRoute(cookie?.value)) return createDetectedRouteResponse(request, origin, cookie.value);
81
- const rootRoutes = await localApiGet("/-route?where[isRoot][equals]=true", {}, void 0, origin);
95
+ const rootRoutes = await getRootRoutes(origin);
82
96
  if (rootRoutes.find((x) => x.id === "/")) return;
97
+ const cookie = request.cookies.get("detectedRoute");
98
+ if (isValidDetectedRoute(cookie?.value) && rootRoutes.some((x) => x.id === cookie.value)) return createDetectedRouteResponse(request, origin, cookie.value);
83
99
  const markets = await localApiGet("/market?pagination=false", {}, void 0, origin);
84
100
  const market = markets.find((x) => x.isDefault) || markets.find((x) => x.id === defaultMarket) || markets[0];
85
101
  const detectedCountry = await detectCountry(request, market.id);
@@ -119,6 +135,6 @@ function createDetectedRouteResponse(request, origin, redirectUrl) {
119
135
  return response;
120
136
  }
121
137
  //#endregion
122
- export { detectCountry, detectLocale, isValidDetectedRoute, routeAutoDetection };
138
+ export { clearRootRoutesCache, detectCountry, detectLocale, isValidDetectedRoute, routeAutoDetection };
123
139
 
124
140
  //# sourceMappingURL=route-auto-detection.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"route-auto-detection.js","names":[],"sources":["../../src/proxy/route-auto-detection.ts"],"sourcesContent":["import { asEquatable, defaultLocale, defaultMarket, IMarket, IRoute } from '@websolutespa/bom-core';\nimport { NextRequest, NextResponse } from 'next/server';\nimport { debug } from '../lib/debug';\nimport { localApiGet } from '../lib/http';\nimport { getRequestOrigin, Middleware, MiddlewareOptions } from './proxy';\n\nexport async function detectLocale(request: NextRequest, defaultLocale?: string) {\n const acceptLanguage = request.headers.get('accept-language')?.split(',')[0];\n const detectedLocale =\n request.cookies.get('NEXT_LOCALE')?.value ||\n acceptLanguage ||\n defaultLocale ||\n process.env.DEFAULT_LOCALE;\n return detectedLocale as string;\n}\n\nconst GEOIP_TIMEOUT = 2000;\nconst GEOIP_CACHE_TTL = 60 * 60 * 1000;\nconst GEOIP_CACHE_MAX = 1000;\n\ntype GeoIpCacheEntry = { country: string; expires: number };\nconst globalForGeoIp = globalThis as typeof globalThis & {\n _bomGeoIpCache?: Map<string, GeoIpCacheEntry>;\n};\n// Country lookups are external calls; cache them per IP so repeat visitors\n// and crawlers do not hit the GeoIP service on every request to `/`.\nconst geoIpCache = (globalForGeoIp._bomGeoIpCache ??= new Map<string, GeoIpCacheEntry>());\n\nfunction getCachedCountry(ip: string): string | undefined {\n const entry = geoIpCache.get(ip);\n if (!entry) {\n return undefined;\n }\n if (entry.expires < Date.now()) {\n geoIpCache.delete(ip);\n return undefined;\n }\n return entry.country;\n}\n\nfunction setCachedCountry(ip: string, country: string) {\n if (geoIpCache.size >= GEOIP_CACHE_MAX) {\n // Maps iterate in insertion order, so the first key is the oldest entry.\n const oldest = geoIpCache.keys().next().value;\n if (oldest !== undefined) {\n geoIpCache.delete(oldest);\n }\n }\n geoIpCache.set(ip, { country, expires: Date.now() + GEOIP_CACHE_TTL });\n}\n\n/**\n * A relative, same-origin path previously set by this middleware. Anything\n * else (absolute or protocol-relative URLs) is ignored to avoid open redirects.\n */\nexport function isValidDetectedRoute(value?: string): value is string {\n if (\n !value ||\n !value.startsWith('/') ||\n value.startsWith('//') ||\n value === '/' ||\n value.includes('\\\\')\n ) {\n return false;\n }\n // dot segments (also percent-encoded) would resolve to a different path on redirect\n let decoded: string;\n try {\n decoded = decodeURIComponent(value);\n } catch {\n return false;\n }\n return (\n !decoded.split(/[/?#]/).some((segment) => segment === '.' || segment === '..') &&\n !decoded.includes('\\\\')\n );\n}\n\nexport async function detectCountry(request: NextRequest, defaultMarket?: string) {\n let ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip');\n if (ip) {\n ip = ip.split(',')[0]!.trim();\n }\n const isValidIp = ip?.match(/^(\\d+?)\\.(\\d+?)\\.(\\d+?)\\.(\\d+?)$/);\n const cachedCountry = isValidIp && ip ? getCachedCountry(ip) : undefined;\n if (cachedCountry !== undefined) {\n return cachedCountry || defaultMarket || process.env.DEFAULT_MARKET;\n }\n let detectedCountry = '';\n try {\n const token = process.env.IPINFO_TOKEN;\n if (token) {\n const url = isValidIp\n ? `https://api.ipinfo.io/lite/${ip}/country_code?token=${token}`\n : `https://api.ipinfo.io/lite/me/country_code?token=${token}`;\n const response = await fetch(url, { signal: AbortSignal.timeout(GEOIP_TIMEOUT) });\n if (response.ok) {\n const data = await response.text();\n detectedCountry = data.toLowerCase();\n }\n } else {\n const url = `https://geoip.websolute.it/Ip2Location/get_info.aspx?ipaddress=${isValidIp ? ip : ''}`;\n const response = await fetch(url, { signal: AbortSignal.timeout(GEOIP_TIMEOUT) });\n if (response.ok) {\n const xml = await response.text();\n detectedCountry = (\n (xml.split('<CountryCode><![CDATA[')[1] || '').split(']]></CountryCode>')[0] || ''\n )\n .replace('-', '')\n .toLowerCase();\n // console.log('detectedCountry', detectedCountry);\n }\n }\n // console.log('routeInterceptor.detectCountry', detectedCountry);\n if (isValidIp && ip) {\n setCachedCountry(ip, detectedCountry);\n }\n return detectedCountry || defaultMarket || process.env.DEFAULT_MARKET;\n } catch (error) {\n console.warn('routeInterceptor.detectCountry.error', error);\n }\n return (defaultMarket || process.env.DEFAULT_MARKET) as string;\n}\n\nexport const routeAutoDetection: Middleware = async ({ request }: MiddlewareOptions) => {\n let redirectUrl: string | undefined = undefined;\n const url = request.nextUrl;\n const origin = getRequestOrigin(request);\n if (url.pathname === '/') {\n const cookie = request.cookies.get('detectedRoute');\n if (isValidDetectedRoute(cookie?.value)) {\n // The cookie is only set after a successful detection, so trust it and\n // skip the route, market and GeoIP lookups entirely.\n return createDetectedRouteResponse(request, origin, cookie.value);\n }\n // console.log('routeInterceptor.routeAutoDetection', url.pathname);\n const rootRoutes: IRoute[] = await localApiGet(\n '/-route?where[isRoot][equals]=true',\n {},\n undefined,\n origin\n );\n // console.log('routeInterceptor.routeAutoDetection.rootRoutes', rootRoutes);\n const defaultRoute = rootRoutes.find((x) => x.id === '/');\n // console.log('routeInterceptor.routeAutoDetection.defaultRoute', defaultRoute);\n if (defaultRoute) {\n return;\n }\n const markets: IMarket[] = await localApiGet('/market?pagination=false', {}, undefined, origin);\n // console.log('routeInterceptor.routeAutoDetection.markets', markets);\n const market =\n markets.find((x) => x.isDefault) || markets.find((x) => x.id === defaultMarket) || markets[0];\n // console.log('routeInterceptor.routeAutoDetection.market', market);\n const detectedCountry = await detectCountry(request, market.id);\n // console.log('routeInterceptor.routeAutoDetection.detectedCountry', detectedCountry);\n const detectedMarket = detectedCountry\n ? markets\n .filter((x) => Array.isArray(x.countries))\n .find((x) => {\n const countries: string[] = (x.countries || []).map((x) =>\n typeof x === 'string' ? x : (x.id as string)\n );\n return countries.includes(detectedCountry);\n }) || markets.find((x) => !Array.isArray(x.countries))\n : undefined;\n // console.log('routeInterceptor.routeAutoDetection.detectedMarket', detectedMarket);\n let detectedMarketRoutes = rootRoutes.filter((x) => x.market === detectedMarket?.id);\n if (detectedMarketRoutes.length === 0) {\n detectedMarketRoutes = rootRoutes.filter((x) => x.market === market.id);\n }\n // console.log('routeInterceptor.routeAutoDetection.detectedMarketRoutes', detectedMarketRoutes);\n const defaultMarketLocale = market.defaultLanguage\n ? ((typeof market.defaultLanguage === 'string'\n ? market.defaultLanguage\n : market.defaultLanguage.id) as string)\n : defaultLocale;\n // console.log('routeInterceptor.routeAutoDetection.defaultMarketLocale', defaultMarketLocale);\n const detectedLocale = await detectLocale(request, defaultMarketLocale);\n // console.log('routeInterceptor.routeAutoDetection.detectedLocale', detectedLocale);\n const detectedLocaleRoutes = detectedMarketRoutes.filter((x) => x.locale === detectedLocale);\n const detectedRoute =\n detectedLocaleRoutes.length > 0\n ? detectedLocaleRoutes[0]!\n : detectedMarketRoutes.find((x) => {\n const market = markets.find((m) => m.id === x.market)!;\n const marketLocale = market.defaultLanguage\n ? asEquatable(market.defaultLanguage as string)\n : defaultMarketLocale;\n return x.locale === marketLocale;\n })!;\n // console.log('routeInterceptor.routeAutoDetection.detectedRoute', detectedRoute);\n if (detectedRoute && detectedRoute.id !== url.pathname) {\n debug(\n 'routeInterceptor.routeAutoDetection',\n detectedLocale,\n detectedCountry,\n detectedRoute.id\n );\n redirectUrl = detectedRoute.id;\n }\n // console.log('routeInterceptor.routeAutoDetection', locale, detectedCountry, rootRoutes);\n }\n if (redirectUrl) {\n return createDetectedRouteResponse(request, origin, redirectUrl);\n }\n};\n\nfunction createDetectedRouteResponse(request: NextRequest, origin: string, redirectUrl: string) {\n const resolvedUrl = new URL(redirectUrl, origin).href;\n const search = request.nextUrl.search;\n const response = NextResponse.redirect(resolvedUrl + search, { status: 307 });\n response.cookies.set({\n expires: new Date(Date.now() + 1 * 24 * 60 * 60 * 1000),\n httpOnly: true,\n name: 'detectedRoute',\n path: '/',\n sameSite: 'lax',\n secure: true,\n value: redirectUrl,\n });\n return response;\n}\n"],"mappings":";;;;;;AAMA,eAAsB,aAAa,SAAsB,eAAwB;CAC/E,MAAM,iBAAiB,QAAQ,QAAQ,IAAI,kBAAkB,EAAE,MAAM,IAAI,CAAC;AAM1E,QAJE,QAAQ,QAAQ,IAAI,cAAc,EAAE,SACpC,kBACA,iBACA,QAAQ,IAAI;;AAIhB,MAAM,gBAAgB;AACtB,MAAM,kBAAkB,OAAU;AAClC,MAAM,kBAAkB;AAGxB,MAAM,iBAAiB;AAKvB,MAAM,aAAc,eAAe,mCAAmB,IAAI,KAA8B;AAExF,SAAS,iBAAiB,IAAgC;CAC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IAAI,KAAK,KAAK,KAAK,GAAG,OAAc,KAAK,IAAK;EACvD,UAAU;EACV,MAAM;EACN,MAAM;EACN,UAAU;EACV,QAAQ;EACR,OAAO;EACR,CAAC;AACF,QAAO"}
1
+ {"version":3,"file":"route-auto-detection.js","names":[],"sources":["../../src/proxy/route-auto-detection.ts"],"sourcesContent":["import { asEquatable, defaultLocale, defaultMarket, IMarket, IRoute } from '@websolutespa/bom-core';\r\nimport { NextRequest, NextResponse } from 'next/server';\r\nimport { debug } from '../lib/debug';\r\nimport { localApiGet } from '../lib/http';\r\nimport { TtlCache } from '../lib/ttl-cache';\r\nimport { getRequestOrigin, Middleware, MiddlewareOptions } from './proxy';\r\nimport { getRouteCacheTtl } from './route-proxy';\r\n\r\nexport async function detectLocale(request: NextRequest, defaultLocale?: string) {\r\n const acceptLanguage = request.headers.get('accept-language')?.split(',')[0];\r\n const detectedLocale =\r\n request.cookies.get('NEXT_LOCALE')?.value ||\r\n acceptLanguage ||\r\n defaultLocale ||\r\n process.env.DEFAULT_LOCALE;\r\n return detectedLocale as string;\r\n}\r\n\r\nconst GEOIP_TIMEOUT = 2000;\r\nconst GEOIP_CACHE_TTL = 60 * 60 * 1000;\r\nconst GEOIP_CACHE_MAX = 1000;\r\n\r\ntype GeoIpCacheEntry = { country: string; expires: number };\r\nconst globalForGeoIp = globalThis as typeof globalThis & {\r\n _bomGeoIpCache?: Map<string, GeoIpCacheEntry>;\r\n};\r\n// Country lookups are external calls; cache them per IP so repeat visitors\r\n// and crawlers do not hit the GeoIP service on every request to `/`.\r\nconst geoIpCache = (globalForGeoIp._bomGeoIpCache ??= new Map<string, GeoIpCacheEntry>());\r\n\r\nfunction getCachedCountry(ip: string): string | undefined {\r\n const entry = geoIpCache.get(ip);\r\n if (!entry) {\r\n return undefined;\r\n }\r\n if (entry.expires < Date.now()) {\r\n geoIpCache.delete(ip);\r\n return undefined;\r\n }\r\n return entry.country;\r\n}\r\n\r\nfunction setCachedCountry(ip: string, country: string) {\r\n if (geoIpCache.size >= GEOIP_CACHE_MAX) {\r\n // Maps iterate in insertion order, so the first key is the oldest entry.\r\n const oldest = geoIpCache.keys().next().value;\r\n if (oldest !== undefined) {\r\n geoIpCache.delete(oldest);\r\n }\r\n }\r\n geoIpCache.set(ip, { country, expires: Date.now() + GEOIP_CACHE_TTL });\r\n}\r\n\r\n/**\r\n * A relative, same-origin path previously set by this middleware. Anything\r\n * else (absolute or protocol-relative URLs) is ignored to avoid open redirects.\r\n */\r\nexport function isValidDetectedRoute(value?: string): value is string {\r\n if (\r\n !value ||\r\n !value.startsWith('/') ||\r\n value.startsWith('//') ||\r\n value === '/' ||\r\n value.includes('\\\\')\r\n ) {\r\n return false;\r\n }\r\n // dot segments (also percent-encoded) would resolve to a different path on redirect\r\n let decoded: string;\r\n try {\r\n decoded = decodeURIComponent(value);\r\n } catch {\r\n return false;\r\n }\r\n return (\r\n !decoded.split(/[/?#]/).some((segment) => segment === '.' || segment === '..') &&\r\n !decoded.includes('\\\\')\r\n );\r\n}\r\n\r\nconst ROOT_ROUTES_CACHE_MAX = 100;\r\nconst globalForRootRoutes = globalThis as typeof globalThis & {\r\n _bomRootRoutesCache?: TtlCache<IRoute[]>;\r\n};\r\nconst rootRoutesCache = (globalForRootRoutes._bomRootRoutesCache ??= new TtlCache<IRoute[]>(\r\n ROOT_ROUTES_CACHE_MAX\r\n));\r\n\r\n/** Drops cached root routes for this instance, e.g. from a test. */\r\nexport function clearRootRoutesCache() {\r\n rootRoutesCache.clear();\r\n}\r\n\r\n/** Root routes per origin, cached for `BOM_ROUTE_CACHE_TTL` seconds like the route proxy. */\r\nasync function getRootRoutes(origin: string): Promise<IRoute[]> {\r\n const load = () =>\r\n localApiGet<IRoute[]>('/-route?where[isRoot][equals]=true', {}, undefined, origin);\r\n const ttl = getRouteCacheTtl();\r\n if (!ttl) {\r\n return load();\r\n }\r\n return rootRoutesCache.getOrSet(origin, () => ttl, load);\r\n}\r\n\r\nexport async function detectCountry(request: NextRequest, defaultMarket?: string) {\r\n let ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip');\r\n if (ip) {\r\n ip = ip.split(',')[0]!.trim();\r\n }\r\n const isValidIp = ip?.match(/^(\\d+?)\\.(\\d+?)\\.(\\d+?)\\.(\\d+?)$/);\r\n const cachedCountry = isValidIp && ip ? getCachedCountry(ip) : undefined;\r\n if (cachedCountry !== undefined) {\r\n return cachedCountry || defaultMarket || process.env.DEFAULT_MARKET;\r\n }\r\n let detectedCountry = '';\r\n try {\r\n const token = process.env.IPINFO_TOKEN;\r\n if (token) {\r\n const url = isValidIp\r\n ? `https://api.ipinfo.io/lite/${ip}/country_code?token=${token}`\r\n : `https://api.ipinfo.io/lite/me/country_code?token=${token}`;\r\n const response = await fetch(url, { signal: AbortSignal.timeout(GEOIP_TIMEOUT) });\r\n if (response.ok) {\r\n const data = await response.text();\r\n detectedCountry = data.toLowerCase();\r\n }\r\n } else {\r\n const url = `https://geoip.websolute.it/Ip2Location/get_info.aspx?ipaddress=${isValidIp ? ip : ''}`;\r\n const response = await fetch(url, { signal: AbortSignal.timeout(GEOIP_TIMEOUT) });\r\n if (response.ok) {\r\n const xml = await response.text();\r\n detectedCountry = (\r\n (xml.split('<CountryCode><![CDATA[')[1] || '').split(']]></CountryCode>')[0] || ''\r\n )\r\n .replace('-', '')\r\n .toLowerCase();\r\n // console.log('detectedCountry', detectedCountry);\r\n }\r\n }\r\n // console.log('routeInterceptor.detectCountry', detectedCountry);\r\n if (isValidIp && ip) {\r\n setCachedCountry(ip, detectedCountry);\r\n }\r\n return detectedCountry || defaultMarket || process.env.DEFAULT_MARKET;\r\n } catch (error) {\r\n console.warn('routeInterceptor.detectCountry.error', error);\r\n }\r\n return (defaultMarket || process.env.DEFAULT_MARKET) as string;\r\n}\r\n\r\nexport const routeAutoDetection: Middleware = async ({ request }: MiddlewareOptions) => {\r\n let redirectUrl: string | undefined = undefined;\r\n const url = request.nextUrl;\r\n const origin = getRequestOrigin(request);\r\n if (url.pathname === '/') {\r\n // console.log('routeInterceptor.routeAutoDetection', url.pathname);\r\n const rootRoutes = await getRootRoutes(origin);\r\n // console.log('routeInterceptor.routeAutoDetection.rootRoutes', rootRoutes);\r\n const defaultRoute = rootRoutes.find((x) => x.id === '/');\r\n // console.log('routeInterceptor.routeAutoDetection.defaultRoute', defaultRoute);\r\n if (defaultRoute) {\r\n return;\r\n }\r\n const cookie = request.cookies.get('detectedRoute');\r\n if (\r\n isValidDetectedRoute(cookie?.value) &&\r\n rootRoutes.some((x) => x.id === cookie.value)\r\n ) {\r\n // A cookie naming a current root route skips the market and GeoIP\r\n // lookups; a stale one (e.g. a removed market) runs detection again,\r\n // which overwrites it.\r\n return createDetectedRouteResponse(request, origin, cookie.value);\r\n }\r\n const markets: IMarket[] = await localApiGet('/market?pagination=false', {}, undefined, origin);\r\n // console.log('routeInterceptor.routeAutoDetection.markets', markets);\r\n const market =\r\n markets.find((x) => x.isDefault) || markets.find((x) => x.id === defaultMarket) || markets[0];\r\n // console.log('routeInterceptor.routeAutoDetection.market', market);\r\n const detectedCountry = await detectCountry(request, market.id);\r\n // console.log('routeInterceptor.routeAutoDetection.detectedCountry', detectedCountry);\r\n const detectedMarket = detectedCountry\r\n ? markets\r\n .filter((x) => Array.isArray(x.countries))\r\n .find((x) => {\r\n const countries: string[] = (x.countries || []).map((x) =>\r\n typeof x === 'string' ? x : (x.id as string)\r\n );\r\n return countries.includes(detectedCountry);\r\n }) || markets.find((x) => !Array.isArray(x.countries))\r\n : undefined;\r\n // console.log('routeInterceptor.routeAutoDetection.detectedMarket', detectedMarket);\r\n let detectedMarketRoutes = rootRoutes.filter((x) => x.market === detectedMarket?.id);\r\n if (detectedMarketRoutes.length === 0) {\r\n detectedMarketRoutes = rootRoutes.filter((x) => x.market === market.id);\r\n }\r\n // console.log('routeInterceptor.routeAutoDetection.detectedMarketRoutes', detectedMarketRoutes);\r\n const defaultMarketLocale = market.defaultLanguage\r\n ? ((typeof market.defaultLanguage === 'string'\r\n ? market.defaultLanguage\r\n : market.defaultLanguage.id) as string)\r\n : defaultLocale;\r\n // console.log('routeInterceptor.routeAutoDetection.defaultMarketLocale', defaultMarketLocale);\r\n const detectedLocale = await detectLocale(request, defaultMarketLocale);\r\n // console.log('routeInterceptor.routeAutoDetection.detectedLocale', detectedLocale);\r\n const detectedLocaleRoutes = detectedMarketRoutes.filter((x) => x.locale === detectedLocale);\r\n const detectedRoute =\r\n detectedLocaleRoutes.length > 0\r\n ? detectedLocaleRoutes[0]!\r\n : detectedMarketRoutes.find((x) => {\r\n const market = markets.find((m) => m.id === x.market)!;\r\n const marketLocale = market.defaultLanguage\r\n ? asEquatable(market.defaultLanguage as string)\r\n : defaultMarketLocale;\r\n return x.locale === marketLocale;\r\n })!;\r\n // console.log('routeInterceptor.routeAutoDetection.detectedRoute', detectedRoute);\r\n if (detectedRoute && detectedRoute.id !== url.pathname) {\r\n debug(\r\n 'routeInterceptor.routeAutoDetection',\r\n detectedLocale,\r\n detectedCountry,\r\n detectedRoute.id\r\n );\r\n redirectUrl = detectedRoute.id;\r\n }\r\n // console.log('routeInterceptor.routeAutoDetection', locale, detectedCountry, rootRoutes);\r\n }\r\n if (redirectUrl) {\r\n return createDetectedRouteResponse(request, origin, redirectUrl);\r\n }\r\n};\r\n\r\nfunction createDetectedRouteResponse(request: NextRequest, origin: string, redirectUrl: string) {\r\n const resolvedUrl = new URL(redirectUrl, origin).href;\r\n const search = request.nextUrl.search;\r\n const response = NextResponse.redirect(resolvedUrl + search, { status: 307 });\r\n response.cookies.set({\r\n expires: new Date(Date.now() + 1 * 24 * 60 * 60 * 1000),\r\n httpOnly: true,\r\n name: 'detectedRoute',\r\n path: '/',\r\n sameSite: 'lax',\r\n secure: true,\r\n value: redirectUrl,\r\n });\r\n return response;\r\n}\r\n"],"mappings":";;;;;;;;AAQA,eAAsB,aAAa,SAAsB,eAAwB;CAC/E,MAAM,iBAAiB,QAAQ,QAAQ,IAAI,kBAAkB,EAAE,MAAM,IAAI,CAAC;AAM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AM,gBACJ,qBAAqB,SAAS,IAC1B,qBAAqB,KACrB,qBAAqB,MAAM,MAAM;GAC/B,MAAM,SAAS,QAAQ,MAAM,MAAM,EAAE,OAAO,EAAE,OAAO;GACrD,MAAM,eAAe,OAAO,kBACxB,YAAY,OAAO,gBAA0B,GAC7C;AACJ,UAAO,EAAE,WAAW;IACpB;AAER,MAAI,iBAAiB,cAAc,OAAO,IAAI,UAAU;AACtD,SACE,uCACA,gBACA,iBACA,cAAc,GACf;AACD,iBAAc,cAAc;;;AAIhC,KAAI,YACF,QAAO,4BAA4B,SAAS,QAAQ,YAAY;;AAIpE,SAAS,4BAA4B,SAAsB,QAAgB,aAAqB;CAC9F,MAAM,cAAc,IAAI,IAAI,aAAa,OAAO,CAAC;CACjD,MAAM,SAAS,QAAQ,QAAQ;CAC/B,MAAM,WAAW,aAAa,SAAS,cAAc,QAAQ,EAAE,QAAQ,KAAK,CAAC;AAC7E,UAAS,QAAQ,IAAI;EACnB,SAAS,IAAI,KAAK,KAAK,KAAK,GAAG,OAAc,KAAK,IAAK;EACvD,UAAU;EACV,MAAM;EACN,MAAM;EACN,UAAU;EACV,QAAQ;EACR,OAAO;EACR,CAAC;AACF,QAAO"}
@@ -29,8 +29,9 @@ type RouteResolverResponse = {
29
29
  */
30
30
  declare function createRouteProxy(...middlewares: RouteMiddleware[]): Middleware;
31
31
  declare function getRouteResolverPath(pathname: string, href: string, hrefBeforeRedirect?: string | null): string;
32
+ declare function getRouteCacheTtl(): number;
32
33
  /** Drops cached route resolutions for this instance, e.g. from a test or webhook. */
33
34
  declare function clearRouteProxyCache(): void;
34
35
  //#endregion
35
- export { Proxy, ResolvedRoute, RouteInterceptorProxy, RouteMiddleware, RouteMiddlewareOptions, RouteResolverResponse, clearRouteProxyCache, createRouteProxy, getRouteResolverPath };
36
+ export { Proxy, ResolvedRoute, RouteInterceptorProxy, RouteMiddleware, RouteMiddlewareOptions, RouteResolverResponse, clearRouteProxyCache, createRouteProxy, getRouteCacheTtl, getRouteResolverPath };
36
37
  //# sourceMappingURL=route-proxy.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"route-proxy.d.ts","names":[],"sources":["../../src/proxy/route-proxy.ts"],"mappings":";;;;;KAUY,KAAA,IAAS,OAAA,EAAS,WAAA,EAAa,IAAA,EAAM,cAAA,KAAmB,OAAA,CAAQ,oBAAA;AAAA,KAEhE,sBAAA;EACV,OAAA,EAAS,WAAA;EACT,IAAA,EAAM,cAAA;EACN,KAAA,EAAO,MAAA;EACP,QAAA;AAAA;AAAA,KAEU,eAAA,IACV,KAAA,EAAO,sBAAA,KACJ,oBAAA,GAAuB,OAAA,CAAQ,oBAAA;AAAA,KAExB,qBAAA,IACV,KAAA,EAAO,MAAA,EACP,OAAA,EAAS,WAAA,EACT,IAAA,EAAM,cAAA,KACH,OAAA,CAAQ,oBAAA;AAAA,KAED,aAAA,GAAgB,MAAA;EAAW,KAAA;AAAA;AAAA,KAC3B,qBAAA;EACV,MAAA,GAAS,MAAA;EACT,KAAA,GAAQ,aAAA;AAAA;;;AAnBV;;;;;;iBA8BgB,gBAAA,CAAA,GAAoB,WAAA,EAAa,eAAA,KAAoB,UAAA;AAAA,iBA8JrD,oBAAA,CACd,QAAA,UACA,IAAA,UACA,kBAAA;;iBA2Bc,oBAAA,CAAA"}
1
+ {"version":3,"file":"route-proxy.d.ts","names":[],"sources":["../../src/proxy/route-proxy.ts"],"mappings":";;;;;KAUY,KAAA,IAAS,OAAA,EAAS,WAAA,EAAa,IAAA,EAAM,cAAA,KAAmB,OAAA,CAAQ,oBAAA;AAAA,KAEhE,sBAAA;EACV,OAAA,EAAS,WAAA;EACT,IAAA,EAAM,cAAA;EACN,KAAA,EAAO,MAAA;EACP,QAAA;AAAA;AAAA,KAEU,eAAA,IACV,KAAA,EAAO,sBAAA,KACJ,oBAAA,GAAuB,OAAA,CAAQ,oBAAA;AAAA,KAExB,qBAAA,IACV,KAAA,EAAO,MAAA,EACP,OAAA,EAAS,WAAA,EACT,IAAA,EAAM,cAAA,KACH,OAAA,CAAQ,oBAAA;AAAA,KAED,aAAA,GAAgB,MAAA;EAAW,KAAA;AAAA;AAAA,KAC3B,qBAAA;EACV,MAAA,GAAS,MAAA;EACT,KAAA,GAAQ,aAAA;AAAA;;;AAnBV;;;;;;iBA8BgB,gBAAA,CAAA,GAAoB,WAAA,EAAa,eAAA,KAAoB,UAAA;AAAA,iBAkKrD,oBAAA,CACd,QAAA,UACA,IAAA,UACA,kBAAA;AAAA,iBAqBc,gBAAA,CAAA;;iBAMA,oBAAA,CAAA"}
@@ -24,9 +24,12 @@ function createRouteProxy(...middlewares) {
24
24
  const headers = new Headers(request.headers);
25
25
  headers.set("x-pathname", pathname);
26
26
  try {
27
- if (request.cookies.has("__prerender_bypass")) return;
27
+ const draftMode = request.cookies.has("__prerender_bypass");
28
28
  const outcome = await resolveRoute(getRouteResolverPath(url.pathname, url.href, hrefBeforeRedirect), origin);
29
- if (!outcome.ok) throw outcome;
29
+ if (!outcome.ok) {
30
+ if (draftMode && outcome.status >= 400 && outcome.status < 500) return;
31
+ throw outcome;
32
+ }
30
33
  const resolution = outcome.data;
31
34
  const route = resolution?.route;
32
35
  if (route) {
@@ -53,7 +56,8 @@ function createRouteProxy(...middlewares) {
53
56
  headers.set("x-id", String(route.page));
54
57
  headers.set("x-forwarded-pathname", nextUrl.pathname);
55
58
  return NextResponse.rewrite(nextUrl, { request: { headers } });
56
- } else {
59
+ } else if (draftMode) return;
60
+ else {
57
61
  const parentRoute = resolution?.parent;
58
62
  const market = parentRoute?.market || defaultMarket;
59
63
  const locale = parentRoute?.locale || defaultLocale;
@@ -174,6 +178,6 @@ function getRedirectUrl(error, request) {
174
178
  }
175
179
  }
176
180
  //#endregion
177
- export { clearRouteProxyCache, createRouteProxy, getRouteResolverPath };
181
+ export { clearRouteProxyCache, createRouteProxy, getRouteCacheTtl, getRouteResolverPath };
178
182
 
179
183
  //# sourceMappingURL=route-proxy.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"route-proxy.js","names":[],"sources":["../../src/proxy/route-proxy.ts"],"sourcesContent":["import { defaultLocale, defaultMarket, IRoute } from '@websolutespa/bom-core';\nimport { NextFetchEvent, NextRequest, NextResponse } from 'next/server';\nimport { debug } from '../lib/debug';\nimport { localApiGet } from '../lib/http';\nimport { TtlCache } from '../lib/ttl-cache';\nimport { getRouteTemplate } from '../lib/route';\nimport { getHrefBeforeRedirect, getNextUrl } from '../server/utils';\nimport type { NextMiddlewareResult } from './proxy';\nimport { getRequestOrigin, Middleware, MiddlewareOptions } from './proxy';\n\nexport type Proxy = (request: NextRequest, next: NextFetchEvent) => Promise<NextMiddlewareResult>;\n\nexport type RouteMiddlewareOptions = {\n request: NextRequest;\n next: NextFetchEvent;\n route: IRoute;\n disabled?: boolean;\n};\nexport type RouteMiddleware = (\n props: RouteMiddlewareOptions\n) => NextMiddlewareResult | Promise<NextMiddlewareResult>;\n\nexport type RouteInterceptorProxy = (\n route: IRoute,\n request: NextRequest,\n next: NextFetchEvent\n) => Promise<NextMiddlewareResult>;\n\nexport type ResolvedRoute = IRoute & { splat?: string };\nexport type RouteResolverResponse = {\n parent?: IRoute;\n route?: ResolvedRoute;\n};\n\n/**\n * Resolves a public request to a CMS route, then rewrites it to the internal\n * Next.js page while preserving the original browser URL.\n *\n * The resolver call is deliberately made to this request's public origin so it\n * works behind reverse proxies and deployment hosts. A rewrite keeps routing\n * server-side, avoiding an extra browser round trip that a redirect would add.\n */\nexport function createRouteProxy(...middlewares: RouteMiddleware[]): Middleware {\n return async function ({ request, next }: MiddlewareOptions) {\n const url = request.nextUrl;\n const origin = getRequestOrigin(request);\n const hrefBeforeRedirect = getHrefBeforeRedirect(request);\n const { pathname } = url;\n const headers = new Headers(request.headers);\n headers.set('x-pathname', pathname);\n try {\n const draftMode = request.cookies.has('__prerender_bypass');\n if (draftMode) {\n // Draft requests need Payload's native preview behavior, so skip the\n // route lookup and its database/cache work entirely.\n return;\n }\n // Resolve once before invoking route middleware. This shares the route\n // snapshot result across all middleware rather than letting each one\n // repeat the internal API request.\n const outcome = await resolveRoute(\n getRouteResolverPath(url.pathname, url.href, hrefBeforeRedirect),\n origin\n );\n if (!outcome.ok) {\n throw outcome;\n }\n const resolution = outcome.data;\n const route = resolution?.route;\n // console.log('createRouteProxy', route);\n if (route) {\n let middlewareResponse,\n i = 0;\n // Run in registration order and stop at the first response. Later\n // middleware cannot affect a committed rewrite, so short-circuiting\n // avoids unnecessary authentication or policy checks.\n while (i < middlewares.length && !middlewareResponse) {\n const middleware = middlewares[i] as RouteMiddleware;\n // console.log('createRouteProxy.middlewares', middlewares.length, typeof middleware === 'function');\n if (typeof middleware === 'function') {\n middlewareResponse = await middleware({ request, next, route });\n if (middlewareResponse) {\n return middlewareResponse;\n }\n }\n i++;\n }\n const nextUrl = getNextUrl(request, route);\n debug('createRouteProxy.Found', pathname, '>', nextUrl.pathname);\n // Pass the resolved route as request headers so the internal page can\n // render without performing a second route-resolution lookup.\n headers.set('x-market', route.market);\n headers.set('x-locale', route.locale);\n headers.set('x-schema', route.schema);\n const template = getRouteTemplate(route);\n if (template) {\n headers.set('x-template', template);\n }\n headers.set('x-id', String(route.page));\n headers.set('x-forwarded-pathname', nextUrl.pathname);\n const response = NextResponse.rewrite(nextUrl, {\n request: {\n headers,\n },\n });\n // const response = NextResponse.redirect(url);\n return response;\n } else {\n const parentRoute = resolution?.parent;\n // The resolver returns the nearest parent even when no leaf route\n // matches. Reusing its market and locale makes the 404 contextual\n // without another lookup; defaults cover an entirely unknown path.\n const market = parentRoute?.market || defaultMarket;\n const locale = parentRoute?.locale || defaultLocale;\n const nextUrl = request.nextUrl.clone();\n nextUrl.pathname = `/${market}/${locale}/404`;\n headers.set('x-market', market);\n headers.set('x-locale', locale);\n headers.set('x-schema', 'not_found');\n headers.set('x-id', '404');\n headers.set('x-forwarded-pathname', nextUrl.pathname);\n debug('createRouteProxy.NotFound', pathname);\n const response = NextResponse.rewrite(nextUrl, {\n request: {\n headers,\n },\n });\n return response;\n }\n } catch (error: unknown) {\n const routeError =\n error && typeof error === 'object'\n ? (error as { status?: number; statusText?: string; url?: string })\n : {};\n\n if (routeError.status && routeError.status >= 300 && routeError.status < 400) {\n debug('createRouteProxy.3xx', url.pathname, routeError.status, routeError.statusText);\n // The handler has already validated the redirect target. Redirect the\n // browser once so its address bar changes, rather than rewriting a\n // route whose canonical URL is different.\n const redirectUrl = getRedirectUrl(error, request);\n const status = REDIRECT_STATUSES.includes(routeError.status) ? routeError.status : 307;\n return NextResponse.redirect(redirectUrl, status);\n } else if (routeError.status && routeError.status >= 400 && routeError.status < 500) {\n if (routeError.status === 404) {\n /**\n * A resolver miss is not necessarily a CMS 404: it may be a Next.js\n * file-system route such as an API endpoint or static asset. Letting\n * Next continue avoids routing those requests through a fallback\n * render and keeps their fast native handling intact.\n */\n // console.log('createRouteProxy.route.notfound', url.pathname);\n return;\n }\n debug('createRouteProxy.4xx', url.pathname, routeError.status, routeError.statusText);\n // Other client errors are terminal CMS outcomes, so render the shared\n // 404 page directly instead of issuing a separate client navigation.\n const market = defaultMarket;\n const locale = defaultLocale;\n const nextUrl = request.nextUrl.clone();\n nextUrl.pathname = `/${market}/${locale}/404`;\n headers.set('x-market', market);\n headers.set('x-locale', locale);\n headers.set('x-schema', 'not_found');\n headers.set('x-id', '404');\n headers.set('x-forwarded-pathname', nextUrl.pathname);\n debug('createRouteProxy.NotFound', pathname);\n const response = NextResponse.rewrite(nextUrl, {\n request: {\n headers,\n },\n });\n return response;\n /*\n const response = NextResponse.next({\n status: routeError.status,\n statusText: routeError.statusText,\n headers,\n });\n return response;\n */\n }\n // A resolver failure must not block unrelated Next.js routes. Returning\n // undefined delegates to the normal pipeline and avoids masking a\n // transient upstream failure with a misleading synthetic response.\n console.warn(\n 'createRouteProxy.error.5xx',\n url.pathname,\n routeError.url,\n routeError.status,\n routeError.statusText || error\n );\n return;\n }\n };\n}\n\n// Statuses accepted by NextResponse.redirect; CMS values outside this set fall back to 307.\nconst REDIRECT_STATUSES = [301, 302, 303, 307, 308];\n\nexport function getRouteResolverPath(\n pathname: string,\n href: string,\n hrefBeforeRedirect?: string | null\n): string {\n const params = new URLSearchParams({ pathname, href });\n if (hrefBeforeRedirect) {\n params.set('hrefBeforeRedirect', hrefBeforeRedirect);\n }\n return `/-route?${params.toString()}`;\n}\n\ntype RouteOutcome =\n | { ok: true; data: RouteResolverResponse }\n | { ok: false; status: number; statusText: string; body?: { redirectUrl?: string } };\n\nconst ROUTE_CACHE_MAX = 5000;\nconst globalForRoute = globalThis as typeof globalThis & {\n _bomRouteProxyCache?: TtlCache<RouteOutcome>;\n};\nconst routeCache = (globalForRoute._bomRouteProxyCache ??= new TtlCache<RouteOutcome>(\n ROUTE_CACHE_MAX\n));\n\nfunction getRouteCacheTtl(): number {\n const value = Number(process.env.BOM_ROUTE_CACHE_TTL ?? 30);\n return Number.isFinite(value) && value > 0 ? value * 1000 : 0;\n}\n\n/** Drops cached route resolutions for this instance, e.g. from a test or webhook. */\nexport function clearRouteProxyCache() {\n routeCache.clear();\n}\n\n/**\n * Resolves through the internal `/-route` endpoint, caching found routes,\n * redirects and misses per instance for `BOM_ROUTE_CACHE_TTL` seconds\n * (default 30, `0` disables). Misses use a shorter TTL so new CMS pages show\n * up quickly; server errors and network failures are never cached.\n */\nasync function resolveRoute(path: string, origin: string): Promise<RouteOutcome> {\n const ttl = getRouteCacheTtl();\n const load = async (): Promise<RouteOutcome> => {\n try {\n const data = await localApiGet<RouteResolverResponse>(path, {}, undefined, origin);\n return { ok: true, data };\n } catch (error: unknown) {\n if (error instanceof Response && error.status < 500) {\n let body: { redirectUrl?: string } | undefined;\n if (error.status >= 300 && error.status < 400) {\n body = await error.json().catch(() => undefined);\n }\n return { ok: false, status: error.status, statusText: error.statusText, body };\n }\n throw error;\n }\n };\n if (!ttl) {\n return load();\n }\n return routeCache.getOrSet(\n path,\n (outcome) => (outcome.ok && outcome.data?.route ? ttl : Math.min(ttl, 10000)),\n load\n );\n}\n\n/**\n * Reads the redirect target from the resolver's 3xx JSON body. Falls back to\n * the site root only when the body is missing or malformed.\n */\nfunction getRedirectUrl(error: unknown, request: NextRequest): URL {\n const fallback = request.nextUrl.clone();\n fallback.pathname = '/';\n fallback.search = '';\n const redirectUrl = (error as { body?: { redirectUrl?: string } })?.body?.redirectUrl;\n try {\n return redirectUrl ? new URL(redirectUrl, request.nextUrl.origin) : fallback;\n } catch {\n return fallback;\n }\n}\n\n/*\n\nexport const routeInterceptor: Proxy = async function (request: NextRequest, next: NextFetchEvent) {\n const middleware = await createRouteProxy();\n return await middleware(request, next);\n};\n\n*/\n"],"mappings":";;;;;;;;;;;;;;;;;AA0CA,SAAgB,iBAAiB,GAAG,aAA4C;AAC9E,QAAO,eAAgB,EAAE,SAAS,QAA2B;EAC3D,MAAM,MAAM,QAAQ;EACpB,MAAM,SAAS,iBAAiB,QAAQ;EACxC,MAAM,qBAAqB,sBAAsB,QAAQ;EACzD,MAAM,EAAE,aAAa;EACrB,MAAM,UAAU,IAAI,QAAQ,QAAQ,QAAQ;AAC5C,UAAQ,IAAI,cAAc,SAAS;AACnC,MAAI;AAEF,OADkB,QAAQ,QAAQ,IAAI,qBAAqB,CAIzD;GAKF,MAAM,UAAU,MAAM,aACpB,qBAAqB,IAAI,UAAU,IAAI,MAAM,mBAAmB,EAChE,OACD;AACD,OAAI,CAAC,QAAQ,GACX,OAAM;GAER,MAAM,aAAa,QAAQ;GAC3B,MAAM,QAAQ,YAAY;AAE1B,OAAI,OAAO;IACT,IAAI,oBACF,IAAI;AAIN,WAAO,IAAI,YAAY,UAAU,CAAC,oBAAoB;KACpD,MAAM,aAAa,YAAY;AAE/B,SAAI,OAAO,eAAe,YAAY;AACpC,2BAAqB,MAAM,WAAW;OAAE;OAAS;OAAM;OAAO,CAAC;AAC/D,UAAI,mBACF,QAAO;;AAGX;;IAEF,MAAM,UAAU,WAAW,SAAS,MAAM;AAC1C,UAAM,0BAA0B,UAAU,KAAK,QAAQ,SAAS;AAGhE,YAAQ,IAAI,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,IAAI;AACJ,QAAI,MAAM,UAAU,OAAO,MAAM,SAAS,IACxC,QAAO,MAAM,MAAM,MAAM,CAAC,YAAY,KAAA,EAAU;AAElD,WAAO;KAAE,IAAI;KAAO,QAAQ,MAAM;KAAQ,YAAY,MAAM;KAAY;KAAM;;AAEhF,SAAM;;;AAGV,KAAI,CAAC,IACH,QAAO,MAAM;AAEf,QAAO,WAAW,SAChB,OACC,YAAa,QAAQ,MAAM,QAAQ,MAAM,QAAQ,MAAM,KAAK,IAAI,KAAK,IAAM,EAC5E,KACD;;;;;;AAOH,SAAS,eAAe,OAAgB,SAA2B;CACjE,MAAM,WAAW,QAAQ,QAAQ,OAAO;AACxC,UAAS,WAAW;AACpB,UAAS,SAAS;CAClB,MAAM,cAAe,OAA+C,MAAM;AAC1E,KAAI;AACF,SAAO,cAAc,IAAI,IAAI,aAAa,QAAQ,QAAQ,OAAO,GAAG;SAC9D;AACN,SAAO"}
1
+ {"version":3,"file":"route-proxy.js","names":[],"sources":["../../src/proxy/route-proxy.ts"],"sourcesContent":["import { defaultLocale, defaultMarket, IRoute } from '@websolutespa/bom-core';\r\nimport { NextFetchEvent, NextRequest, NextResponse } from 'next/server';\r\nimport { debug } from '../lib/debug';\r\nimport { localApiGet } from '../lib/http';\r\nimport { TtlCache } from '../lib/ttl-cache';\r\nimport { getRouteTemplate } from '../lib/route';\r\nimport { getHrefBeforeRedirect, getNextUrl } from '../server/utils';\r\nimport type { NextMiddlewareResult } from './proxy';\r\nimport { getRequestOrigin, Middleware, MiddlewareOptions } from './proxy';\r\n\r\nexport type Proxy = (request: NextRequest, next: NextFetchEvent) => Promise<NextMiddlewareResult>;\r\n\r\nexport type RouteMiddlewareOptions = {\r\n request: NextRequest;\r\n next: NextFetchEvent;\r\n route: IRoute;\r\n disabled?: boolean;\r\n};\r\nexport type RouteMiddleware = (\r\n props: RouteMiddlewareOptions\r\n) => NextMiddlewareResult | Promise<NextMiddlewareResult>;\r\n\r\nexport type RouteInterceptorProxy = (\r\n route: IRoute,\r\n request: NextRequest,\r\n next: NextFetchEvent\r\n) => Promise<NextMiddlewareResult>;\r\n\r\nexport type ResolvedRoute = IRoute & { splat?: string };\r\nexport type RouteResolverResponse = {\r\n parent?: IRoute;\r\n route?: ResolvedRoute;\r\n};\r\n\r\n/**\r\n * Resolves a public request to a CMS route, then rewrites it to the internal\r\n * Next.js page while preserving the original browser URL.\r\n *\r\n * The resolver call is deliberately made to this request's public origin so it\r\n * works behind reverse proxies and deployment hosts. A rewrite keeps routing\r\n * server-side, avoiding an extra browser round trip that a redirect would add.\r\n */\r\nexport function createRouteProxy(...middlewares: RouteMiddleware[]): Middleware {\r\n return async function ({ request, next }: MiddlewareOptions) {\r\n const url = request.nextUrl;\r\n const origin = getRequestOrigin(request);\r\n const hrefBeforeRedirect = getHrefBeforeRedirect(request);\r\n const { pathname } = url;\r\n const headers = new Headers(request.headers);\r\n headers.set('x-pathname', pathname);\r\n try {\r\n // In Draft Mode public URLs are still resolved (editors see drafts on\r\n // them), but an unresolved path is left to Next: the preview handler\r\n // redirects to the internal `/{market}/{locale}/{template}/{id}` path,\r\n // which the resolver does not know.\r\n const draftMode = request.cookies.has('__prerender_bypass');\r\n // Resolve once before invoking route middleware. This shares the route\r\n // snapshot result across all middleware rather than letting each one\r\n // repeat the internal API request.\r\n const outcome = await resolveRoute(\r\n getRouteResolverPath(url.pathname, url.href, hrefBeforeRedirect),\r\n origin\r\n );\r\n if (!outcome.ok) {\r\n if (draftMode && outcome.status >= 400 && outcome.status < 500) {\r\n return;\r\n }\r\n throw outcome;\r\n }\r\n const resolution = outcome.data;\r\n const route = resolution?.route;\r\n // console.log('createRouteProxy', route);\r\n if (route) {\r\n let middlewareResponse,\r\n i = 0;\r\n // Run in registration order and stop at the first response. Later\r\n // middleware cannot affect a committed rewrite, so short-circuiting\r\n // avoids unnecessary authentication or policy checks.\r\n while (i < middlewares.length && !middlewareResponse) {\r\n const middleware = middlewares[i] as RouteMiddleware;\r\n // console.log('createRouteProxy.middlewares', middlewares.length, typeof middleware === 'function');\r\n if (typeof middleware === 'function') {\r\n middlewareResponse = await middleware({ request, next, route });\r\n if (middlewareResponse) {\r\n return middlewareResponse;\r\n }\r\n }\r\n i++;\r\n }\r\n const nextUrl = getNextUrl(request, route);\r\n debug('createRouteProxy.Found', pathname, '>', nextUrl.pathname);\r\n // Pass the resolved route as request headers so the internal page can\r\n // render without performing a second route-resolution lookup.\r\n headers.set('x-market', route.market);\r\n headers.set('x-locale', route.locale);\r\n headers.set('x-schema', route.schema);\r\n const template = getRouteTemplate(route);\r\n if (template) {\r\n headers.set('x-template', template);\r\n }\r\n headers.set('x-id', String(route.page));\r\n headers.set('x-forwarded-pathname', nextUrl.pathname);\r\n const response = NextResponse.rewrite(nextUrl, {\r\n request: {\r\n headers,\r\n },\r\n });\r\n // const response = NextResponse.redirect(url);\r\n return response;\r\n } else if (draftMode) {\r\n return;\r\n } else {\r\n const parentRoute = resolution?.parent;\r\n // The resolver returns the nearest parent even when no leaf route\r\n // matches. Reusing its market and locale makes the 404 contextual\r\n // without another lookup; defaults cover an entirely unknown path.\r\n const market = parentRoute?.market || defaultMarket;\r\n const locale = parentRoute?.locale || defaultLocale;\r\n const nextUrl = request.nextUrl.clone();\r\n nextUrl.pathname = `/${market}/${locale}/404`;\r\n headers.set('x-market', market);\r\n headers.set('x-locale', locale);\r\n headers.set('x-schema', 'not_found');\r\n headers.set('x-id', '404');\r\n headers.set('x-forwarded-pathname', nextUrl.pathname);\r\n debug('createRouteProxy.NotFound', pathname);\r\n const response = NextResponse.rewrite(nextUrl, {\r\n request: {\r\n headers,\r\n },\r\n });\r\n return response;\r\n }\r\n } catch (error: unknown) {\r\n const routeError =\r\n error && typeof error === 'object'\r\n ? (error as { status?: number; statusText?: string; url?: string })\r\n : {};\r\n\r\n if (routeError.status && routeError.status >= 300 && routeError.status < 400) {\r\n debug('createRouteProxy.3xx', url.pathname, routeError.status, routeError.statusText);\r\n // The handler has already validated the redirect target. Redirect the\r\n // browser once so its address bar changes, rather than rewriting a\r\n // route whose canonical URL is different.\r\n const redirectUrl = getRedirectUrl(error, request);\r\n const status = REDIRECT_STATUSES.includes(routeError.status) ? routeError.status : 307;\r\n return NextResponse.redirect(redirectUrl, status);\r\n } else if (routeError.status && routeError.status >= 400 && routeError.status < 500) {\r\n if (routeError.status === 404) {\r\n /**\r\n * A resolver miss is not necessarily a CMS 404: it may be a Next.js\r\n * file-system route such as an API endpoint or static asset. Letting\r\n * Next continue avoids routing those requests through a fallback\r\n * render and keeps their fast native handling intact.\r\n */\r\n // console.log('createRouteProxy.route.notfound', url.pathname);\r\n return;\r\n }\r\n debug('createRouteProxy.4xx', url.pathname, routeError.status, routeError.statusText);\r\n // Other client errors are terminal CMS outcomes, so render the shared\r\n // 404 page directly instead of issuing a separate client navigation.\r\n const market = defaultMarket;\r\n const locale = defaultLocale;\r\n const nextUrl = request.nextUrl.clone();\r\n nextUrl.pathname = `/${market}/${locale}/404`;\r\n headers.set('x-market', market);\r\n headers.set('x-locale', locale);\r\n headers.set('x-schema', 'not_found');\r\n headers.set('x-id', '404');\r\n headers.set('x-forwarded-pathname', nextUrl.pathname);\r\n debug('createRouteProxy.NotFound', pathname);\r\n const response = NextResponse.rewrite(nextUrl, {\r\n request: {\r\n headers,\r\n },\r\n });\r\n return response;\r\n /*\r\n const response = NextResponse.next({\r\n status: routeError.status,\r\n statusText: routeError.statusText,\r\n headers,\r\n });\r\n return response;\r\n */\r\n }\r\n // A resolver failure must not block unrelated Next.js routes. Returning\r\n // undefined delegates to the normal pipeline and avoids masking a\r\n // transient upstream failure with a misleading synthetic response.\r\n console.warn(\r\n 'createRouteProxy.error.5xx',\r\n url.pathname,\r\n routeError.url,\r\n routeError.status,\r\n routeError.statusText || error\r\n );\r\n return;\r\n }\r\n };\r\n}\r\n\r\n// Statuses accepted by NextResponse.redirect; CMS values outside this set fall back to 307.\r\nconst REDIRECT_STATUSES = [301, 302, 303, 307, 308];\r\n\r\nexport function getRouteResolverPath(\r\n pathname: string,\r\n href: string,\r\n hrefBeforeRedirect?: string | null\r\n): string {\r\n const params = new URLSearchParams({ pathname, href });\r\n if (hrefBeforeRedirect) {\r\n params.set('hrefBeforeRedirect', hrefBeforeRedirect);\r\n }\r\n return `/-route?${params.toString()}`;\r\n}\r\n\r\ntype RouteOutcome =\r\n | { ok: true; data: RouteResolverResponse }\r\n | { ok: false; status: number; statusText: string; body?: { redirectUrl?: string } };\r\n\r\nconst ROUTE_CACHE_MAX = 5000;\r\nconst globalForRoute = globalThis as typeof globalThis & {\r\n _bomRouteProxyCache?: TtlCache<RouteOutcome>;\r\n};\r\nconst routeCache = (globalForRoute._bomRouteProxyCache ??= new TtlCache<RouteOutcome>(\r\n ROUTE_CACHE_MAX\r\n));\r\n\r\nexport function getRouteCacheTtl(): number {\r\n const value = Number(process.env.BOM_ROUTE_CACHE_TTL ?? 30);\r\n return Number.isFinite(value) && value > 0 ? value * 1000 : 0;\r\n}\r\n\r\n/** Drops cached route resolutions for this instance, e.g. from a test or webhook. */\r\nexport function clearRouteProxyCache() {\r\n routeCache.clear();\r\n}\r\n\r\n/**\r\n * Resolves through the internal `/-route` endpoint, caching found routes,\r\n * redirects and misses per instance for `BOM_ROUTE_CACHE_TTL` seconds\r\n * (default 30, `0` disables). Misses use a shorter TTL so new CMS pages show\r\n * up quickly; server errors and network failures are never cached.\r\n */\r\nasync function resolveRoute(path: string, origin: string): Promise<RouteOutcome> {\r\n const ttl = getRouteCacheTtl();\r\n const load = async (): Promise<RouteOutcome> => {\r\n try {\r\n const data = await localApiGet<RouteResolverResponse>(path, {}, undefined, origin);\r\n return { ok: true, data };\r\n } catch (error: unknown) {\r\n if (error instanceof Response && error.status < 500) {\r\n let body: { redirectUrl?: string } | undefined;\r\n if (error.status >= 300 && error.status < 400) {\r\n body = await error.json().catch(() => undefined);\r\n }\r\n return { ok: false, status: error.status, statusText: error.statusText, body };\r\n }\r\n throw error;\r\n }\r\n };\r\n if (!ttl) {\r\n return load();\r\n }\r\n return routeCache.getOrSet(\r\n path,\r\n (outcome) => (outcome.ok && outcome.data?.route ? ttl : Math.min(ttl, 10000)),\r\n load\r\n );\r\n}\r\n\r\n/**\r\n * Reads the redirect target from the resolver's 3xx JSON body. Falls back to\r\n * the site root only when the body is missing or malformed.\r\n */\r\nfunction getRedirectUrl(error: unknown, request: NextRequest): URL {\r\n const fallback = request.nextUrl.clone();\r\n fallback.pathname = '/';\r\n fallback.search = '';\r\n const redirectUrl = (error as { body?: { redirectUrl?: string } })?.body?.redirectUrl;\r\n try {\r\n return redirectUrl ? new URL(redirectUrl, request.nextUrl.origin) : fallback;\r\n } catch {\r\n return fallback;\r\n }\r\n}\r\n\r\n/*\r\n\r\nexport const routeInterceptor: Proxy = async function (request: NextRequest, next: NextFetchEvent) {\r\n const middleware = await createRouteProxy();\r\n return await middleware(request, next);\r\n};\r\n\r\n*/\r\n"],"mappings":";;;;;;;;;;;;;;;;;AA0CA,SAAgB,iBAAiB,GAAG,aAA4C;AAC9E,QAAO,eAAgB,EAAE,SAAS,QAA2B;EAC3D,MAAM,MAAM,QAAQ;EACpB,MAAM,SAAS,iBAAiB,QAAQ;EACxC,MAAM,qBAAqB,sBAAsB,QAAQ;EACzD,MAAM,EAAE,aAAa;EACrB,MAAM,UAAU,IAAI,QAAQ,QAAQ,QAAQ;AAC5C,UAAQ,IAAI,cAAc,SAAS;AACnC,MAAI;GAKF,MAAM,YAAY,QAAQ,QAAQ,IAAI,qBAAqB;GAI3D,MAAM,UAAU,MAAM,aACpB,qBAAqB,IAAI,UAAU,IAAI,MAAM,mBAAmB,EAChE,OACD;AACD,OAAI,CAAC,QAAQ,IAAI;AACf,QAAI,aAAa,QAAQ,UAAU,OAAO,QAAQ,SAAS,IACzD;AAEF,UAAM;;GAER,MAAM,aAAa,QAAQ;GAC3B,MAAM,QAAQ,YAAY;AAE1B,OAAI,OAAO;IACT,IAAI,oBACF,IAAI;AAIN,WAAO,IAAI,YAAY,UAAU,CAAC,oBAAoB;KACpD,MA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AASpB,eAAe,aAAa,MAAc,QAAuC;CAC/E,MAAM,MAAM,kBAAkB;CAC9B,MAAM,OAAO,YAAmC;AAC9C,MAAI;AAEF,UAAO;IAAE,IAAI;IAAM,MADN,MAAM,YAAmC,MAAM,EAAE,EAAE,KAAA,GAAW,OAAO;IACzD;WAClB,OAAgB;AACvB,OAAI,iBAAiB,YAAY,MAAM,SAAS,KAAK;IACnD,IAAI;AACJ,QAAI,MAAM,UAAU,OAAO,MAAM,SAAS,IACxC,QAAO,MAAM,MAAM,MAAM,CAAC,YAAY,KAAA,EAAU;AAElD,WAAO;KAAE,IAAI;KAAO,QAAQ,MAAM;KAAQ,YAAY,MAAM;KAAY;KAAM;;AAEhF,SAAM;;;AAGV,KAAI,CAAC,IACH,QAAO,MAAM;AAEf,QAAO,WAAW,SAChB,OACC,YAAa,QAAQ,MAAM,QAAQ,MAAM,QAAQ,MAAM,KAAK,IAAI,KAAK,IAAM,EAC5E,KACD;;;;;;AAOH,SAAS,eAAe,OAAgB,SAA2B;CACjE,MAAM,WAAW,QAAQ,QAAQ,OAAO;AACxC,UAAS,WAAW;AACpB,UAAS,SAAS;CAClB,MAAM,cAAe,OAA+C,MAAM;AAC1E,KAAI;AACF,SAAO,cAAc,IAAI,IAAI,aAAa,QAAQ,QAAQ,OAAO,GAAG;SAC9D;AACN,SAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"auth.handler.d.ts","names":[],"sources":["../../../src/server/handlers/auth.handler.ts"],"mappings":";;;;iBAMgB,gBAAA,CAAiB,MAAA,EAAQ,OAAA,CAAQ,eAAA,KACxB,OAAA,EAAS,WAAA,KAAW,OAAA,CAAA,QAAA"}
1
+ {"version":3,"file":"auth.handler.d.ts","names":[],"sources":["../../../src/server/handlers/auth.handler.ts"],"mappings":";;;;iBAOgB,gBAAA,CAAiB,MAAA,EAAQ,OAAA,CAAQ,eAAA,KACxB,OAAA,EAAS,WAAA,KAAW,OAAA,CAAA,QAAA"}
@@ -1,3 +1,4 @@
1
+ import { isEndUser } from "../../lib/user.js";
1
2
  import { getPayload } from "../mixer.js";
2
3
  import { getHandlerErrorResponse } from "./error-response.js";
3
4
  import { headers } from "next/headers";
@@ -9,11 +10,12 @@ function getAuthMeHandler(config) {
9
10
  config,
10
11
  headers: await headers()
11
12
  });
12
- if ((user?.roles || []).includes("user") && "firstName" in user) {
13
- const { firstName, lastName } = user;
13
+ const candidate = user;
14
+ if (isEndUser(candidate)) {
15
+ const { id, email, firstName, lastName } = candidate;
14
16
  return Response.json({
15
- id: user.id,
16
- email: user.email,
17
+ id,
18
+ email,
17
19
  firstName,
18
20
  lastName
19
21
  }, { status: 200 });
@@ -1 +1 @@
1
- {"version":3,"file":"auth.handler.js","names":["getHeaders"],"sources":["../../../src/server/handlers/auth.handler.ts"],"sourcesContent":["import { headers as getHeaders } from 'next/headers';\nimport { NextRequest } from 'next/server';\nimport { SanitizedConfig } from 'payload';\nimport { getPayload } from '../mixer';\nimport { getHandlerErrorResponse } from './error-response';\n\nexport function getAuthMeHandler(config: Promise<SanitizedConfig>) {\n return async function (request: NextRequest) {\n try {\n const headers = await getHeaders();\n const { user } = await getPayload({ config, headers });\n const roles = user?.roles || [];\n if (roles.includes('user') && 'firstName' in user) {\n // end users (roles user) carry their names\n const { firstName, lastName } = user as { firstName?: string; lastName?: string };\n return Response.json(\n {\n id: user.id,\n email: user.email,\n firstName,\n lastName,\n },\n { status: 200 }\n );\n }\n return Response.json(null, { status: 200 });\n } catch (error) {\n console.log('getAuthMeHandler.error', error);\n return getHandlerErrorResponse(error);\n }\n };\n}\n"],"mappings":";;;;AAMA,SAAgB,iBAAiB,QAAkC;AACjE,QAAO,eAAgB,SAAsB;AAC3C,MAAI;GAEF,MAAM,EAAE,SAAS,MAAM,WAAW;IAAE;IAAQ,SAD5B,MAAMA,SAAY;IACmB,CAAC;AAEtD,QADc,MAAM,SAAS,EAAE,EACrB,SAAS,OAAO,IAAI,eAAe,MAAM;IAEjD,MAAM,EAAE,WAAW,aAAa;AAChC,WAAO,SAAS,KACd;KACE,IAAI,KAAK;KACT,OAAO,KAAK;KACZ;KACA;KACD,EACD,EAAE,QAAQ,KAAK,CAChB;;AAEH,UAAO,SAAS,KAAK,MAAM,EAAE,QAAQ,KAAK,CAAC;WACpC,OAAO;AACd,WAAQ,IAAI,0BAA0B,MAAM;AAC5C,UAAO,wBAAwB,MAAM"}
1
+ {"version":3,"file":"auth.handler.js","names":["getHeaders"],"sources":["../../../src/server/handlers/auth.handler.ts"],"sourcesContent":["import { headers as getHeaders } from 'next/headers';\r\nimport { NextRequest } from 'next/server';\r\nimport { SanitizedConfig } from 'payload';\r\nimport { isEndUser } from '../../lib/user';\r\nimport { getPayload } from '../mixer';\r\nimport { getHandlerErrorResponse } from './error-response';\r\n\r\nexport function getAuthMeHandler(config: Promise<SanitizedConfig>) {\r\n return async function (request: NextRequest) {\r\n try {\r\n const headers = await getHeaders();\r\n const { user } = await getPayload({ config, headers });\r\n // a plain value (not `user`, typed as the back-office User): narrowing it would intersect User and EndUser\r\n const candidate: unknown = user;\r\n if (isEndUser(candidate)) {\r\n // end users carry their names\r\n const { id, email, firstName, lastName } = candidate as {\r\n id: string | number;\r\n email?: string;\r\n firstName?: string;\r\n lastName?: string;\r\n };\r\n return Response.json({ id, email, firstName, lastName }, { status: 200 });\r\n }\r\n return Response.json(null, { status: 200 });\r\n } catch (error) {\r\n console.log('getAuthMeHandler.error', error);\r\n return getHandlerErrorResponse(error);\r\n }\r\n };\r\n}\r\n"],"mappings":";;;;;AAOA,SAAgB,iBAAiB,QAAkC;AACjE,QAAO,eAAgB,SAAsB;AAC3C,MAAI;GAEF,MAAM,EAAE,SAAS,MAAM,WAAW;IAAE;IAAQ,SAD5B,MAAMA,SAAY;IACmB,CAAC;GAEtD,MAAM,YAAqB;AAC3B,OAAI,UAAU,UAAU,EAAE;IAExB,MAAM,EAAE,IAAI,OAAO,WAAW,aAAa;AAM3C,WAAO,SAAS,KAAK;KAAE;KAAI;KAAO;KAAW;KAAU,EAAE,EAAE,QAAQ,KAAK,CAAC;;AAE3E,UAAO,SAAS,KAAK,MAAM,EAAE,QAAQ,KAAK,CAAC;WACpC,OAAO;AACd,WAAQ,IAAI,0BAA0B,MAAM;AAC5C,UAAO,wBAAwB,MAAM"}
@@ -0,0 +1,37 @@
1
+ import { RedisLike } from "../cache-handler/redis.js";
2
+
3
+ //#region src/server/rate-limit.d.ts
4
+ /** The counter commands of a `redis` client the rate limiter uses (injectable for tests). */
5
+ type RedisCounter = RedisLike & {
6
+ incr(key: string): Promise<number>;
7
+ expire(key: string, seconds: number): Promise<unknown>;
8
+ };
9
+ type RateLimitOptions = {
10
+ /** namespace of the counters, for example the action name */prefix: string; /** requests allowed per window and key */
11
+ limit: number; /** window length in seconds */
12
+ windowSeconds: number; /** max keys of the in-memory fallback (oldest evicted first), default 10 000 */
13
+ maxMemoryKeys?: number; /** the Redis client, default the shared `REDIS_URL` client of the cache handler (memory when not ready) */
14
+ redis?: () => Promise<RedisCounter | undefined>; /** clock, for tests */
15
+ now?: () => number;
16
+ };
17
+ type RateLimitResult = {
18
+ allowed: boolean; /** requests left in the current window */
19
+ remaining: number; /** epoch ms when the current window ends */
20
+ reset: number;
21
+ backend: 'redis' | 'memory';
22
+ };
23
+ type RateLimiter = {
24
+ /** counts one request for `key` (for example the client IP) and tells whether it is allowed */hit(key: string): Promise<RateLimitResult>;
25
+ };
26
+ /**
27
+ * Fixed-window rate limiter for public endpoints (forms, actions).
28
+ *
29
+ * With `REDIS_URL` it counts in Redis (`<REDIS_PREFIX>:rate:<prefix>:<key>:<window>`, `INCR` + `EXPIRE`), so every
30
+ * instance of the site shares the limit: on serverless or behind a load balancer a per-process counter is not
31
+ * enough. While Redis is not configured or not ready it falls back to a bounded per-process map, which still stops a
32
+ * single client hammering one instance. A Redis error never rejects the request: it falls back to memory.
33
+ */
34
+ declare function createRateLimiter(options: RateLimitOptions): RateLimiter;
35
+ //#endregion
36
+ export { RateLimitOptions, RateLimitResult, RateLimiter, RedisCounter, createRateLimiter };
37
+ //# sourceMappingURL=rate-limit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit.d.ts","names":[],"sources":["../../src/server/rate-limit.ts"],"mappings":";;;;KAGY,YAAA,GAAe,SAAA;EACzB,IAAA,CAAK,GAAA,WAAc,OAAA;EACnB,MAAA,CAAO,GAAA,UAAa,OAAA,WAAkB,OAAA;AAAA;AAAA,KAG5B,gBAAA;EAJS,6DAMnB,MAAA,UAL6C;EAO7C,KAAA,UATyB;EAWzB,aAAA,UAVK;EAYL,aAAA,WAXA;EAaA,KAAA,SAAc,OAAA,CAAQ,YAAA,eAbF;EAepB,GAAA;AAAA;AAAA,KAGU,eAAA;EACV,OAAA,WAhB0B;EAkB1B,SAAA,UARqB;EAUrB,KAAA;EACA,OAAA;AAAA;AAAA,KAGU,WAAA;EAdV,+FAgBA,GAAA,CAAI,GAAA,WAAc,OAAA,CAAQ,eAAA;AAAA;;;;AAX5B;;;;;iBAsBgB,iBAAA,CAAkB,OAAA,EAAS,gBAAA,GAAmB,WAAA"}