@revenexx/cover 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/app/api/categories.ts +1 -0
  2. package/app/api/offers.ts +1 -0
  3. package/app/app.config.ts +13 -0
  4. package/app/components/OgImage/CoverPage.takumi.vue +37 -0
  5. package/app/components/RevenexxForm.vue +21 -6
  6. package/app/components/account/approvals/AccountPendingApprovals.vue +19 -1
  7. package/app/components/account/approvals/AccountPendingOrderDetail.vue +3 -0
  8. package/app/components/account/carts/AccountCartsTable.vue +11 -1
  9. package/app/components/account/orderlists/AccountOrderListDetail.vue +32 -3
  10. package/app/components/account/organization/AccountOrganization.vue +1 -1
  11. package/app/components/auth/AuthForgotPasswordPanel.vue +7 -2
  12. package/app/components/auth/AuthLoginPanel.vue +23 -8
  13. package/app/components/auth/AuthRegisterTeaser.vue +1 -1
  14. package/app/components/cart/position/CartPosition.vue +11 -4
  15. package/app/components/cart/quickadd/CartQuickAdd.vue +4 -2
  16. package/app/components/cart/recommend/CartRecommendCard.vue +1 -0
  17. package/app/components/cart/switcher/CartSwitcher.vue +1 -0
  18. package/app/components/cart/view/CartListHeader.vue +5 -0
  19. package/app/components/cart/view/CartSummaryPanel.vue +20 -8
  20. package/app/components/cart/view/CartView.vue +4 -2
  21. package/app/components/checkout/onepage/CheckoutGate.vue +4 -2
  22. package/app/components/checkout/onepage/CheckoutGuestDetailsSection.vue +2 -1
  23. package/app/components/checkout/onepage/CheckoutPaymentSection.vue +1 -1
  24. package/app/components/checkout/onepage/CheckoutSummarySection.vue +8 -0
  25. package/app/components/checkout/return/CheckoutPaymentReturn.vue +7 -0
  26. package/app/components/layout/footer/Footer.vue +21 -4
  27. package/app/components/layout/header/AppBar.vue +5 -2
  28. package/app/components/layout/header/LocaleSwitcher.vue +7 -9
  29. package/app/components/layout/header/MobileMenu.vue +4 -1
  30. package/app/components/product/detail/ProductDetailAddToCart.vue +17 -11
  31. package/app/components/product/detail/ProductDetailImageGallery.vue +101 -8
  32. package/app/components/product/detail/ProductDetailVariantRow.vue +84 -4
  33. package/app/components/product/detail/ProductDetailVariants.vue +75 -11
  34. package/app/components/product/detail/ProductDetailView.vue +64 -69
  35. package/app/components/punchout/action/PunchoutTransferAction.vue +4 -3
  36. package/app/composables/useAuthStore.ts +21 -4
  37. package/app/composables/useCategories.ts +24 -0
  38. package/app/composables/useCategoryAnswer.ts +30 -0
  39. package/app/composables/useCategorySeo.ts +62 -0
  40. package/app/composables/useDefaultUiLanguage.ts +14 -0
  41. package/app/composables/useOgImageReady.ts +16 -0
  42. package/app/composables/useProductAnswer.ts +121 -0
  43. package/app/composables/useProductLocales.ts +21 -10
  44. package/app/composables/useProductSeo.ts +145 -0
  45. package/app/composables/usePunchoutVisit.ts +36 -1
  46. package/app/composables/useRouteSubject.ts +23 -3
  47. package/app/composables/useSeoContext.ts +164 -0
  48. package/app/composables/useSeoHead.ts +189 -0
  49. package/app/composables/useSeoRules.ts +23 -0
  50. package/app/interfaces/punchout.ts +11 -0
  51. package/app/interfaces/seo.ts +48 -0
  52. package/app/layouts/default.vue +2 -8
  53. package/app/layouts/focus.vue +3 -1
  54. package/app/middleware/punchout-exits.global.ts +25 -0
  55. package/app/payments/psp/novalnet.ts +25 -3
  56. package/app/payments/psp/novalnetStyle.ts +186 -0
  57. package/app/plugins/punchout-links.client.ts +46 -0
  58. package/app/shared/categoryTree.ts +7 -0
  59. package/app/shared/locale.ts +8 -0
  60. package/app/shared/productLocales.ts +62 -1
  61. package/app/shared/punchoutExits.ts +156 -0
  62. package/app/shared/seoRules.ts +297 -0
  63. package/app/shared/structuredData.ts +104 -0
  64. package/i18n/locales/de/account.json +4 -0
  65. package/i18n/locales/de/common.json +6 -0
  66. package/i18n/locales/de/pages.json +109 -0
  67. package/i18n/locales/de/punchout.json +3 -0
  68. package/i18n/locales/en/account.json +4 -0
  69. package/i18n/locales/en/common.json +6 -0
  70. package/i18n/locales/en/pages.json +109 -0
  71. package/i18n/locales/en/punchout.json +3 -0
  72. package/nuxt.config.ts +140 -1
  73. package/package.json +10 -3
  74. package/server/api/auth/otp.post.ts +4 -8
  75. package/server/api/auth/otp.put.ts +20 -11
  76. package/server/api/categories/[slug]/exists.get.ts +28 -0
  77. package/server/api/offers/guest.get.ts +53 -0
  78. package/server/api/orders/index.post.ts +18 -11
  79. package/server/api/payment/methods.post.ts +2 -33
  80. package/server/api/product/[id]/locales.get.ts +9 -3
  81. package/server/data/product-detail.json +0 -20
  82. package/server/dev/errorHandler.ts +9 -5
  83. package/server/dev/typesense/autoSeed.ts +63 -0
  84. package/server/dev/typesense/seed.ts +4 -43
  85. package/server/dev/typesense/seedProducts.ts +87 -0
  86. package/server/interfaces/category.ts +5 -0
  87. package/server/interfaces/product.ts +13 -6
  88. package/server/interfaces/punchout.ts +20 -1
  89. package/server/middleware/missing-media.ts +2 -2
  90. package/server/middleware/punchout-exits.ts +45 -0
  91. package/server/middleware/punchout-visit-csp.ts +35 -0
  92. package/server/plugins/previewHostNoindex.ts +21 -0
  93. package/server/plugins/punchout-cookies.ts +48 -0
  94. package/server/plugins/seoSiteConfig.ts +62 -0
  95. package/server/routes/punchout/start.get.ts +7 -0
  96. package/server/routes/robots.txt.ts +21 -0
  97. package/server/services/ApiCategoryService.ts +6 -0
  98. package/server/services/ApiProductService.ts +2 -2
  99. package/server/services/LocalFileCategoryService.ts +6 -0
  100. package/server/utils/liveCatalog.ts +83 -18
  101. package/server/utils/livePrices.ts +12 -3
  102. package/server/utils/locale.ts +3 -8
  103. package/server/utils/offerService.ts +8 -3
  104. package/server/utils/paymentOptions.ts +49 -0
  105. package/server/utils/promotionsService.ts +25 -0
  106. package/server/utils/punchoutFrame.ts +131 -0
  107. package/server/utils/punchoutOrder.ts +40 -0
  108. package/server/utils/punchoutVisit.ts +41 -8
  109. package/server/utils/revenexxSdk.ts +7 -1
  110. package/server/utils/seoRequestHost.ts +21 -0
  111. package/server/utils/storefrontMessages.ts +5 -5
  112. package/server/utils/storefrontSeoRules.ts +298 -0
  113. package/server/middleware/punchout-hand-back-csp.ts +0 -17
