@shopbite-de/storefront 2.4.0 → 2.5.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 (82) hide show
  1. package/.env.example +13 -1
  2. package/CLAUDE.md +5 -3
  3. package/app/components/Home/Categories.vue +2 -2
  4. package/app/components/Navigation/MobileTop.vue +1 -1
  5. package/app/composables/useAddressAutocomplete.ts +3 -11
  6. package/app/composables/useCheckoutMethodGuard.ts +1 -1
  7. package/app/composables/useShippingMethodChoice.ts +2 -2
  8. package/app/composables/useTrackEvent.ts +4 -3
  9. package/app/pages/account/recover/password/index.vue +10 -0
  10. package/app/pages/registrierung/bestaetigen.vue +4 -0
  11. package/app/utils/openingHours.ts +1 -1
  12. package/app/utils/schema.ts +2 -2
  13. package/app/utils/trackingUrl.ts +39 -0
  14. package/content/index.yml +16 -16
  15. package/content/zahlung-und-versand.md +3 -3
  16. package/docs/notes/2026-07-04-issue-239-hydration-mismatches.md +1 -1
  17. package/docs/notes/2026-09-08-issue-244-category-url-trailing-slash.md +2 -2
  18. package/docs/notes/2026-09-10-issue-251-shop-data-in-base-layer.md +4 -4
  19. package/docs/notes/2026-09-10-issue-272-restaurant-schema.md +3 -3
  20. package/docs/notes/2026-09-10-issue-273-performance-media.md +4 -4
  21. package/docs/notes/2026-09-10-issue-274-seo-basics.md +6 -6
  22. package/docs/notes/2026-09-10-issue-275-accessibility.md +3 -3
  23. package/docs/notes/2026-09-10-issue-290-footer-nap.md +5 -5
  24. package/docs/notes/2026-09-10-issue-294-matomo-without-config.md +1 -1
  25. package/docs/notes/2026-09-10-issue-296-track-direct-search.md +1 -1
  26. package/docs/notes/2026-09-10-issue-312-store-api-criteria-post.md +3 -3
  27. package/docs/notes/2026-09-10-issue-313-wishlist-scoped-tailwind.md +1 -1
  28. package/docs/notes/2026-09-10-issue-314-mobile-js-cost.md +1 -1
  29. package/docs/notes/2026-09-12-issue-319-stylesheet-cost.md +1 -1
  30. package/docs/notes/2026-09-12-issue-325-product-card.md +2 -2
  31. package/docs/notes/2026-09-12-issue-327-home-hero.md +2 -2
  32. package/docs/notes/2026-09-13-issue-332-home-info-cards.md +1 -1
  33. package/docs/notes/2026-09-13-quick-view-flicker.md +1 -1
  34. package/docs/notes/2026-09-14-demo-noindex.md +2 -2
  35. package/docs/notes/2026-09-17-quick-view-compact-options.md +1 -1
  36. package/docs/notes/2026-09-21-issue-273-cache-and-demo-video.md +1 -1
  37. package/docs/notes/2026-09-21-issue-363-non-fatal-404.md +2 -2
  38. package/docs/notes/2026-09-21-issue-366-wishlist-404.md +1 -1
  39. package/docs/notes/2026-09-21-issue-378-dev-modules.md +1 -1
  40. package/docs/notes/2026-10-05-issue-289-product-deep-links.md +1 -1
  41. package/docs/notes/2026-10-05-issue-400-menu-item-ingredients-diet.md +1 -1
  42. package/docs/notes/2026-10-05-issue-401-restaurant-schema-ordering.md +1 -1
  43. package/docs/notes/2026-10-05-issue-402-llms-txt.md +1 -1
  44. package/docs/notes/2026-10-05-issue-403-ai-crawlers.md +1 -1
  45. package/docs/notes/2026-10-05-issue-404-faq.md +1 -1
  46. package/docs/notes/2026-10-06-old-seo-url-redirect.md +5 -5
  47. package/docs/notes/2026-10-07-issue-434-property-group-projection.md +1 -1
  48. package/nuxt.config.ts +56 -8
  49. package/package.json +2 -1
  50. package/server/api/address/autocomplete.get.ts +79 -14
  51. package/server/api/listing/[categoryId].get.ts +5 -28
  52. package/server/api/search.get.ts +4 -18
  53. package/server/plugins/bounded-cache.ts +28 -0
  54. package/server/plugins/security-headers.ts +54 -0
  55. package/server/routes/llms.txt.ts +1 -1
  56. package/server/utils/addressAutocomplete.ts +181 -0
  57. package/server/utils/listingParams.ts +117 -0
  58. package/server/utils/securityHeaders.ts +165 -0
  59. package/test/layer/nuxt.config.ts +2 -2
  60. package/test/nuxt/AccountPagesPreset.test.ts +10 -10
  61. package/test/nuxt/AuthPagesPreset.test.ts +3 -0
  62. package/test/nuxt/CheckoutFormsPreset.test.ts +5 -5
  63. package/test/nuxt/CheckoutSummary.test.ts +1 -1
  64. package/test/nuxt/HeaderFooterPreset.test.ts +10 -10
  65. package/test/nuxt/HomeFaq.test.ts +1 -1
  66. package/test/nuxt/NavigationMobileTop.test.ts +1 -1
  67. package/test/nuxt/OrderPagesPreset.test.ts +2 -2
  68. package/test/nuxt/RegisterConfirmPage.test.ts +12 -0
  69. package/test/nuxt/useAddressAutocomplete.test.ts +7 -22
  70. package/test/nuxt/useCheckoutMethodGuard.test.ts +1 -1
  71. package/test/nuxt/useShippingMethodChoice.test.ts +1 -1
  72. package/test/nuxt/useTrackEvent.test.ts +16 -0
  73. package/test/unit/addressAutocomplete.spec.ts +247 -0
  74. package/test/unit/boundedCache.spec.ts +231 -0
  75. package/test/unit/highlight.spec.ts +2 -2
  76. package/test/unit/llmsTxt.spec.ts +28 -28
  77. package/test/unit/openingHours.spec.ts +3 -3
  78. package/test/unit/schema.spec.ts +29 -32
  79. package/test/unit/securityHeaders.spec.ts +254 -0
  80. package/test/unit/seo.spec.ts +23 -29
  81. package/test/unit/sitemap.spec.ts +1 -1
  82. package/test/unit/trackingUrl.spec.ts +48 -0
