@hszrdm/create-commerce 1.21.0 → 1.22.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.
- package/package.json +1 -1
- package/templates/backend/package.json +1 -1
- package/templates/storefront/package.json +1 -0
- package/templates/storefront/src/app/globals.css +5 -0
- package/templates/storefront/src/components/account-dashboard.tsx +35 -15
- package/templates/storefront/src/components/account-verification-panel.tsx +29 -17
- package/templates/storefront/src/components/consent-banner.tsx +10 -10
- package/templates/storefront/src/lib/core/account.ts +2 -0
- package/templates/storefront/tests/account-verification.test.mjs +12 -0
- package/templates/storefront/tests/consent.test.mjs +120 -0
package/package.json
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
"test:stripe": "node --experimental-strip-types --test tests/stripe-checkout-phase.test.mjs",
|
|
15
15
|
"test:company-tax": "node --experimental-strip-types --test tests/company-tax.test.mjs",
|
|
16
16
|
"test:ga4": "node --experimental-strip-types --test tests/ga4-bootstrap.test.mjs",
|
|
17
|
+
"test:consent": "node --experimental-strip-types --test tests/consent.test.mjs",
|
|
17
18
|
"test:seo": "node --experimental-strip-types --test tests/technical-seo.test.mjs",
|
|
18
19
|
"test:account-verification": "node --test tests/account-verification.test.mjs",
|
|
19
20
|
"test:product-images": "node --experimental-strip-types --test tests/product-image.test.mjs",
|
|
@@ -241,7 +241,12 @@ input[readonly] { background: var(--surface-soft); color: var(--muted); }
|
|
|
241
241
|
.consent-toggle span { display: flex; flex-direction: column; gap: 2px; }
|
|
242
242
|
.consent-toggle small { color: rgba(255,255,255,.65); }
|
|
243
243
|
.consent-actions { display: flex; flex-direction: column; justify-content: end; gap: 8px; min-width: 220px; }
|
|
244
|
+
.consent-actions > .button:not(.consent-reject) { min-height: 48px; }
|
|
244
245
|
.consent .button.secondary { border-color: rgba(255,255,255,.18); background: rgba(255,255,255,.08); color: white; }
|
|
246
|
+
/* Smaller tertiary choice, still full-width, high-contrast and 44px touch-accessible. */
|
|
247
|
+
.consent-actions > .consent-reject { min-height: 44px; font-size: .88rem; font-weight: 700; padding: 8px 12px; }
|
|
248
|
+
.consent-dismiss { position: absolute; top: 9px; right: 9px; display: grid; place-items: center; width: 44px; height: 44px; padding: 0; border: 0; border-radius: 11px; background: transparent; color: white; cursor: pointer; font-size: 1.35rem; }
|
|
249
|
+
.consent-dismiss:hover, .consent-dismiss:focus-visible { background: rgba(255,255,255,.14); }
|
|
245
250
|
|
|
246
251
|
@media (max-width: 1040px) {
|
|
247
252
|
.product-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
|
@@ -58,6 +58,27 @@ export function AccountDashboard({ config }: { config: CoreConfig }) {
|
|
|
58
58
|
const [tab, setTab] = useState<AccountTab>("profile")
|
|
59
59
|
const [email, setEmail] = useState("")
|
|
60
60
|
const [password, setPassword] = useState("")
|
|
61
|
+
const [verificationLink, setVerificationLink] = useState("")
|
|
62
|
+
const [emailChangeLink, setEmailChangeLink] = useState("")
|
|
63
|
+
|
|
64
|
+
useEffect(() => {
|
|
65
|
+
const url = new URL(window.location.href)
|
|
66
|
+
const fragment = new URLSearchParams(url.hash.slice(1))
|
|
67
|
+
for (const [key, capture] of [
|
|
68
|
+
["verify_email", setVerificationLink],
|
|
69
|
+
["change_email_code", setEmailChangeLink],
|
|
70
|
+
] as const) {
|
|
71
|
+
const code = fragment.get(key) || url.searchParams.get(key)
|
|
72
|
+
if (!code) continue
|
|
73
|
+
capture(code)
|
|
74
|
+
if (fragment.has(key)) {
|
|
75
|
+
fragment.delete(key)
|
|
76
|
+
url.hash = fragment.toString()
|
|
77
|
+
}
|
|
78
|
+
url.searchParams.delete(key)
|
|
79
|
+
window.history.replaceState(window.history.state, "", url.pathname + url.search + url.hash)
|
|
80
|
+
}
|
|
81
|
+
}, [])
|
|
61
82
|
const [firstName, setFirstName] = useState("")
|
|
62
83
|
const [lastName, setLastName] = useState("")
|
|
63
84
|
|
|
@@ -78,21 +99,15 @@ export function AccountDashboard({ config }: { config: CoreConfig }) {
|
|
|
78
99
|
useEffect(() => {
|
|
79
100
|
void refresh().catch(() => setCustomer(null)).finally(() => setLoading(false))
|
|
80
101
|
}, [refresh])
|
|
81
|
-
// The Email Center template is shared with registration verification.
|
|
82
|
-
// Existing email-change links must keep working after adding link support.
|
|
83
102
|
useEffect(() => {
|
|
84
|
-
if (!customer || !isAccountEmailVerified(customer)) return
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
if (!code) return
|
|
88
|
-
url.searchParams.delete("change_email_code")
|
|
89
|
-
window.history.replaceState(window.history.state, "", url.pathname + url.search + url.hash)
|
|
90
|
-
void api.confirmEmailChange(code).then(() => refresh()).then(() => {
|
|
103
|
+
if (!customer || !isAccountEmailVerified(customer) || !emailChangeLink) return
|
|
104
|
+
setEmailChangeLink("")
|
|
105
|
+
void api.confirmEmailChange(emailChangeLink).then(() => refresh()).then(() => {
|
|
91
106
|
setAccountNotice({ tone: "success", text: localized(locale, "E-mail-cím módosítva.", "Email address updated.") })
|
|
92
|
-
}).catch((
|
|
93
|
-
setAccountNotice({ tone: "error", text:
|
|
107
|
+
}).catch(() => {
|
|
108
|
+
setAccountNotice({ tone: "error", text: localized(locale, "Az e-mail módosítása nem sikerült.", "Could not change email.") })
|
|
94
109
|
})
|
|
95
|
-
}, [api, customer, refresh, locale])
|
|
110
|
+
}, [api, customer, emailChangeLink, refresh, locale])
|
|
96
111
|
|
|
97
112
|
|
|
98
113
|
const authSubmit = async (event: FormEvent) => {
|
|
@@ -121,8 +136,8 @@ export function AccountDashboard({ config }: { config: CoreConfig }) {
|
|
|
121
136
|
setMessage(
|
|
122
137
|
localized(
|
|
123
138
|
locale,
|
|
124
|
-
"A fiók létrejött.
|
|
125
|
-
"Your account has been created.
|
|
139
|
+
"A fiók létrejött. Erősítsd meg az e-mail-címed.",
|
|
140
|
+
"Your account has been created. Verify your email address to continue.",
|
|
126
141
|
),
|
|
127
142
|
)
|
|
128
143
|
return
|
|
@@ -166,6 +181,9 @@ export function AccountDashboard({ config }: { config: CoreConfig }) {
|
|
|
166
181
|
<p className="eyebrow">{copy.customerAccount}</p>
|
|
167
182
|
<h1>{mode === "register" ? copy.register : mode === "forgot" ? copy.forgotPassword : copy.login}</h1>
|
|
168
183
|
</div>
|
|
184
|
+
{verificationLink || emailChangeLink ? (
|
|
185
|
+
<p role="status">{localized(locale, "A megerősítés folytatásához jelentkezz be.", "Sign in to continue verification.")}</p>
|
|
186
|
+
) : null}
|
|
169
187
|
<div className="segmented">
|
|
170
188
|
<button type="button" className={mode === "login" ? "active" : ""} onClick={() => setMode("login")}>{copy.login}</button>
|
|
171
189
|
<button type="button" className={mode === "register" ? "active" : ""} onClick={() => setMode("register")}>{copy.register}</button>
|
|
@@ -203,6 +221,8 @@ export function AccountDashboard({ config }: { config: CoreConfig }) {
|
|
|
203
221
|
api={api}
|
|
204
222
|
email={stringValue(customer.email)}
|
|
205
223
|
locale={locale}
|
|
224
|
+
linkCode={verificationLink}
|
|
225
|
+
notice={message}
|
|
206
226
|
onVerified={onVerificationComplete}
|
|
207
227
|
onLogout={onVerificationLogout}
|
|
208
228
|
/>
|
|
@@ -447,7 +467,7 @@ function SecuritySection({
|
|
|
447
467
|
<p className="muted">{localized(locale, "Jelenlegi cím", "Current address")}: {stringValue(customer.email)}</p>
|
|
448
468
|
<Field label={copy.newEmail} type="email" value={newEmail} onChange={setNewEmail} />
|
|
449
469
|
<Field label={copy.currentPassword} type="password" value={currentPassword} onChange={setCurrentPassword} />
|
|
450
|
-
<button className="button secondary" type="button" onClick={() => void api.requestEmailChange(currentPassword, newEmail).then(() => setMessage(localized(locale, "Megerősítő
|
|
470
|
+
<button className="button secondary" type="button" onClick={() => void api.requestEmailChange(currentPassword, newEmail).then(() => setMessage(localized(locale, "Megerősítő e-mail kérése rögzítve.", "Verification email requested.")))}>{copy.requestEmailChange}</button>
|
|
451
471
|
<div className="inline-form">
|
|
452
472
|
<input value={emailCode} onChange={(e) => setEmailCode(e.target.value)} placeholder={copy.verificationCode} />
|
|
453
473
|
<button className="button" type="button" onClick={() => void api.confirmEmailChange(emailCode).then(refresh).then(() => setMessage(localized(locale, "E-mail cím módosítva.", "Email address changed.")))}>{copy.verify}</button>
|
|
@@ -14,12 +14,16 @@ export function AccountVerificationPanel({
|
|
|
14
14
|
api,
|
|
15
15
|
email,
|
|
16
16
|
locale,
|
|
17
|
+
linkCode,
|
|
18
|
+
notice,
|
|
17
19
|
onVerified,
|
|
18
20
|
onLogout,
|
|
19
21
|
}: {
|
|
20
22
|
api: ReturnType<typeof accountApi>
|
|
21
23
|
email: string
|
|
22
24
|
locale: "hu" | "en"
|
|
25
|
+
linkCode: string
|
|
26
|
+
notice: string | null
|
|
23
27
|
onVerified: () => Promise<unknown>
|
|
24
28
|
onLogout: () => Promise<unknown>
|
|
25
29
|
}) {
|
|
@@ -30,6 +34,7 @@ export function AccountVerificationPanel({
|
|
|
30
34
|
const [loading, setLoading] = useState(true)
|
|
31
35
|
const [busy, setBusy] = useState<"resend" | "verify" | "logout" | null>(null)
|
|
32
36
|
const [message, setMessage] = useState("")
|
|
37
|
+
const inFlight = useRef(false)
|
|
33
38
|
const usedLink = useRef("")
|
|
34
39
|
const onVerifiedRef = useRef(onVerified)
|
|
35
40
|
onVerifiedRef.current = onVerified
|
|
@@ -58,55 +63,61 @@ export function AccountVerificationPanel({
|
|
|
58
63
|
}, [])
|
|
59
64
|
|
|
60
65
|
const confirm = useCallback(async (value: string) => {
|
|
61
|
-
if (!value.trim()) return
|
|
66
|
+
if (!value.trim() || inFlight.current) return
|
|
67
|
+
inFlight.current = true
|
|
62
68
|
setBusy("verify")
|
|
63
69
|
setMessage("")
|
|
64
70
|
try {
|
|
65
71
|
await api.confirmEmailVerification(value.trim())
|
|
66
72
|
await onVerifiedRef.current()
|
|
67
73
|
} catch (error) {
|
|
68
|
-
setMessage(error instanceof
|
|
74
|
+
setMessage(error instanceof CoreApiError && (error.status === 400 || error.status === 403)
|
|
75
|
+
? (en ? "The verification code is invalid or expired." : "A kód érvénytelen vagy lejárt.")
|
|
76
|
+
: (en ? "Verification failed. Try again." : "A megerősítés sikertelen. Próbáld újra."))
|
|
69
77
|
} finally {
|
|
78
|
+
inFlight.current = false
|
|
70
79
|
setBusy(null)
|
|
71
80
|
}
|
|
72
81
|
}, [api, en])
|
|
73
82
|
|
|
74
|
-
// Links are usable from the same session, or after the customer logs in.
|
|
75
|
-
// Remove the sensitive code from browser history as soon as it is consumed.
|
|
76
83
|
useEffect(() => {
|
|
77
|
-
const url = new URL(window.location.href)
|
|
78
|
-
const linkCode = url.searchParams.get("verify_email")
|
|
79
84
|
if (!linkCode || usedLink.current === linkCode) return
|
|
80
85
|
usedLink.current = linkCode
|
|
81
|
-
url.searchParams.delete("verify_email")
|
|
82
|
-
window.history.replaceState(window.history.state, "", url.pathname + url.search + url.hash)
|
|
83
86
|
setCode(linkCode)
|
|
84
87
|
void confirm(linkCode)
|
|
85
|
-
}, [confirm])
|
|
88
|
+
}, [confirm, linkCode])
|
|
86
89
|
|
|
87
90
|
const retrySeconds = retryAt && now ? Math.max(0, Math.ceil((retryAt - now) / 1000)) : 0
|
|
88
91
|
const countdown = `${Math.floor(retrySeconds / 60).toString().padStart(2, "0")}:${(retrySeconds % 60).toString().padStart(2, "0")}`
|
|
89
92
|
|
|
90
93
|
const resend = async () => {
|
|
91
|
-
if (
|
|
94
|
+
if (inFlight.current || loading || retrySeconds > 0) return
|
|
95
|
+
inFlight.current = true
|
|
92
96
|
setBusy("resend")
|
|
93
97
|
setMessage("")
|
|
94
98
|
try {
|
|
95
99
|
const result = await api.requestEmailVerification() as {
|
|
96
100
|
resend_available_at?: string | null
|
|
97
|
-
|
|
101
|
+
already_verified?: boolean
|
|
102
|
+
}
|
|
103
|
+
if (result.already_verified) {
|
|
104
|
+
await onVerifiedRef.current()
|
|
105
|
+
return
|
|
98
106
|
}
|
|
99
107
|
const millis = result.resend_available_at ? Date.parse(result.resend_available_at) : NaN
|
|
100
|
-
setRetryAt(Number.isFinite(millis) ? millis :
|
|
108
|
+
setRetryAt(Number.isFinite(millis) ? millis : null)
|
|
101
109
|
setMessage(en ? "A new verification email has been requested." : "Új megerősítő e-mailt kértünk.")
|
|
102
110
|
} catch (error) {
|
|
103
111
|
if (error instanceof CoreApiError && error.status === 429) {
|
|
104
|
-
const payload = error.payload as { retry_after_seconds?: number } | null
|
|
105
|
-
|
|
112
|
+
const payload = error.payload as { resend_available_at?: string; retry_after_seconds?: number } | null
|
|
113
|
+
const availableAt = Date.parse(payload?.resend_available_at ?? "")
|
|
114
|
+
setRetryAt(Number.isFinite(availableAt) ? availableAt : Date.now() + (payload?.retry_after_seconds ?? 0) * 1000)
|
|
106
115
|
} else {
|
|
107
|
-
|
|
116
|
+
await refreshStatus().catch(() => undefined)
|
|
117
|
+
setMessage(en ? "Could not request a new email." : "Az újraküldési kérés nem sikerült.")
|
|
108
118
|
}
|
|
109
119
|
} finally {
|
|
120
|
+
inFlight.current = false
|
|
110
121
|
setBusy(null)
|
|
111
122
|
}
|
|
112
123
|
}
|
|
@@ -115,9 +126,10 @@ export function AccountVerificationPanel({
|
|
|
115
126
|
<section className="panel stack" aria-live="polite">
|
|
116
127
|
<p className="eyebrow">{en ? "Account verification" : "Fiók megerősítése"}</p>
|
|
117
128
|
<h1>{en ? "Your email is not verified yet" : "Az e-mail-címed még nincs megerősítve"}</h1>
|
|
129
|
+
{notice ? <p role="status">{notice}</p> : null}
|
|
118
130
|
<p>{en
|
|
119
|
-
? `
|
|
120
|
-
: `
|
|
131
|
+
? `To use the store, verify ${email} with the link or code from your verification email.`
|
|
132
|
+
: `A webshop használatához erősítsd meg a(z) ${email} címet a levélben található linkkel vagy kóddal.`}</p>
|
|
121
133
|
<button className="button secondary" type="button" onClick={() => void resend()} disabled={loading || busy !== null || retrySeconds > 0}>
|
|
122
134
|
{busy === "resend"
|
|
123
135
|
? (en ? "Sending…" : "Küldés…")
|
|
@@ -66,6 +66,11 @@ export function ConsentBanner({ enabled }: { enabled: boolean }) {
|
|
|
66
66
|
|
|
67
67
|
{open ? (
|
|
68
68
|
<aside className="consent" aria-label="Cookie-beállítások" role="dialog" aria-modal="true">
|
|
69
|
+
{preferences ? (
|
|
70
|
+
<button type="button" className="consent-dismiss" aria-label="Cookie-beállítások bezárása" onClick={() => setOpen(false)}>
|
|
71
|
+
×
|
|
72
|
+
</button>
|
|
73
|
+
) : null}
|
|
69
74
|
<div className="stack consent-copy">
|
|
70
75
|
<div>
|
|
71
76
|
<strong>Cookie-beállítások</strong>
|
|
@@ -109,20 +114,15 @@ export function ConsentBanner({ enabled }: { enabled: boolean }) {
|
|
|
109
114
|
</div>
|
|
110
115
|
|
|
111
116
|
<div className="consent-actions">
|
|
112
|
-
<button
|
|
113
|
-
|
|
117
|
+
<button type="button" className="button" onClick={() => save({ analytics: true, marketing: true })}>
|
|
118
|
+
Mindet elfogadom
|
|
114
119
|
</button>
|
|
115
|
-
<button className="button secondary" onClick={() => save({ analytics, marketing })}>
|
|
120
|
+
<button type="button" className="button secondary" onClick={() => save({ analytics, marketing })}>
|
|
116
121
|
Beállítások mentése
|
|
117
122
|
</button>
|
|
118
|
-
<button className="button" onClick={() => save({ analytics:
|
|
119
|
-
|
|
123
|
+
<button type="button" className="button secondary consent-reject" onClick={() => save({ analytics: false, marketing: false })}>
|
|
124
|
+
Opcionálisak elutasítása
|
|
120
125
|
</button>
|
|
121
|
-
{preferences ? (
|
|
122
|
-
<button className="button secondary" onClick={() => setOpen(false)}>
|
|
123
|
-
Bezárás
|
|
124
|
-
</button>
|
|
125
|
-
) : null}
|
|
126
126
|
</div>
|
|
127
127
|
</aside>
|
|
128
128
|
) : null}
|
|
@@ -173,6 +173,8 @@ export function accountApi(config: CoreConfig) {
|
|
|
173
173
|
requestEmailVerification: () =>
|
|
174
174
|
medusaFetch<{
|
|
175
175
|
success: boolean
|
|
176
|
+
already_verified?: boolean
|
|
177
|
+
verification_requested?: boolean
|
|
176
178
|
retry_after_seconds: number
|
|
177
179
|
resend_available_at: string | null
|
|
178
180
|
}>(paths.email_verification, {
|
|
@@ -38,3 +38,15 @@ test("cart ownership is transferred only after email confirmation", () => {
|
|
|
38
38
|
assert.match(dashboard, /if \(signedIn && isAccountEmailVerified\(signedIn\)\)/)
|
|
39
39
|
assert.match(dashboard, /if \(updated && isAccountEmailVerified\(updated\)\)/)
|
|
40
40
|
})
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
test("verification links are removed before login and handed to the verification panel", () => {
|
|
44
|
+
const dashboard = read("components/account-dashboard.tsx")
|
|
45
|
+
const panel = read("components/account-verification-panel.tsx")
|
|
46
|
+
assert.match(dashboard, /new URLSearchParams\(url\.hash\.slice\(1\)\)/)
|
|
47
|
+
assert.match(dashboard, /window\.history\.replaceState/)
|
|
48
|
+
assert.match(dashboard, /linkCode=\{verificationLink\}/)
|
|
49
|
+
assert.match(panel, /void confirm\(linkCode\)/)
|
|
50
|
+
assert.match(panel, /inFlight\.current/)
|
|
51
|
+
assert.doesNotMatch(dashboard, /sessionStorage|localStorage/)
|
|
52
|
+
})
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import assert from "node:assert/strict"
|
|
2
|
+
import { readFileSync } from "node:fs"
|
|
3
|
+
import { afterEach, test } from "node:test"
|
|
4
|
+
import {
|
|
5
|
+
COOKIE_CONSENT_KEY,
|
|
6
|
+
COOKIE_CONSENT_EVENT,
|
|
7
|
+
defaultConsentPreferences,
|
|
8
|
+
readConsentPreferences,
|
|
9
|
+
saveConsentPreferences,
|
|
10
|
+
toGoogleConsentState,
|
|
11
|
+
} from "../src/lib/core/consent.ts"
|
|
12
|
+
|
|
13
|
+
const originalWindow = globalThis.window
|
|
14
|
+
const originalCustomEvent = globalThis.CustomEvent
|
|
15
|
+
|
|
16
|
+
afterEach(() => {
|
|
17
|
+
if (originalWindow === undefined) delete globalThis.window
|
|
18
|
+
else globalThis.window = originalWindow
|
|
19
|
+
if (originalCustomEvent === undefined) delete globalThis.CustomEvent
|
|
20
|
+
else globalThis.CustomEvent = originalCustomEvent
|
|
21
|
+
})
|
|
22
|
+
|
|
23
|
+
test("first visit keeps necessary storage active and optional categories OFF", () => {
|
|
24
|
+
const preferences = defaultConsentPreferences()
|
|
25
|
+
assert.equal(preferences.necessary, true)
|
|
26
|
+
assert.equal(preferences.analytics, false)
|
|
27
|
+
assert.equal(preferences.marketing, false)
|
|
28
|
+
assert.deepEqual(toGoogleConsentState(preferences), {
|
|
29
|
+
analytics_storage: "denied",
|
|
30
|
+
ad_storage: "denied",
|
|
31
|
+
ad_user_data: "denied",
|
|
32
|
+
ad_personalization: "denied",
|
|
33
|
+
})
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
test("Core banner shows accept all, save settings and reject optional in that order", () => {
|
|
37
|
+
const component = readFileSync(new URL("../src/components/consent-banner.tsx", import.meta.url), "utf8")
|
|
38
|
+
const css = readFileSync(new URL("../src/app/globals.css", import.meta.url), "utf8")
|
|
39
|
+
const start = component.indexOf('<div className="consent-actions">')
|
|
40
|
+
assert.ok(start >= 0)
|
|
41
|
+
const end = component.indexOf("</div>", start)
|
|
42
|
+
assert.ok(end > start)
|
|
43
|
+
const actions = component.slice(start, end)
|
|
44
|
+
const accept = actions.indexOf("Mindet elfogadom")
|
|
45
|
+
const save = actions.indexOf("Beállítások mentése")
|
|
46
|
+
const reject = actions.indexOf("Opcionálisak elutasítása")
|
|
47
|
+
assert.ok(accept >= 0 && save > accept && reject > save)
|
|
48
|
+
assert.equal((actions.match(/<button /g) || []).length, 3)
|
|
49
|
+
assert.match(actions, /save\(\{ analytics: true, marketing: true \}\)/)
|
|
50
|
+
assert.match(actions, /save\(\{ analytics, marketing \}\)/)
|
|
51
|
+
assert.match(actions, /save\(\{ analytics: false, marketing: false \}\)/)
|
|
52
|
+
assert.match(actions, /className="button secondary consent-reject"/)
|
|
53
|
+
assert.match(css, /\.consent-actions > \.consent-reject \{ min-height: 44px;/)
|
|
54
|
+
assert.match(css, /font-size: \.88rem/)
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
test("necessary is checked, optional categories are not prechecked, and saved choices are restored", () => {
|
|
58
|
+
const component = readFileSync(new URL("../src/components/consent-banner.tsx", import.meta.url), "utf8")
|
|
59
|
+
assert.match(component, /<input type="checkbox" checked disabled \/>/)
|
|
60
|
+
assert.match(component, /useState\(false\)/)
|
|
61
|
+
assert.match(component, /setAnalytics\(Boolean\(stored\?\.analytics\)\)/)
|
|
62
|
+
assert.match(component, /setMarketing\(Boolean\(stored\?\.marketing\)\)/)
|
|
63
|
+
assert.match(component, /setOpen\(!stored\)/)
|
|
64
|
+
assert.match(component, /setAnalytics\(Boolean\(latest\?\.analytics\)\)/)
|
|
65
|
+
assert.match(component, /setMarketing\(Boolean\(latest\?\.marketing\)\)/)
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
test("save, accept all and reject optional persist exact choices and notify analytics", () => {
|
|
69
|
+
const storage = new Map()
|
|
70
|
+
const commands = []
|
|
71
|
+
const events = []
|
|
72
|
+
globalThis.CustomEvent = class {
|
|
73
|
+
constructor(type, init) {
|
|
74
|
+
this.type = type
|
|
75
|
+
this.detail = init?.detail
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
globalThis.window = {
|
|
79
|
+
localStorage: {
|
|
80
|
+
getItem: (key) => storage.get(key) ?? null,
|
|
81
|
+
setItem: (key, value) => storage.set(key, value),
|
|
82
|
+
},
|
|
83
|
+
gtag: (...args) => commands.push(args),
|
|
84
|
+
dispatchEvent: (event) => { events.push(event); return true },
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
assert.equal(readConsentPreferences(), null)
|
|
88
|
+
|
|
89
|
+
const accepted = saveConsentPreferences({ analytics: true, marketing: true })
|
|
90
|
+
assert.equal(accepted?.necessary, true)
|
|
91
|
+
assert.equal(readConsentPreferences()?.analytics, true)
|
|
92
|
+
assert.equal(readConsentPreferences()?.marketing, true)
|
|
93
|
+
assert.equal(commands.at(-1)[2].analytics_storage, "granted")
|
|
94
|
+
assert.equal(commands.at(-1)[2].ad_storage, "granted")
|
|
95
|
+
|
|
96
|
+
const custom = saveConsentPreferences({ analytics: true, marketing: false })
|
|
97
|
+
assert.equal(custom?.analytics, true)
|
|
98
|
+
assert.equal(custom?.marketing, false)
|
|
99
|
+
assert.equal(commands.at(-1)[2].analytics_storage, "granted")
|
|
100
|
+
assert.equal(commands.at(-1)[2].ad_storage, "denied")
|
|
101
|
+
|
|
102
|
+
const rejected = saveConsentPreferences({ analytics: false, marketing: false })
|
|
103
|
+
assert.equal(rejected?.necessary, true)
|
|
104
|
+
assert.equal(readConsentPreferences()?.analytics, false)
|
|
105
|
+
assert.equal(readConsentPreferences()?.marketing, false)
|
|
106
|
+
assert.equal(commands.at(-1)[2].analytics_storage, "denied")
|
|
107
|
+
assert.equal(commands.at(-1)[2].ad_storage, "denied")
|
|
108
|
+
assert.equal(events.length, 3)
|
|
109
|
+
assert.ok(events.every(event => event.type === COOKIE_CONSENT_EVENT))
|
|
110
|
+
assert.ok(storage.has(COOKIE_CONSENT_KEY))
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
test("tampered consent never silently opts into optional categories", () => {
|
|
114
|
+
globalThis.window = {
|
|
115
|
+
localStorage: {
|
|
116
|
+
getItem: () => JSON.stringify({ version: 1, necessary: true, analytics: "true", marketing: true }),
|
|
117
|
+
},
|
|
118
|
+
}
|
|
119
|
+
assert.equal(readConsentPreferences(), null)
|
|
120
|
+
})
|