@@ -0,0 +1,131 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type { PunchoutVisit } from "../interfaces/punchout";
4
+
5
+ /**
6
+ * A punchout visit inside the procurement system's iframe (RAD-226).
7
+ *
8
+ * A punchout visit usually runs inside the ERP or the trade software, often in
9
+ * an iframe. Two things stop the shop rendering there, and both are answered
10
+ * here for the visit and only for the visit:
11
+ *
12
+ * - **framing.** The edge answers `frame-ancestors 'self'` (and
13
+ * `X-Frame-Options: SAMEORIGIN`) unless the storefront sends a CSP of its
14
+ * own, which it then keeps — the same mechanism the hand-back page's
15
+ * `form-action` relies on (PE-994). A visit's pages therefore answer a CSP
16
+ * whose `frame-ancestors` names the parents the punchout ACCOUNT allows,
17
+ * from the claim. A browser that sees `frame-ancestors` ignores
18
+ * `X-Frame-Options`, so the edge's header needs no change.
19
+ * - **cookies.** Inside a third-party iframe a `SameSite=Lax` cookie is
20
+ * neither stored nor sent, so the buyer would be signed out on the first
21
+ * click. During a visit every cookie the shop sets is `SameSite=None;
22
+ * Secure`, and `Partitioned` when the visit is framed, so a browser that
23
+ * blocks third-party cookies still keeps them inside that one frame. A
24
+ * normal storefront session keeps `lax`.
25
+ *
26
+ * `Partitioned` only for a framed visit: a top-level visit's cookies would
27
+ * otherwise sit beside the buyer's ordinary, unpartitioned ones under the same
28
+ * names, and the shop would read whichever the browser sent first.
29
+ */
30
+
31
+ /**
32
+ * One origin as a CSP source: http(s), an optional `*.`, a port, nothing else.
33
+ * The claim already answers checked origins; this is the storefront's own
34
+ * check, because the value goes into a response header.
35
+ */
36
+ const FRAME_ORIGIN = /^https?:\/\/(?:\*\.)?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*(?::\d{1,5})?$/;
37
+
38
+ /** At most this many parents reach the header, whatever the claim said. */
39
+ const MAX_FRAME_ANCESTORS = 10;
40
+
41
+ /** The claim's `frame_ancestors`, as the visit keeps them: checked, once each. */
42
+ export function frameAncestorsOf(value: unknown): string[] {
43
+ if (!Array.isArray(value)) {
44
+ return [];
45
+ }
46
+ const origins: string[] = [];
47
+ for (const entry of value) {
48
+ const origin = typeof entry === "string" ? entry.trim().toLowerCase().replace(/\/+$/, "") : "";
49
+ if (FRAME_ORIGIN.test(origin) && !origins.includes(origin)) {
50
+ origins.push(origin);
51
+ }
52
+ }
53
+ return origins.slice(0, MAX_FRAME_ANCESTORS);
54
+ }
55
+
56
+ /**
57
+ * Whether this navigation is being loaded into a frame. `Sec-Fetch-Dest` is
58
+ * sent by every current browser on a navigation; a browser that sends none is
59
+ * read as top-level, which keeps its cookies unpartitioned.
60
+ */
61
+ export function isFramedNavigation(event: H3Event): boolean {
62
+ const dest = String(event.node.req.headers["sec-fetch-dest"] ?? "").toLowerCase();
63
+ return dest === "iframe" || dest === "frame";
64
+ }
65
+
66
+ /**
67
+ * The CSP a visit's pages answer: the edge's own default policy, with the
68
+ * account's parents added to `frame-ancestors` and — on the hand-back page
69
+ * only — the visit's return address added to `form-action`.
70
+ */
71
+ export function punchoutVisitCsp(visit: Pick<PunchoutVisit, "frameAncestors" | "handBackOrigin"> | null, handBackPage: boolean): string {
72
+ const formAction = handBackPage && visit?.handBackOrigin ? `form-action 'self' ${visit.handBackOrigin}` : "form-action 'self'";
73
+ const parents = frameAncestorsOf(visit?.frameAncestors ?? []);
74
+ const frameAncestors = ["frame-ancestors 'self'", ...parents].join(" ");
75
+ return `object-src 'none'; ${formAction}; ${frameAncestors}`;
76
+ }
77
+
78
+ /** How the visit's cookies are written. */
79
+ export interface PunchoutCookieMode {
80
+ readonly partitioned: boolean;
81
+ }
82
+
83
+ /**
84
+ * One `Set-Cookie` value as a visit writes it: `SameSite=None; Secure`, and
85
+ * `Partitioned` for a framed visit. Whatever `SameSite` the setter chose is
86
+ * replaced; everything else — expiry, path, `HttpOnly` — is kept.
87
+ */
88
+ export function punchoutCookie(setCookie: string, mode: PunchoutCookieMode): string {
89
+ const parts = setCookie.split(";").map(part => part.trim()).filter(Boolean);
90
+ const kept = parts.filter((part, index) => {
91
+ if (index === 0) {
92
+ return true;
93
+ }
94
+ const name = part.split("=")[0]!.trim().toLowerCase();
95
+ return name !== "samesite" && name !== "secure" && name !== "partitioned";
96
+ });
97
+ kept.push("Secure", "SameSite=None");
98
+ if (mode.partitioned) {
99
+ kept.push("Partitioned");
100
+ }
101
+ return kept.join("; ");
102
+ }
103
+
104
+ /** The same for a header value as Node holds it: one string or a list. */
105
+ export function punchoutCookies(value: number | string | readonly string[], mode: PunchoutCookieMode): number | string | string[] {
106
+ if (typeof value === "number") {
107
+ return value;
108
+ }
109
+ return Array.isArray(value)
110
+ ? value.map(cookie => punchoutCookie(String(cookie), mode))
111
+ : punchoutCookie(String(value), mode);
112
+ }
113
+
114
+ /**
115
+ * Whether a request belongs to a visit, for the cookie rule: the visit cookie
116
+ * is THERE — expired or not, because the request that drops an expired visit
117
+ * has to drop it with the attributes it was set with, or a partitioned cookie
118
+ * is not deleted. Answers the visit's mode, or null outside a visit.
119
+ */
120
+ export function punchoutCookieModeOf(rawVisitCookie: string | undefined): PunchoutCookieMode | null {
121
+ if (!rawVisitCookie) {
122
+ return null;
123
+ }
124
+ try {
125
+ const visit = JSON.parse(rawVisitCookie) as Partial<PunchoutVisit> | null;
126
+ return { partitioned: visit?.framed === true };
127
+ }
128
+ catch {
129
+ return { partitioned: false };
130
+ }
131
+ }
@@ -0,0 +1,40 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type { PunchoutVisit } from "../interfaces/punchout";
4
+ import { purchaseModeOf } from "../../app/shared/punchoutExits";
5
+
6
+ /**
7
+ * An order placed inside a punchout visit (RAD-226).
8
+ *
9
+ * The checkout is the ordinary one; two things are added for a visit whose
10
+ * purchase mode lets it order. The order says which visit it came from, so a
11
+ * punchout order is recognisable on its own (in analytics, in the Cockpit).
12
+ * And the punchout app is told the visit ended in an order — for `order`
13
+ * that closes the visit; for `order_and_transfer` the hand-back that follows
14
+ * is what closes it, and the punchout app requires the order for it.
15
+ */
16
+
17
+ /** What the order carries about the visit, under `metadata.punchout`. */
18
+ export function punchoutOrderMetadata(visit: PunchoutVisit): { punchout: { account_code: string | null; protocol: string; psid: string } } {
19
+ return { punchout: { account_code: visit.accountCode ?? null, protocol: visit.protocol, psid: visit.psid } };
20
+ }
21
+
22
+ /**
23
+ * After the order exists: mark the visit ordered and, for `order`, close it in
24
+ * the punchout app. Best-effort — the order is placed and the buyer charged,
25
+ * so a punchout app that does not answer is logged, not turned into a failed
26
+ * checkout; the punchout app also reads the order off the visit's cart by
27
+ * itself when the visit is next asked about.
28
+ */
29
+ export async function settlePunchoutOrder(event: H3Event, visit: PunchoutVisit): Promise<void> {
30
+ updatePunchoutVisit(event, { ordered: true });
31
+ if (purchaseModeOf(visit.purchaseMode) !== "order") {
32
+ return;
33
+ }
34
+ try {
35
+ await useRevenexxSdk().call("POST", `/v1/punchout/sessions/${encodeURIComponent(visit.psid)}/ordered`, { body: {} });
36
+ }
37
+ catch (err) {
38
+ getLogService().error("Punchout visit could not be closed as ordered", apiErrorContext(err));
39
+ }
40
+ }
@@ -4,6 +4,8 @@ import { deleteCookie, getCookie, setCookie } from "h3";
4
4
 