@@ -50,25 +50,12 @@ const BASE_CRITERIA = {
50
50
  limit: 100,
51
51
  };
52
52
 
53
- function sanitizeString(value: unknown, maxLength: number): string | undefined {
54
- if (typeof value !== "string" || value === "") return undefined;
55
- const trimmed = value.trim();
56
- return trimmed.length <= maxLength ? trimmed : undefined;
57
- }
58
-
59
- function sanitizePage(value: unknown): number | undefined {
60
- const n = Number(value);
61
- return Number.isInteger(n) && n >= 1 && n <= 1000 ? n : undefined;
62
- }
63
-
64
53
  export default defineCachedEventHandler(
65
54
  async (event) => {
66
55
  const { endpoint, accessToken } = useRuntimeConfig().public.shopware;
67
56
  const q = getQuery(event) as Record<string, unknown>;
68
57
 
69
- const search = sanitizeString(q.query, 256);
70
- const order = sanitizeString(q.order, 64);
71
- const p = sanitizePage(q.p);
58
+ const { search, order, p } = searchParams(q);
72
59
 
73
60
  if (!search) {
74
61
  return {
@@ -97,10 +84,9 @@ export default defineCachedEventHandler(
97
84
  name: "search",
98
85
  getKey: (event) => {
99
86
  const q = getQuery(event) as Record<string, unknown>;
100
- const search = sanitizeString(q.query, 256) ?? "";
101
- const order = sanitizeString(q.order, 64) ?? "";
102
- const p = sanitizePage(q.p) ?? 1;
103
- return [search, order, p].join("|");
87
+ // Validated before it becomes a key (400 otherwise).
88
+ const { search, order, p } = searchParams(q);
89
+ return [search ?? "", order ?? "", p ?? 1].join("|");
104
90
  },
105
91
  },
106
92
  );
@@ -0,0 +1,28 @@
1
+ import lruCacheDriver from "unstorage/drivers/lru-cache";
2
+
3
+ /**
4
+ * Bounded storage for the Nitro cache (cached handlers and functions): an LRU
5
+ * with at most `cacheStorage.maxEntries` entries and `maxSizeMb` of
6
+ * serialised data (NUXT_CACHE_STORAGE_*). Without it the cache lives in the
7
+ * root memory storage without any bound. The least recently used entries
8
+ * are dropped first and are fetched again on their next request. A shop
9
+ * that mounts its own cache storage (`nitro.storage.cache`, e.g. Redis)
10
+ * keeps it; `maxEntries` 0 turns the LRU off.
11
+ */
12
+ export default defineNitroPlugin(() => {
13
+ const { maxEntries = 5000, maxSizeMb = 128 } =
14
+ (
15
+ useRuntimeConfig() as {
16
+ cacheStorage?: { maxEntries?: number; maxSizeMb?: number };
17
+ }
18
+ ).cacheStorage ?? {};
19
+ const max = Math.floor(Number(maxEntries));
20
+ const maxSize = Math.floor(Number(maxSizeMb) * 1024 * 1024);
21
+ if (!(max > 0) || !(maxSize > 0)) return;
22
+
23
+ const storage = useStorage();
24
+ // An unmounted `cache:` resolves to the root storage (base "").
25
+ if (storage.getMount("cache:").base !== "") return;
26
+
27
+ storage.mount("cache", lruCacheDriver({ max, maxSize }));
28
+ });
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Security headers on every response (`runtimeConfig.securityHeaders`,
3
+ * `server/utils/securityHeaders.ts`). Server-rendered HTML additionally gets
4
+ * `Cache-Control: private, no-store` (it may contain the visitor's cart or
5
+ * login, `useUserContextInSSR`) unless a route rule sets one, an optional
6
+ * Content-Security-Policy-Report-Only with hashes of its inline scripts,
7
+ * and no `x-powered-by`.
8
+ */
9
+ import type { SecurityHeadersConfig } from "../utils/securityHeaders";
10
+
11
+ interface RenderResponse {
12
+ body?: unknown;
13
+ headers?: Record<string, string | number | string[] | undefined>;
14
+ }
15
+
16
+ export default defineNitroPlugin((nitroApp) => {
17
+ const runtimeConfig = useRuntimeConfig();
18
+ const config = (runtimeConfig.securityHeaders ?? {}) as SecurityHeadersConfig;
19
+ const headers = securityHeaders(config, runtimeConfig.public.storeUrl);
20
+
21
+ nitroApp.hooks.hook("request", (event) => {
22
+ setResponseHeaders(event, headers);
23
+ });
24
+
25
+ nitroApp.hooks.hook(
26
+ "render:response",
27
+ (response: RenderResponse, { event }) => {
28
+ event.node.res.removeHeader("x-powered-by");
29
+ const responseHeaders = (response.headers ??= {});
30
+ delete responseHeaders["x-powered-by"];
31
+
32
+ const contentType = String(responseHeaders["content-type"] ?? "");
33
+ if (!contentType.includes("text/html")) return;
34
+
35
+ if (
36
+ config.htmlCacheControl?.trim() &&
37
+ !responseHeaders["cache-control"]
38
+ ) {
39
+ responseHeaders["cache-control"] = config.htmlCacheControl.trim();
40
+ }
41
+
42
+ const csp = config.contentSecurityPolicyReportOnly;
43
+ if (csp?.enabled && typeof response.body === "string") {
44
+ responseHeaders["content-security-policy-report-only"] =
45
+ contentSecurityPolicyReportOnly({
46
+ config: csp,
47
+ scriptHashes: inlineScriptHashes(response.body),
48
+ shopwareEndpoint: runtimeConfig.public.shopware?.endpoint,
49
+ matomoUrl: runtimeConfig.public.scripts?.matomoAnalytics?.matomoUrl,
50
+ });
51
+ }
52
+ },
53
+ );
54
+ });
@@ -10,7 +10,7 @@ type Schemas = components["schemas"];
10
10
 
11
11
  // Store API maximum per request.
12
12
  const PRODUCT_PAGE_SIZE = 100;
13
- // A menu has a few hundred products at most (La Fattoria: 390 incl. extras).
13
+ // A menu has a few hundred products at most (a real menu: 390 incl. extras).
14
14
  const MAX_PRODUCT_PAGES = 10;
15
15
 
16
16
  const NAVIGATION_CRITERIA = {
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Input rules, rate limit and cache of the Geoapify proxy
3
+ * (`server/api/address/autocomplete.get.ts`).
4
+ */
5
+
6
+ /** The checkout asks from three characters on (`useAddressAutocomplete`). */
7
+ export const AUTOCOMPLETE_MIN_TEXT = 3;
8
+ export const AUTOCOMPLETE_MAX_TEXT = 200;
9
+ export const AUTOCOMPLETE_MAX_LIMIT = 10;
10
+ const DEFAULT_LIMIT = 5;
11
+ const DEFAULT_LANG = "de";
12
+
13
+ export interface AutocompleteParams {
14
+ text: string;
15
+ lang: string;
16
+ limit: number;
17
+ }
18
+
19
+ export class AutocompleteInputError extends Error {}
20
+
21
+ function single(value: unknown): string | undefined {
22
+ if (value === undefined || value === null || value === "") return undefined;
23
+ if (typeof value !== "string" && typeof value !== "number") {
24
+ throw new AutocompleteInputError("Invalid parameter");
25
+ }
26
+ return String(value);
27
+ }
28
+
29
+ /**
30
+ * The allowed query parameters (`text`, `lang`, `limit`); everything else is
31
+ * ignored. Returns null for a text too short to look up and throws
32
+ * `AutocompleteInputError` for invalid values.
33
+ */
34
+ export function parseAutocompleteQuery(
35
+ query: Record<string, unknown>,
36
+ ): AutocompleteParams | null {
37
+ const text = single(query.text)?.trim() ?? "";
38
+ if (text.length > AUTOCOMPLETE_MAX_TEXT) {
39
+ throw new AutocompleteInputError("Text too long");
40
+ }
41
+
42
+ const lang = single(query.lang) ?? DEFAULT_LANG;
43
+ if (!/^[a-z]{2}$/.test(lang)) {
44
+ throw new AutocompleteInputError("Invalid language");
45
+ }
46
+
47
+ const rawLimit = single(query.limit) ?? String(DEFAULT_LIMIT);
48
+ if (!/^\d{1,2}$/.test(rawLimit)) {
49
+ throw new AutocompleteInputError("Invalid limit");
50
+ }
51
+ const limit = Number(rawLimit);
52
+ if (limit < 1 || limit > AUTOCOMPLETE_MAX_LIMIT) {
53
+ throw new AutocompleteInputError("Invalid limit");
54
+ }
55
+
56
+ if (text.length < AUTOCOMPLETE_MIN_TEXT) return null;
57
+ return { text, lang, limit };
58
+ }
59
+
60
+ /**
61
+ * The Geoapify `filter` from the configured bounding box
62
+ * ("lon1,lat1,lon2,lat2"), or undefined when it is empty or malformed.
63
+ */
64
+ export function boundingBoxFilter(boundingBox: unknown): string | undefined {
65
+ if (typeof boundingBox !== "string") return undefined;
66
+ const parts = boundingBox.split(",").map((part) => part.trim());
67
+ if (parts.length !== 4) return undefined;
68
+ if (!parts.every((part) => /^-?\d{1,3}(\.\d+)?$/.test(part))) {
69
+ return undefined;
70
+ }
71
+ return `rect:${parts.join(",")}`;
72
+ }
73
+
74
+ /** Hides the API key in a URL or in an error message containing one. */
75
+ export function redactApiKey(text: string): string {
76
+ return text.replace(/([?&]apiKey=)[^&\s"']*/gi, "$1***");
77
+ }
78
+
79
+ interface GeoapifyFeature {
80
+ properties?: Record<string, unknown>;
81
+ }
82
+
83
+ const ADDRESS_FIELDS = [
84
+ "street",
85
+ "housenumber",
86
+ "name",
87
+ "city",
88
+ "town",
89
+ "village",
90
+ "postcode",
91
+ "formatted",
92
+ ] as const;
93
+
94
+ /** Keeps only the address fields the checkout reads. */
95
+ export function pickAddressFields(response: unknown): {
96
+ features: { properties: Record<string, unknown> }[];
97
+ } {
98
+ const features = (response as { features?: unknown } | null)?.features;
99
+ if (!Array.isArray(features)) return { features: [] };
100
+ return {
101
+ features: (features as GeoapifyFeature[]).map((feature) => {
102
+ const properties: Record<string, unknown> = {};
103
+ for (const field of ADDRESS_FIELDS) {
104
+ const value = feature?.properties?.[field];
105
+ if (typeof value === "string" || typeof value === "number") {
106
+ properties[field] = value;
107
+ }
108
+ }
109
+ return { properties };
110
+ }),
111
+ };
112
+ }
113
+
114
+ /**
115
+ * In-memory token bucket per key (client IP): `capacity` requests at once,
116
+ * refilled by `refillPerMinute`. Holds at most `maxKeys` buckets; when full,
117
+ * the least recently used bucket is dropped.
118
+ */
119
+ export function createTokenBucketLimiter(options: {
120
+ capacity: number;
121
+ refillPerMinute: number;
122
+ maxKeys?: number;
123
+ now?: () => number;
124
+ }) {
125
+ const { capacity, refillPerMinute, maxKeys = 10_000 } = options;
126
+ const now = options.now ?? (() => Date.now());
127
+ const perMs = refillPerMinute / 60_000;
128
+ const buckets = new Map<string, { tokens: number; at: number }>();
129
+
130
+ return {
131
+ /** Takes a token for `key`; false when the bucket is empty. */
132
+ take(key: string): boolean {
133
+ const time = now();
134
+ const bucket = buckets.get(key);
135
+ let tokens = capacity;
136
+ if (bucket) {
137
+ tokens = Math.min(capacity, bucket.tokens + (time - bucket.at) * perMs);
138
+ buckets.delete(key);
139
+ } else if (buckets.size >= maxKeys) {
140
+ const oldest = buckets.keys().next().value;
141
+ if (oldest !== undefined) buckets.delete(oldest);
142
+ }
143
+ const allowed = tokens >= 1;
144
+ buckets.set(key, { tokens: allowed ? tokens - 1 : tokens, at: time });
145
+ return allowed;
146
+ },
147
+ size: () => buckets.size,
148
+ };
149
+ }
150
+
151
+ /** A small in-memory cache with a TTL and at most `maxEntries` entries. */
152
+ export function createTtlCache<T>(options: {
153
+ ttlMs: number;
154
+ maxEntries: number;
155
+ now?: () => number;
156
+ }) {
157
+ const { ttlMs, maxEntries } = options;
158
+ const now = options.now ?? (() => Date.now());
159
+ const entries = new Map<string, { value: T; expires: number }>();
160
+
161
+ return {
162
+ get(key: string): T | undefined {
163
+ const entry = entries.get(key);
164
+ if (!entry) return undefined;
165
+ if (entry.expires <= now()) {
166
+ entries.delete(key);
167
+ return undefined;
168
+ }
169
+ return entry.value;
170
+ },
171
+ set(key: string, value: T) {
172
+ entries.delete(key);
173
+ while (entries.size >= maxEntries) {
174
+ const oldest = entries.keys().next().value;
175
+ if (oldest === undefined) break;
176
+ entries.delete(oldest);
177
+ }
178
+ entries.set(key, { value, expires: now() + ttlMs });
179
+ },
180
+ };
181
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Query parameters of the cached listing and search routes
3
+ * (`/api/listing/[categoryId]`, `/api/search`). They become part of the cache
4
+ * key, so they are validated and normalised first: an invalid value is a 400
5
+ * and never creates a cache entry.
6
+ */
7
+
8
+ /** Shopware's standard sortings (`listingSortings` replaces the list). */
9
+ export const DEFAULT_SORTINGS = [
10
+ "name-asc",
11
+ "name-desc",
12
+ "price-asc",
13
+ "price-desc",
14
+ "topseller",
15
+ "score",
16
+ ];
17
+ /** Pages of 100 dishes; no menu has more. */
18
+ export const MAX_PAGE = 20;
19
+ export const MAX_TEXT_QUERY = 100;
20
+ export const MAX_FILTER_IDS = 50;
21
+
22
+ const ID = /^[0-9a-f]{32}$/i;
23
+
24
+ export interface ListingParams {
25
+ order?: string;
26
+ properties?: string;
27
+ manufacturer?: string;
28
+ query?: string;
29
+ p?: number;
30
+ }
31
+
32
+ function invalid(name: string): never {
33
+ throw createError({
34
+ statusCode: 400,
35
+ statusMessage: `Invalid parameter: ${name}`,
36
+ });
37
+ }
38
+
39
+ function optionalString(
40
+ query: Record<string, unknown>,
41
+ name: string,
42
+ ): string | undefined {
43
+ const value = query[name];
44
+ if (value === undefined || value === null || value === "") return undefined;
45
+ if (typeof value !== "string") invalid(name);
46
+ return value.trim() || undefined;
47
+ }
48
+
49
+ /** `|`-separated 32-hex ids, lower case, without duplicates, sorted. */
50
+ function idList(query: Record<string, unknown>, name: string) {
51
+ const value = optionalString(query, name);
52
+ if (value === undefined) return undefined;
53
+ const ids = value.split("|");
54
+ if (ids.length > MAX_FILTER_IDS || !ids.every((id) => ID.test(id))) {
55
+ invalid(name);
56
+ }
57
+ return [...new Set(ids.map((id) => id.toLowerCase()))].sort().join("|");
58
+ }
59
+
60
+ function sortings(): string[] {
61
+ const configured = (
62
+ useRuntimeConfig() as { listingSortings?: string | string[] }
63
+ ).listingSortings;
64
+ const list = Array.isArray(configured)
65
+ ? configured
66
+ : (configured ?? "").split(",");
67
+ const keys = list.map((key) => String(key).trim()).filter(Boolean);
68
+ return keys.length > 0 ? keys : DEFAULT_SORTINGS;
69
+ }
70
+
71
+ function order(query: Record<string, unknown>) {
72
+ const value = optionalString(query, "order");
73
+ if (value !== undefined && !sortings().includes(value)) invalid("order");
74
+ return value;
75
+ }
76
+
77
+ function page(query: Record<string, unknown>) {
78
+ const value = optionalString(query, "p");
79
+ if (value === undefined) return undefined;
80
+ if (!/^\d{1,2}$/.test(value)) invalid("p");
81
+ const p = Number(value);
82
+ if (p < 1 || p > MAX_PAGE) invalid("p");
83
+ return p;
84
+ }
85
+
86
+ /** A search text: whitespace collapsed, at most `MAX_TEXT_QUERY` characters. */
87
+ function text(query: Record<string, unknown>, name: string) {
88
+ const value = optionalString(query, name)?.replace(/\s+/g, " ");
89
+ if (value !== undefined && value.length > MAX_TEXT_QUERY) invalid(name);
90
+ return value;
91
+ }
92
+
93
+ /** A category id (32 hex characters), lower case. */
94
+ export function categoryIdParam(value: string | undefined): string {
95
+ if (!value || !ID.test(value)) invalid("categoryId");
96
+ return value.toLowerCase();
97
+ }
98
+
99
+ /** Parameters of `/api/listing/[categoryId]`. */
100
+ export function listingParams(query: Record<string, unknown>): ListingParams {
101
+ return {
102
+ order: order(query),
103
+ properties: idList(query, "properties"),
104
+ manufacturer: idList(query, "manufacturer"),
105
+ query: text(query, "query"),
106
+ p: page(query),
107
+ };
108
+ }
109
+
110
+ /** Parameters of `/api/search`. */
111
+ export function searchParams(query: Record<string, unknown>) {
112
+ return {
113
+ search: text(query, "query"),
114
+ order: order(query),
115
+ p: page(query),
116
+ };
117
+ }
@@ -0,0 +1,165 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ /**
4
+ * Security headers of every response (`server/plugins/security-headers.ts`),
5
+ * from `runtimeConfig.securityHeaders` (NUXT_SECURITY_HEADERS_*). An empty
6
+ * value leaves that header out.
7
+ */
8
+ export interface SecurityHeadersConfig {
9
+ /** Sent only when `public.storeUrl` is https. */
10
+ strictTransportSecurity?: string;
11
+ contentTypeOptions?: string;
12
+ frameOptions?: string;
13
+ /** `frame-ancestors` of the enforced Content-Security-Policy. */
14
+ frameAncestors?: string;
15
+ referrerPolicy?: string;
16
+ permissionsPolicy?: string;
17
+ /** Cache-Control of server-rendered HTML without a route rule one. */
18
+ htmlCacheControl?: string;
19
+ contentSecurityPolicyReportOnly?: CspReportOnlyConfig;
20
+ }
21
+
22
+ export interface CspReportOnlyConfig {
23
+ enabled?: boolean;
24
+ /** Extra sources, space- or comma-separated (e.g. a RUM collector). */
25
+ scriptSrc?: string;
26
+ connectSrc?: string;
27
+ imgSrc?: string;
28
+ /** Endpoint for violation reports (`report-uri`), optional. */
29
+ reportUri?: string;
30
+ }
31
+
32
+ function isHttps(url: string | undefined): boolean {
33
+ try {
34
+ return !!url && new URL(url).protocol === "https:";
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+
40
+ /** The headers sent with every response. */
41
+ export function securityHeaders(
42
+ config: SecurityHeadersConfig,
43
+ storeUrl?: string,
44
+ ): Record<string, string> {
45
+ const headers: Record<string, string> = {};
46
+ const set = (name: string, value: string | undefined) => {
47
+ if (value?.trim()) headers[name] = value.trim();
48
+ };
49
+
50
+ if (isHttps(storeUrl)) {
51
+ set("strict-transport-security", config.strictTransportSecurity);
52
+ }
53
+ set("x-content-type-options", config.contentTypeOptions);
54
+ set("x-frame-options", config.frameOptions);
55
+ if (config.frameAncestors?.trim()) {
56
+ set(
57
+ "content-security-policy",
58
+ `frame-ancestors ${config.frameAncestors.trim()}`,
59
+ );
60
+ }
61
+ set("referrer-policy", config.referrerPolicy);
62
+ set("permissions-policy", config.permissionsPolicy);
63
+ return headers;
64
+ }
65
+
66
+ /** The origin of a URL, or undefined for an empty or invalid one. */
67
+ export function originOf(url: string | undefined): string | undefined {
68
+ if (!url) return undefined;
69
+ try {
70
+ const { origin } = new URL(url);
71
+ return origin === "null" ? undefined : origin;
72
+ } catch {
73
+ return undefined;
74
+ }
75
+ }
76
+
77
+ /** Script types the browser executes, so CSP `script-src` applies. */
78
+ const EXECUTABLE_TYPES = new Set([
79
+ "",
80
+ "module",
81
+ "importmap",
82
+ "speculationrules",
83
+ "text/javascript",
84
+ "application/javascript",
85
+ ]);
86
+
87
+ /**
88
+ * `'sha256-…'` sources for the inline scripts of an HTML document (Nuxt's
89
+ * runtime config script and the import map); data blocks such as
90
+ * `application/json` (the payload) and `application/ld+json` are not
91
+ * executed and need none.
92
+ */
93
+ export function inlineScriptHashes(html: string): string[] {
94
+ const hashes = new Set<string>();
95
+ const scripts = /<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi;
96
+ for (const [, attrs = "", content = ""] of html.matchAll(scripts)) {
97
+ if (/\bsrc\s*=/i.test(attrs)) continue;
98
+ const type = /\btype\s*=\s*["']?([^"'\s>]+)/i.exec(attrs)?.[1] ?? "";
99
+ if (!EXECUTABLE_TYPES.has(type.toLowerCase())) continue;
100
+ const hash = createHash("sha256").update(content, "utf8").digest("base64");
101
+ hashes.add(`'sha256-${hash}'`);
102
+ }
103
+ return [...hashes];
104
+ }
105
+
106
+ function sources(list: string | undefined): string[] {
107
+ return (list ?? "")
108
+ .split(/[\s,]+/)
109
+ .map((source) => source.trim())
110
+ .filter(Boolean);
111
+ }
112
+
113
+ function unique(list: (string | undefined)[]): string[] {
114
+ return [...new Set(list.filter((value): value is string => !!value))];
115
+ }
116
+
117
+ /**
118
+ * Report-only policy for a rendered page: own origin, the Shopware endpoint
119
+ * (Store API calls from the browser), the Matomo host and the configured
120
+ * extra sources. Inline scripts are allowed by hash; inline styles stay
121
+ * allowed (Vue style bindings, inlined component CSS).
122
+ */
123
+ export function contentSecurityPolicyReportOnly(options: {
124
+ config: CspReportOnlyConfig;
125
+ scriptHashes: string[];
126
+ shopwareEndpoint?: string;
127
+ matomoUrl?: string;
128
+ }): string {
129
+ const { config, scriptHashes } = options;
130
+ const shopware = originOf(options.shopwareEndpoint);
131
+ const matomo = originOf(options.matomoUrl);
132
+
133
+ const directives: [string, string[]][] = [
134
+ ["default-src", ["'self'"]],
135
+ [
136
+ "script-src",
137
+ unique(["'self'", ...scriptHashes, matomo, ...sources(config.scriptSrc)]),
138
+ ],
139
+ ["style-src", ["'self'", "'unsafe-inline'"]],
140
+ [
141
+ "img-src",
142
+ unique(["'self'", "data:", "blob:", "https:", shopware, matomo]).concat(
143
+ sources(config.imgSrc),
144
+ ),
145
+ ],
146
+ ["font-src", ["'self'", "data:"]],
147
+ [
148
+ "connect-src",
149
+ unique(["'self'", shopware, matomo, ...sources(config.connectSrc)]),
150
+ ],
151
+ ["worker-src", ["'self'"]],
152
+ ["manifest-src", ["'self'"]],
153
+ ["frame-src", ["'self'"]],
154
+ ["object-src", ["'none'"]],
155
+ ["base-uri", ["'self'"]],
156
+ ["form-action", ["'self'"]],
157
+ ];
158
+ if (config.reportUri?.trim()) {
159
+ directives.push(["report-uri", [config.reportUri.trim()]]);
160
+ }
161
+
162
+ return directives
163
+ .map(([name, values]) => `${name} ${unique(values).join(" ")}`)
164
+ .join("; ");
165
+ }
@@ -1,5 +1,5 @@
1
- // A minimal shop that extends the storefront like the real shops do (La
2
- // Fattoria, the quickstart). CI builds it to catch imports that only
1
+ // A minimal shop that extends the storefront like the real shops do (customer
2
+ // shops, the quickstart). CI builds it to catch imports that only
3
3
  // resolve inside the storefront itself, e.g. the `#shared` alias, which in a
4
4
  // layer points to the shop's shared/ folder (2.0.1).
5
5
  export default defineNuxtConfig({
@@ -25,10 +25,10 @@ const home = {
25
25
  id: "addr-home",
26
26
  firstName: "Gina",
27
27
  lastName: "Rossi",
28
- street: "Kantstr. 6",
29
- zipcode: "63179",
30
- city: "Obertshausen",
31
- phoneNumber: "06104 71427",
28
+ street: "Musterstr. 1",
29
+ zipcode: "12345",
30
+ city: "Musterstadt",
31
+ phoneNumber: "0123 456789",
32
32
  countryId: "de",
33
33
  } as Schemas["CustomerAddress"];
34
34
  const office = {
@@ -98,14 +98,14 @@ describe("account pages with a preset (#445)", () => {
98
98
  wrapper.find(`input[name="shippingAddress.${name}"]`).setValue(value);
99
99
  await fill("firstName", "Gina");
100
100
  await fill("lastName", "Rossi");
101
- await fill("street", "Kantstr. 6");
102
- await fill("zipcode", "63179");
103
- await fill("city", "Obertshausen");
104
- await fill("phoneNumber", "06104 71427");
101
+ await fill("street", "Musterstr. 1");
102
+ await fill("zipcode", "12345");
103
+ await fill("city", "Musterstadt");
104
+ await fill("phoneNumber", "0123 456789");
105
105
  await wrapper.find("form").trigger("submit");
106
106
  await flushPromises();
107
107
  expect(mocks.createCustomerAddress).toHaveBeenCalledWith(
108
- expect.objectContaining({ firstName: "Gina", zipcode: "63179" }),
108
+ expect.objectContaining({ firstName: "Gina", zipcode: "12345" }),
109
109
  );
110
110
  expect(wrapper.emitted("submit-success")?.[0]).toEqual([{ id: "new" }]);
111
111
  });
@@ -153,7 +153,7 @@ describe("account pages with a preset (#445)", () => {
153
153
  const makeShipping = cards[1]!
154
154
  .findAll("button")
155
155
  .find((b) => b.text().startsWith("Als Lieferadresse"))!;
156
- expect(makeShipping.text()).toContain("Waldstr. 1, Obertshausen");
156
+ expect(makeShipping.text()).toContain("Waldstr. 1, Musterstadt");
157
157
  await makeShipping.trigger("click");
158
158
  await flushPromises();
159
159
  expect(mocks.setDefaultCustomerShippingAddress).toHaveBeenCalledWith(
@@ -54,9 +54,12 @@ describe("password pages with a preset (#445)", () => {
54
54
  });
55
55
 
56
56
  it("sets a new password with the hash from the link", async () => {
57
+ const replace = vi.spyOn(useRouter(), "replace");
57
58
  const wrapper = await mountSuspended(PasswordReset, {
58
59
  route: "/account/recover/password?hash=abc",
59
60
  });
61
+ // the hash is read once and removed from the address bar
62
+ expect(replace).toHaveBeenLastCalledWith({ query: {} });
60
63
  await wrapper.find('input[name="newPassword"]').setValue("geheim123");
61
64
  await wrapper
62
65
  .find('input[name="newPasswordConfirm"]')