5
5
  import type { PunchoutVisitView } from "../../app/interfaces/punchout";
6
6
  import type { PunchoutVisit } from "../interfaces/punchout";
7
+ import { SESSION_COOKIE_NAME, sessionCookieOptions } from "./authCookie";
8
+ import { purchaseModeOf } from "../../app/shared/punchoutExits";
7
9
 
8
10
  /**
9
11
  * The storefront's own record of one punchout visit.
@@ -53,11 +55,23 @@ export function setPunchoutVisit(event: H3Event, visit: PunchoutVisit): void {
53
55
  * response from paths that have already answered.
54
56
  */
55
57
  export function readPunchoutVisit(event: H3Event, now: Date = new Date()): PunchoutVisit | null {
58
+ const visit = readPunchoutVisitRecord(event);
59
+ if (!visit || isLapsed(visit, now)) {
60
+ return null;
61
+ }
62
+ return visit;
63
+ }
64
+
65
+ /**
66
+ * The visit cookie as it was written, a lapsed visit included — for the one
67
+ * question that needs it: may this request still place the visit's order?
68
+ * An order created after the visit's expiry does not count for it (RAD-226).
69
+ */
70
+ export function readPunchoutVisitRecord(event: H3Event): PunchoutVisit | null {
56
71
  const raw = getCookie(event, PUNCHOUT_COOKIE_NAME);
57
72
  if (!raw) {
58
73
  return null;
59
74
  }
60
-
61
75
  let visit: PunchoutVisit;
62
76
  try {
63
77
  visit = JSON.parse(raw) as PunchoutVisit;
@@ -65,14 +79,20 @@ export function readPunchoutVisit(event: H3Event, now: Date = new Date()): Punch
65
79
  catch {
66
80
  return null;
67
81
  }
82
+ return visit?.psid && visit.protocol ? visit : null;
83
+ }
68
84
 
69
- if (!visit?.psid || !visit.protocol) {
70
- return null;
71
- }
72
- if (visit.expiresAt && new Date(visit.expiresAt).getTime() <= now.getTime()) {
73
- return null;
74
- }
75
- return visit;
85
+ /** Whether the visit has run out. */
86
+ export function isLapsed(visit: Pick<PunchoutVisit, "expiresAt">, now: Date = new Date()): boolean {
87
+ return Boolean(visit.expiresAt) && new Date(visit.expiresAt).getTime() <= now.getTime();
88
+ }
89
+
90
+ /**
91
+ * Whether the shop is in punchout mode for this visit: hiding and refusing
92
+ * every exit but the visit's own (RAD-226). A visit handed back is over.
93
+ */
94
+ export function isRestrictingVisit(visit: PunchoutVisit | null): visit is PunchoutVisit {
95
+ return Boolean(visit) && visit!.handedBack !== true;
76
96
  }
77
97
 
78
98
  /**
@@ -83,6 +103,15 @@ export function readPunchoutVisit(event: H3Event, now: Date = new Date()): Punch
83
103
  export function getPunchoutVisit(event: H3Event, now: Date = new Date()): PunchoutVisit | null {
84
104
  const visit = readPunchoutVisit(event, now);
85
105
  if (!visit && getCookie(event, PUNCHOUT_COOKIE_NAME)) {
106
+ // A visit that ran out ends together with the buyer's session, as a
107
+ // hand-back does (RAD-226): the shop session was the visit's, signed
108
+ // in by the claim, and must not outlive it on a machine the ERP
109
+ // handed over. Dropping the cookie signs the browser out; the platform
110
+ // session behind it runs out on its own.
111
+ const record = readPunchoutVisitRecord(event);
112
+ if (record && record.handedBack !== true && isLapsed(record, now)) {
113
+ deleteCookie(event, SESSION_COOKIE_NAME, sessionCookieOptions());
114
+ }
86
115
  clearPunchoutVisit(event);
87
116
  }
88
117
  return visit;
@@ -119,6 +148,8 @@ export function punchoutVisitView(visit: PunchoutVisit | null): PunchoutVisitVie
119
148
  cartId: null,
120
149
  expiresAt: null,
121
150
  handedBack: false,
151
+ purchaseMode: "transfer",
152
+ ordered: false,
122
153
  };
123
154
  }
124
155
  return {
@@ -130,5 +161,7 @@ export function punchoutVisitView(visit: PunchoutVisit | null): PunchoutVisitVie
130
161
  cartId: visit.cartId,
131
162
  expiresAt: visit.expiresAt,
132
163
  handedBack: visit.handedBack === true,
164
+ purchaseMode: purchaseModeOf(visit.purchaseMode),
165
+ ordered: visit.ordered === true,
133
166
  };
134
167
  }
@@ -54,6 +54,12 @@ export interface RevenexxSdkOptions {
54
54
  * apply no rule without it — the tenant key alone sees every record.
55
55
  */
56
56
  readonly principal?: string;
57
+ /**
58
+ * The channel, sent as `X-Revenexx-Channel`; the punchout visit's by
59
+ * default. An empty string sends none: a call made for nobody (the public
60
+ * price) must not be scoped to one buyer's punchout channel.
61
+ */
62
+ readonly channel?: string;
57
63
  }
58
64
 
59
65
  export interface RevenexxSdkCallOptions {
@@ -294,7 +300,7 @@ function activePrincipal(): string {
294
300
  export function useRevenexxSdk(options: RevenexxSdkOptions = {}): RevenexxSdk {
295
301
  const { tenant, apiKey, jwt, source } = resolveRevenexxCredentials();
296
302
  const market = activeMarket();
297
- const channel = activeChannel();
303
+ const channel = options.channel ?? activeChannel();
298
304
  const principal = options.principal ?? activePrincipal();
299
305
 
300
306
  // A client carrying a principal is ONE buyer's: cached, it would hand that
@@ -0,0 +1,21 @@
1
+ import type { H3Event } from "h3";
2
+ import { getRequestHost, getRequestProtocol } from "h3";
3
+
4
+ /**
5
+ * The host a request was made to, as the seo rules name it: no port, lower
6
+ * case. From `Host`, which the edge passes as the client asked for it
7
+ * (`proxy_set_header Host $host`); `X-Forwarded-Host` is not read, as a client
8
+ * could send any value in it.
9
+ */
10
+ export function seoRequestHost(event: H3Event): string {
11
+ return getRequestHost(event).replace(/:\d+$/, "").toLowerCase();
12
+ }
13
+
14
+ /**
15
+ * The origin the site's URLs are written on: the scheme the edge reports (it
16
+ * terminates TLS and sets `X-Forwarded-Proto`) on the same `Host` as
17
+ * seoRequestHost, port included.
18
+ */
19
+ export function seoRequestOrigin(event: H3Event): string {
20
+ return `${getRequestProtocol(event, { xForwardedProto: true })}://${getRequestHost(event).toLowerCase()}`;
21
+ }
@@ -276,7 +276,7 @@ export function storefrontCatalog(): string {
276
276
  }
277
277
 
278
278
  /** The SDK's tenant + auth headers, without the buyer, market or channel. */
279
- function gatewayHeaders(event: H3Event | undefined): Record<string, string> | null {
279
+ export function gatewayHeaders(event: H3Event | undefined): Record<string, string> | null {
280
280
  const { tenant, jwt, apiKey } = resolveRevenexxCredentials(event);
281
281
  if (!tenant || (!jwt && !apiKey)) {
282
282
  return null;
@@ -286,7 +286,7 @@ function gatewayHeaders(event: H3Event | undefined): Record<string, string> | nu
286
286
  : { "X-Revenexx-Tenant": tenant, "X-Revenexx-Api-Key": apiKey };
287
287
  }
288
288
 
289
- function endpoint(): string {
289
+ export function gatewayEndpoint(): string {
290
290
  return String(useRuntimeConfig().revenexxApiUrl || "https://api.revenexx.com");
291
291
  }
292
292
 
@@ -343,7 +343,7 @@ const pusher = createSourcePusher({
343
343
  if (!body || body.key !== catalog) {
344
344
  return null;
345
345
  }
346
- const response = await fetch(`${endpoint().replace(/\/+$/, "")}/v1/translations/sources`, {
346
+ const response = await fetch(`${gatewayEndpoint().replace(/\/+$/, "")}/v1/translations/sources`, {
347
347
  method: "PUT",
348
348
  headers: { "Accept": "application/json", "Content-Type": "application/json", ...auth },
349
349
  body: JSON.stringify(body),
@@ -363,7 +363,7 @@ const pusher = createSourcePusher({
363
363
  const cache = createStorefrontMessageCache({
364
364
  load: async (key, etag, auth) => {
365
365
  const answer = await fetchStorefrontOverlay({
366
- endpoint: endpoint(),
366
+ endpoint: gatewayEndpoint(),
367
367
  headers: auth,
368
368
  catalog: key.catalog,
369
369
  locale: key.locale,
@@ -450,7 +450,7 @@ async function readUncached(event: H3Event | undefined, locale: string): Promise
450
450
  if (preview) {
451
451
  try {
452
452
  const answer = await fetchStorefrontOverlay({
453
- endpoint: endpoint(),
453
+ endpoint: gatewayEndpoint(),
454
454
  headers,
455
455
  catalog,
456
456
  locale,
@@ -0,0 +1,298 @@
1
+ import type { H3Event } from "h3";
2
+
3
+ import type { SeoRules } from "../../app/interfaces/seo";
4
+ import { defaultSeoRules } from "../../app/shared/seoRules";
5
+ import { gatewayEndpoint, gatewayHeaders } from "./storefrontMessages";
6
+
7
+ /**
8
+ * The domain's SEO rules from the seo service (PE-1235):
9
+ *
10
+ * GET {revenexxApiUrl}/v1/seo/storefront/rules?host=<host>
11
+ * Authorization: Bearer <brokered tenant JWT> X-Revenexx-Tenant: <slug>
12
+ * If-None-Match: "<etag held>"
13
+ * → 200 { data: <bundle> } with Cache-Control: max-age | 304
14
+ *
15
+ * One bundle per host, applied per request (canonical, robots, hreflang, title
16
+ * patterns). Per tenant AND host, because one build serves many tenants and a
17
+ * tenant many domains.
18
+ *
19
+ * The read never decides whether the shop renders: it is bounded by a 300 ms
20
+ * timeout, asked again only after the bundle's max-age, and fails OPEN to the
21
+ * last bundle held, or to the service's own defaults. Same stance as
22
+ * ./storefrontMessages.ts.
23
+ */
24
+
25
+ /** Used when the answer names no max-age. The service sends 30 s. */
26
+ const SEO_RULES_TTL_MS = 30_000;
27
+
28
+ /**
29
+ * The shortest a bundle is held, whatever max-age says: `max-age=0` would
30
+ * otherwise put a call to the seo service in front of every request.
31
+ */
32
+ const SEO_RULES_MIN_TTL_MS = 5_000;
33
+
34
+ /** A rules read that has not answered by then is not waited for. */
35
+ const SEO_RULES_TIMEOUT_MS = 300;
36
+
37
+ /** The host arrives with the request, so the map must not grow with whatever a client sends. */
38
+ const MAX_ENTRIES = 1_000;
39
+
40
+ /* ------------------------------------------------------------------ */
41
+ /* Transport */
42
+ /* ------------------------------------------------------------------ */
43
+
44
+ export interface SeoRulesRequest {
45
+ /** Gateway base URL, e.g. https://api.revenexx.com */
46
+ readonly endpoint: string;
47
+ /** Tenant + auth headers, as the SDK would send them. */
48
+ readonly headers: Readonly<Record<string, string>>;
49
+ readonly host: string;
50
+ /** ETag of the bundle already held. */
51
+ readonly etag?: string;
52
+ readonly timeoutMs?: number;
53
+ }
54
+
55
+ export type SeoRulesAnswer =
56
+ | { readonly status: "fresh"; readonly rules: SeoRules; readonly etag: string; readonly maxAgeMs: number | null }
57
+ | { readonly status: "unchanged"; readonly maxAgeMs: number | null };
58
+
59
+ function maxAgeOf(response: Response): number | null {
60
+ const match = /max-age=(\d+)/.exec(response.headers.get("cache-control") ?? "");
61
+ return match ? Number(match[1]) * 1_000 : null;
62
+ }
63
+
64
+ function isRecord(value: unknown): value is Record<string, unknown> {
65
+ return typeof value === "object" && value !== null && !Array.isArray(value);
66
+ }
67
+
68
+ function isStringList(value: unknown): value is string[] {
69
+ return Array.isArray(value) && value.every(item => typeof item === "string");
70
+ }
71
+
72
+ function isStringOrNull(value: unknown): value is string | null {
73
+ return value === null || typeof value === "string";
74
+ }
75
+
76
+ /**
77
+ * Every part of the bundle the storefront reads, with the type it reads it
78
+ * as. A bundle that passes is dereferenced during rendering without further
79
+ * checks, so anything less is not a bundle: the cache then fails open to
80
+ * what it holds or to the defaults, rather than a page failing on it.
81
+ */
82
+ function isSeoRules(value: unknown): value is SeoRules {
83
+ if (!isRecord(value) || typeof value.host !== "string" || typeof value.site_name !== "string") {
84
+ return false;
85
+ }
86
+ const { canonical, hreflang, max_length: maxLength, page_types: pageTypes, organisation } = value;
87
+ return isRecord(canonical)
88
+ && isStringOrNull(canonical.host)
89
+ && isStringList(canonical.cross_domain_page_types)
90
+ && isStringList(canonical.strip_params)
91
+ && isRecord(hreflang)
92
+ && isStringOrNull(hreflang.x_default)
93
+ && (hreflang.locales === null || isStringList(hreflang.locales))
94
+ && isRecord(maxLength)
95
+ && typeof maxLength.title === "number"
96
+ && typeof maxLength.description === "number"
97
+ && isRecord(pageTypes)
98
+ && Object.values(pageTypes).every(type => isRecord(type)
99
+ && typeof type.robots === "string"
100
+ && (type.title === undefined || typeof type.title === "string")
101
+ && (type.description === undefined || isStringOrNull(type.description)))
102
+ && (organisation === null || (isRecord(organisation)
103
+ && typeof organisation.name === "string"
104
+ && isStringOrNull(organisation.logo)
105
+ && isStringList(organisation.same_as)))
106
+ && isRecord(value.structured_data)
107
+ && typeof value.structured_data.prices === "boolean";
108
+ }
109
+
110
+ /** One read of one host's bundle. Throws on anything but 200/304 or a bundle it cannot read. */
111
+ export async function fetchSeoRules(request: SeoRulesRequest): Promise<SeoRulesAnswer> {
112
+ const url = new URL(`${request.endpoint.replace(/\/+$/, "")}/v1/seo/storefront/rules`);
113
+ url.searchParams.set("host", request.host);
114
+
115
+ const headers: Record<string, string> = { Accept: "application/json", ...request.headers };
116
+ if (request.etag) {
117
+ headers["If-None-Match"] = request.etag;
118
+ }
119
+
120
+ const response = await fetch(url, {
121
+ headers,
122
+ signal: AbortSignal.timeout(request.timeoutMs ?? SEO_RULES_TIMEOUT_MS),
123
+ });
124
+
125
+ if (response.status === 304) {
126
+ return { status: "unchanged", maxAgeMs: maxAgeOf(response) };
127
+ }
128
+ if (!response.ok) {
129
+ throw new Error(`seo/storefront/rules answered ${response.status}`);
130
+ }
131
+ const body = await response.json() as { data?: unknown } | null;
132
+ if (!isSeoRules(body?.data)) {
133
+ throw new Error("seo/storefront/rules answered no bundle");
134
+ }
135
+ return { status: "fresh", rules: body.data, etag: response.headers.get("etag") ?? "", maxAgeMs: maxAgeOf(response) };
136
+ }
137
+
138
+ /* ------------------------------------------------------------------ */
139
+ /* Cache */
140
+ /* ------------------------------------------------------------------ */
141
+
142
+ export interface SeoRulesKey {
143
+ readonly tenant: string;
144
+ readonly host: string;
145
+ }
146
+
147
+ type AuthHeaders = Readonly<Record<string, string>>;
148
+
149
+ export interface SeoRulesCacheOptions {
150
+ /** Reads one bundle; `etag` is what is held, `auth` the headers of the request that asked. */
151
+ readonly load: (key: SeoRulesKey, etag: string, auth: AuthHeaders) => Promise<SeoRulesAnswer>;
152
+ readonly ttlMs?: number;
153
+ readonly maxEntries?: number;
154
+ readonly now?: () => number;
155
+ readonly onError?: (err: unknown, key: SeoRulesKey) => void;
156
+ }
157
+
158
+ interface Entry {
159
+ rules: SeoRules;
160
+ etag: string;
161
+ expiresAt: number;
162
+ /**
163
+ * Defaults rather than a real domain's bundle: held because no bundle was
164
+ * ever read for this host, or read for a host the service does not know.
165
+ */
166
+ fallback: boolean;
167
+ }
168
+
169
+ export interface SeoRulesCache {
170
+ read: (key: SeoRulesKey, auth?: AuthHeaders) => Promise<SeoRules>;
171
+ }
172
+
173
+ /**
174
+ * Bundles held in this process, partitioned by tenant + host. Pure — the
175
+ * loader and the clock are injected — so the refresh and fail-open rules are
176
+ * tested without a server.
177
+ */
178
+ export function createSeoRulesCache(options: SeoRulesCacheOptions): SeoRulesCache {
179
+ const fallbackTtl = options.ttlMs ?? SEO_RULES_TTL_MS;
180
+ const maxEntries = options.maxEntries ?? MAX_ENTRIES;
181
+ const now = options.now ?? Date.now;
182
+ const entries = new Map<string, Entry>();
183
+ /** A burst of requests for one host makes one read, not one each. */
184
+ const inFlight = new Map<string, Promise<SeoRules>>();
185
+
186
+ /**
187
+ * When the map is full, a host without a real bundle goes first: the host
188
+ * comes with the request, so a client sending made-up hosts fills the map
189
+ * with fallbacks, and those must not push out the real domains' bundles.
190
+ * The service answers a made-up host with its defaults and `known: false`,
191
+ * so that bundle counts as a fallback too.
192
+ */
193
+ function remember(id: string, entry: Entry): void {
194
+ entries.delete(id);
195
+ entries.set(id, entry);
196
+ while (entries.size > maxEntries) {
197
+ let victim: string | undefined;
198
+ for (const [key, held] of entries) {
199
+ if (held.fallback) {
200
+ victim = key;
201
+ break;
202
+ }
203
+ }
204
+ victim ??= entries.keys().next().value;
205
+ if (victim === undefined) {
206
+ break;
207
+ }
208
+ entries.delete(victim);
209
+ }
210
+ }
211
+
212
+ const expiry = (maxAgeMs: number | null): number => now() + Math.max(maxAgeMs ?? fallbackTtl, SEO_RULES_MIN_TTL_MS);
213
+
214
+ async function refresh(id: string, key: SeoRulesKey, auth: AuthHeaders, held: Entry | undefined): Promise<SeoRules> {
215
+ try {
216
+ const answer = await options.load(key, held?.etag ?? "", auth);
217
+ const expiresAt = expiry(answer.maxAgeMs);
218
+ if (answer.status === "unchanged") {
219
+ const rules = held?.rules ?? defaultSeoRules(key.host);
220
+ remember(id, { rules, etag: held?.etag ?? "", expiresAt, fallback: held?.fallback ?? true });
221
+ return rules;
222
+ }
223
+ remember(id, { rules: answer.rules, etag: answer.etag, expiresAt, fallback: answer.rules.known === false });
224
+ return answer.rules;
225
+ }
226
+ catch (err) {
227
+ options.onError?.(err, key);
228
+ // Fail open: keep what was held — or the service's defaults — and wait
229
+ // out the window before asking again, so an unreachable service is not
230
+ // asked on every page view.
231
+ const rules = held?.rules ?? defaultSeoRules(key.host);
232
+ remember(id, { rules, etag: held?.etag ?? "", expiresAt: now() + fallbackTtl, fallback: held?.fallback ?? true });
233
+ return rules;
234
+ }
235
+ }
236
+
237
+ return {
238
+ async read(key, auth = {}) {
239
+ const id = `${key.tenant}\u0000${key.host}`;
240
+ const held = entries.get(id);
241
+ if (held && now() < held.expiresAt) {
242
+ return held.rules;
243
+ }
244
+ let pending = inFlight.get(id);
245
+ if (!pending) {
246
+ pending = refresh(id, key, auth, held).finally(() => inFlight.delete(id));
247
+ inFlight.set(id, pending);
248
+ }
249
+ return await pending;
250
+ },
251
+ };
252
+ }
253
+
254
+ /* ------------------------------------------------------------------ */
255
+ /* The request's rules */
256
+ /* ------------------------------------------------------------------ */
257
+
258
+ /**
259
+ * Registry key, like every other BFF domain: "mock" (the layer default — the
260
+ * service's defaults for the request's host, no call) or "api" (the seo
261
+ * service through the gateway).
262
+ */
263
+ function isSeoRulesLive(event?: H3Event): boolean {
264
+ return resolveServiceKey(event, {
265
+ domain: "seoService",
266
+ mockKey: "mock",
267
+ liveKey: "api",
268
+ }) === "api";
269
+ }
270
+
271
+ let processCache: SeoRulesCache | undefined;
272
+ let warnedUnconfigured = false;
273
+
274
+ function seoRulesCache(): SeoRulesCache {
275
+ processCache ??= createSeoRulesCache({
276
+ load: (key, etag, auth) => fetchSeoRules({ endpoint: gatewayEndpoint(), headers: auth, host: key.host, etag }),
277
+ onError: (err, key) => getLogService().warn(`SEO rules unavailable for ${key.host}`, apiErrorContext(err)),
278
+ });
279
+ return processCache;
280
+ }
281
+
282
+ /** The rules for the domain this request was made on. */
283
+ export async function readStorefrontSeoRules(event: H3Event, host: string): Promise<SeoRules> {
284
+ if (!isSeoRulesLive(event)) {
285
+ return defaultSeoRules(host);
286
+ }
287
+ const auth = gatewayHeaders(event);
288
+ if (!auth) {
289
+ // Switched to the seo service but nothing to ask it with: say so once,
290
+ // or the defaults look like a domain nobody configured.
291
+ if (!warnedUnconfigured) {
292
+ warnedUnconfigured = true;
293
+ getLogService().warn("SEO rules: seoService is \"api\" but no tenant credentials are set; serving the defaults");
294
+ }
295
+ return defaultSeoRules(host);
296
+ }
297
+ return await seoRulesCache().read({ tenant: auth["X-Revenexx-Tenant"] ?? "", host }, auth);
298
+ }
@@ -1,17 +0,0 @@
1
- import { setResponseHeader } from "h3";
2
-
3
- /**
4
- * Let the hand-back page submit its form to the visit's return address
5
- * (PE-994). Which origin: the one the punchout app answered on the first
6
- * hand-back, kept on the visit cookie. The page is rendered with it in
7
- * `event.context` so it can tell whether THIS document may submit the form, or
8
- * has to be loaded once more with the header that allows it.
9
- */
10
- export default defineEventHandler((event) => {
11
- if (!isHandBackPath(event.path)) {
12
- return;
13
- }
14
- const visit = readPunchoutVisit(event);
15
- event.context.punchoutHandBackOrigin = visit?.handBackOrigin ?? null;
16
- setResponseHeader(event, "Content-Security-Policy", handBackFormAction(visit));
17
- });