@prenta/admin 2.10.0 → 2.11.1

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 (37) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/dist/__tests__/lib/recaptcha.test.d.ts +2 -0
  3. package/dist/__tests__/lib/recaptcha.test.d.ts.map +1 -0
  4. package/dist/__tests__/lib/recaptcha.test.js +57 -0
  5. package/dist/__tests__/lib/recaptcha.test.js.map +1 -0
  6. package/dist/__tests__/views/forms-settings.render.test.js +122 -1
  7. package/dist/__tests__/views/forms-settings.render.test.js.map +1 -1
  8. package/dist/__tests__/views/login-captcha.render.test.d.ts +2 -0
  9. package/dist/__tests__/views/login-captcha.render.test.d.ts.map +1 -0
  10. package/dist/__tests__/views/login-captcha.render.test.js +80 -0
  11. package/dist/__tests__/views/login-captcha.render.test.js.map +1 -0
  12. package/dist/lib/forms-service.d.ts +37 -2
  13. package/dist/lib/forms-service.d.ts.map +1 -1
  14. package/dist/lib/forms-service.js +22 -4
  15. package/dist/lib/forms-service.js.map +1 -1
  16. package/dist/lib/recaptcha.d.ts +8 -0
  17. package/dist/lib/recaptcha.d.ts.map +1 -0
  18. package/dist/lib/recaptcha.js +73 -0
  19. package/dist/lib/recaptcha.js.map +1 -0
  20. package/dist/prenta-admin.css +1 -1
  21. package/dist/views/FormsSettings.d.ts.map +1 -1
  22. package/dist/views/FormsSettings.js +99 -5
  23. package/dist/views/FormsSettings.js.map +1 -1
  24. package/dist/views/Login.d.ts.map +1 -1
  25. package/dist/views/Login.js +30 -11
  26. package/dist/views/Login.js.map +1 -1
  27. package/dist/views/settings/CaptchaStatusCard.js +2 -2
  28. package/dist/views/settings/CaptchaStatusCard.js.map +1 -1
  29. package/package.json +5 -5
  30. package/src/__tests__/lib/recaptcha.test.ts +63 -0
  31. package/src/__tests__/views/forms-settings.render.test.tsx +151 -1
  32. package/src/__tests__/views/login-captcha.render.test.tsx +94 -0
  33. package/src/lib/forms-service.ts +55 -4
  34. package/src/lib/recaptcha.ts +84 -0
  35. package/src/views/FormsSettings.tsx +249 -4
  36. package/src/views/Login.tsx +35 -11
  37. package/src/views/settings/CaptchaStatusCard.tsx +2 -2
@@ -19,7 +19,9 @@ import {
19
19
  import { LONG_TAIL_CLICK_IDS, TOP_TIER_CLICK_IDS } from '@prenta/core/forms/attribution'
20
20
  import { validateAttributionWindows } from '@prenta/core/forms/attribution-settings'
21
21
  import {
22
- fetchCaptchaStatus,
22
+ fetchFormCaptchaSettings,
23
+ saveFormCaptchaSettings,
24
+ setLoginCaptcha,
23
25
  fetchConsentConfig,
24
26
  fetchEmailSummary,
25
27
  fetchFormsSettings,
@@ -28,8 +30,10 @@ import {
28
30
  saveFormsSettings,
29
31
  sendFormEmailTest,
30
32
  downloadEntriesExport,
33
+ type FormCaptchaSettings,
31
34
  type FormsSettingsDocument,
32
35
  } from '../lib/forms-service.js'
36
+ import { getRecaptchaV3Token } from '../lib/recaptcha.js'
33
37
 
34
38
  const TABS = [
35
39
  { id: 'spam', label: 'Spam protection', icon: Shield },
@@ -161,7 +165,8 @@ export function FormsSettings({
161
165
  const [saving, setSaving] = useState(false)
162
166
  const [saveState, setSaveState] = useState<'idle' | 'saving' | 'saved' | 'error'>('idle')
163
167
  const [blocklistKind, setBlocklistKind] = useState<BlocklistKind | null>(null)
164
- const [captcha, setCaptcha] = useState<boolean | null>(null)
168
+ const [captchaSettings, setCaptchaSettings] = useState<FormCaptchaSettings | null>(null)
169
+ const captcha = captchaSettings ? captchaSettings.provider !== 'none' : null
165
170
  const [aiStats, setAiStats] = useState({ reviewed: 0, flagged: 0, corrected: 0 })
166
171
  const [email, setEmail] = useState<Awaited<ReturnType<typeof fetchEmailSummary>> | null>(null)
167
172
  const [consent, setConsent] = useState({ installed: false, bannerEnabled: false })
@@ -179,7 +184,7 @@ export function FormsSettings({
179
184
  if (!cancelled)
180
185
  setError(err instanceof Error ? err.message : 'Could not load form settings')
181
186
  })
182
- void fetchCaptchaStatus().then((status) => setCaptcha(status.configured))
187
+ void fetchFormCaptchaSettings().then(setCaptchaSettings)
183
188
  void fetchSpamAiStats().then(setAiStats)
184
189
  void fetchEmailSummary().then(setEmail)
185
190
  void fetchConsentConfig().then(setConsent)
@@ -352,7 +357,7 @@ export function FormsSettings({
352
357
  aria-label="Honeypot field"
353
358
  />
354
359
  </Row>
355
- <Row label="CAPTCHA" help="Cloudflare Turnstile, set up by your developer.">
360
+ <Row label="CAPTCHA" help={captchaHelp(captchaSettings)}>
356
361
  <span
357
362
  className={`rounded-pill px-2 py-0.5 text-[12px] font-semibold ${captcha ? 'bg-suc-l text-suc' : 'bg-warn-l text-warn'}`}
358
363
  >
@@ -379,6 +384,13 @@ export function FormsSettings({
379
384
  <option value="off">Off</option>
380
385
  </select>
381
386
  </Row>
387
+ {captchaSettings ? (
388
+ <RecaptchaKeys
389
+ settings={captchaSettings}
390
+ readOnly={readOnly}
391
+ onSaved={setCaptchaSettings}
392
+ />
393
+ ) : null}
382
394
  <Row label="Submission limit" help="Stops one visitor from flooding a form.">
383
395
  <input
384
396
  aria-label="Submission limit"
@@ -1310,6 +1322,239 @@ function FieldGroup({
1310
1322
  )
1311
1323
  }
1312
1324
 
1325
+ const CAPTCHA_PROVIDER_LABELS: Record<FormCaptchaSettings['provider'], string> = {
1326
+ recaptcha: 'Google reCAPTCHA v3',
1327
+ turnstile: 'Cloudflare Turnstile',
1328
+ none: 'Google reCAPTCHA v3',
1329
+ }
1330
+
1331
+ function captchaHelp(settings: FormCaptchaSettings | null): string {
1332
+ if (settings?.source === 'env') {
1333
+ return `${CAPTCHA_PROVIDER_LABELS[settings.provider]}, set by environment variables.`
1334
+ }
1335
+ return 'Google reCAPTCHA v3. Invisible to visitors: each submission gets a score.'
1336
+ }
1337
+
1338
+ const keyInputClass =
1339
+ 'border-bdr bg-card text-txt h-9 w-full max-w-[340px] rounded-[8px] border px-2.5 font-mono text-[12.5px] disabled:opacity-55'
1340
+
1341
+ /**
1342
+ * The reCAPTCHA v3 keys. Saved on their own, not with the page's save bar,
1343
+ * because the secret is write-only and never part of the settings document.
1344
+ */
1345
+ function RecaptchaKeys({
1346
+ settings,
1347
+ readOnly,
1348
+ onSaved,
1349
+ }: {
1350
+ settings: FormCaptchaSettings
1351
+ readOnly: boolean
1352
+ onSaved: (next: FormCaptchaSettings) => void
1353
+ }) {
1354
+ const [siteKey, setSiteKey] = useState(settings.siteKey)
1355
+ const [secretKey, setSecretKey] = useState('')
1356
+ const [threshold, setThreshold] = useState(String(settings.scoreThreshold))
1357
+ const [errors, setErrors] = useState<Record<string, string>>({})
1358
+ const [busy, setBusy] = useState<'save' | 'remove' | 'login' | null>(null)
1359
+
1360
+ useEffect(() => {
1361
+ setSiteKey(settings.siteKey)
1362
+ setThreshold(String(settings.scoreThreshold))
1363
+ }, [settings.siteKey, settings.scoreThreshold])
1364
+
1365
+ if (settings.envOverride) {
1366
+ return (
1367
+ <Row
1368
+ label="reCAPTCHA keys"
1369
+ help="RECAPTCHA_* or TURNSTILE_* environment variables are set, so keys entered here aren't used. Remove those variables to manage keys here."
1370
+ >
1371
+ <span className="text-sub text-[12.5px]">Managed by your deployment</span>
1372
+ </Row>
1373
+ )
1374
+ }
1375
+
1376
+ const dirty =
1377
+ siteKey.trim() !== settings.siteKey ||
1378
+ secretKey.trim() !== '' ||
1379
+ Number(threshold) !== settings.scoreThreshold
1380
+
1381
+ async function save(clear = false) {
1382
+ setBusy(clear ? 'remove' : 'save')
1383
+ setErrors({})
1384
+ const res = await saveFormCaptchaSettings(
1385
+ clear
1386
+ ? { clear: true }
1387
+ : {
1388
+ siteKey: siteKey.trim(),
1389
+ ...(secretKey.trim() ? { secretKey: secretKey.trim() } : {}),
1390
+ scoreThreshold: Number(threshold),
1391
+ },
1392
+ )
1393
+ setBusy(null)
1394
+ if (res.data) {
1395
+ setSecretKey('')
1396
+ onSaved(res.data)
1397
+ toast.success(clear ? 'reCAPTCHA keys removed' : 'reCAPTCHA keys saved')
1398
+ return
1399
+ }
1400
+ if (res.fields) setErrors(res.fields)
1401
+ else toast.error(res.error ?? 'Could not save the reCAPTCHA keys')
1402
+ }
1403
+
1404
+ async function toggleLogin(enabled: boolean) {
1405
+ setBusy('login')
1406
+ let token: string | undefined
1407
+ if (enabled) {
1408
+ try {
1409
+ token = await getRecaptchaV3Token(settings.siteKey, 'login')
1410
+ } catch {
1411
+ setBusy(null)
1412
+ toast.error(
1413
+ "reCAPTCHA didn't load with this site key. Check that this domain is added in the reCAPTCHA admin console.",
1414
+ )
1415
+ return
1416
+ }
1417
+ }
1418
+ const res = await setLoginCaptcha({ enabled, token })
1419
+ setBusy(null)
1420
+ if (res.data) {
1421
+ onSaved(res.data)
1422
+ toast.success(enabled ? 'Admin login protected' : 'Admin login protection off')
1423
+ } else {
1424
+ toast.error(res.error ?? 'Could not change login protection')
1425
+ }
1426
+ }
1427
+
1428
+ const hasKeys = settings.source === 'admin' && settings.hasSecret
1429
+ const loginLocked = readOnly || settings.loginDisabledByEnv || !hasKeys || dirty
1430
+ const loginHelp = settings.loginDisabledByEnv
1431
+ ? 'CAPTCHA_LOGIN=off is set, so sign-ins aren’t checked.'
1432
+ : !hasKeys
1433
+ ? 'Save keys first. Sign-ins are then checked with the same keys.'
1434
+ : dirty
1435
+ ? 'Save your key changes first.'
1436
+ : 'Checks sign-ins with these keys. Turning it on runs a test on this domain first.'
1437
+
1438
+ const fieldError = (key: string) =>
1439
+ errors[key] ? (
1440
+ <span
1441
+ id={`recaptcha-${key}-e`}
1442
+ role="alert"
1443
+ className="text-err flex basis-full items-center justify-end gap-1 text-right text-[12px] font-medium"
1444
+ >
1445
+ <AlertCircle size={13} aria-hidden />
1446
+ {errors[key]}
1447
+ </span>
1448
+ ) : null
1449
+
1450
+ return (
1451
+ <>
1452
+ <Row
1453
+ label="reCAPTCHA site key"
1454
+ help="From the reCAPTCHA admin console. Choose reCAPTCHA v3 and add your site's domains."
1455
+ >
1456
+ <input
1457
+ aria-label="reCAPTCHA site key"
1458
+ value={siteKey}
1459
+ disabled={readOnly}
1460
+ autoComplete="off"
1461
+ spellCheck={false}
1462
+ aria-invalid={errors.siteKey ? true : undefined}
1463
+ aria-describedby={errors.siteKey ? 'recaptcha-siteKey-e' : undefined}
1464
+ onChange={(event) => setSiteKey(event.target.value)}
1465
+ className={keyInputClass}
1466
+ />
1467
+ {fieldError('siteKey')}
1468
+ </Row>
1469
+ <Row
1470
+ label="reCAPTCHA secret key"
1471
+ help={
1472
+ settings.hasSecret
1473
+ ? 'Saved and encrypted. Leave blank to keep it.'
1474
+ : 'Stored encrypted. It never leaves the server.'
1475
+ }
1476
+ >
1477
+ <input
1478
+ aria-label="reCAPTCHA secret key"
1479
+ type="password"
1480
+ value={secretKey}
1481
+ disabled={readOnly}
1482
+ autoComplete="new-password"
1483
+ spellCheck={false}
1484
+ placeholder={settings.secretLast4 ? `•••• ${settings.secretLast4}` : ''}
1485
+ aria-invalid={errors.secretKey ? true : undefined}
1486
+ aria-describedby={errors.secretKey ? 'recaptcha-secretKey-e' : undefined}
1487
+ onChange={(event) => setSecretKey(event.target.value)}
1488
+ className={keyInputClass}
1489
+ />
1490
+ {fieldError('secretKey') ??
1491
+ (settings.hasSecret && settings.secretReadable === false ? (
1492
+ <span
1493
+ role="alert"
1494
+ className="text-err flex basis-full items-center justify-end gap-1 text-right text-[12px] font-medium"
1495
+ >
1496
+ <AlertCircle size={13} aria-hidden />
1497
+ This site can’t read the saved secret, so CAPTCHA checks fail here. It was saved with
1498
+ a different CMS_ENCRYPTION_KEY. Enter the secret key again and save.
1499
+ </span>
1500
+ ) : null)}
1501
+ </Row>
1502
+ <Row
1503
+ label="Score threshold"
1504
+ help="Submissions scoring below this are rejected. 0 is likely a bot, 1 likely a person; Google suggests 0.5."
1505
+ >
1506
+ <input
1507
+ aria-label="Score threshold"
1508
+ type="number"
1509
+ min={0}
1510
+ max={1}
1511
+ step={0.1}
1512
+ value={threshold}
1513
+ disabled={readOnly}
1514
+ aria-invalid={errors.scoreThreshold ? true : undefined}
1515
+ aria-describedby={errors.scoreThreshold ? 'recaptcha-scoreThreshold-e' : undefined}
1516
+ onChange={(event) => setThreshold(event.target.value)}
1517
+ className="border-bdr bg-card h-9 w-[84px] rounded-[8px] border px-2.5 text-right text-[13px] tabular-nums disabled:opacity-55"
1518
+ />
1519
+ {fieldError('scoreThreshold')}
1520
+ </Row>
1521
+ {readOnly ? null : (
1522
+ <div className="border-bdr flex flex-wrap justify-end gap-2 border-b px-5 py-3">
1523
+ {settings.source === 'admin' ? (
1524
+ <Button
1525
+ type="button"
1526
+ variant="danger"
1527
+ size="sm"
1528
+ loading={busy === 'remove'}
1529
+ disabled={busy !== null}
1530
+ onClick={() => void save(true)}
1531
+ >
1532
+ Remove keys
1533
+ </Button>
1534
+ ) : null}
1535
+ <Button
1536
+ type="button"
1537
+ size="sm"
1538
+ loading={busy === 'save'}
1539
+ disabled={busy !== null || !dirty}
1540
+ onClick={() => void save()}
1541
+ >
1542
+ Save keys
1543
+ </Button>
1544
+ </div>
1545
+ )}
1546
+ <Row label="Protect the admin login" help={loginHelp}>
1547
+ <Toggle
1548
+ checked={settings.protectLogin}
1549
+ disabled={loginLocked || busy !== null}
1550
+ onCheckedChange={(enabled) => void toggleLogin(enabled)}
1551
+ aria-label="Protect the admin login"
1552
+ />
1553
+ </Row>
1554
+ </>
1555
+ )
1556
+ }
1557
+
1313
1558
  function Card({
1314
1559
  title,
1315
1560
  description,
@@ -139,7 +139,9 @@ function OAuthIcon({ provider }: { provider: string }) {
139
139
  function useCaptchaScript(provider: string | undefined, siteKey: string | null | undefined) {
140
140
  const [loaded, setLoaded] = useState(false)
141
141
 
142
- useState(() => {
142
+ // An effect, not a state initializer: the captcha config can arrive after
143
+ // the first render, and the script must load then.
144
+ useEffect(() => {
143
145
  if (typeof window === 'undefined' || !siteKey) return
144
146
 
145
147
  if (provider === 'recaptcha') {
@@ -149,7 +151,7 @@ function useCaptchaScript(provider: string | undefined, siteKey: string | null |
149
151
  return
150
152
  }
151
153
  const script = document.createElement('script')
152
- script.src = `https://www.google.com/recaptcha/api.js?render=${siteKey}`
154
+ script.src = `https://www.google.com/recaptcha/api.js?render=${encodeURIComponent(siteKey)}`
153
155
  script.async = true
154
156
  script.onload = () => setLoaded(true)
155
157
  document.head.appendChild(script)
@@ -165,14 +167,35 @@ function useCaptchaScript(provider: string | undefined, siteKey: string | null |
165
167
  script.onload = () => setLoaded(true)
166
168
  document.head.appendChild(script)
167
169
  }
168
- })
170
+ }, [provider, siteKey])
169
171
 
170
172
  return loaded
171
173
  }
172
174
 
175
+ const CAPTCHA_TOKEN_TIMEOUT_MS = 8_000
176
+
177
+ /** Resolves '' when the token doesn't arrive in time or the fetch fails. */
178
+ function withTimeout(promise: Promise<string>, ms: number): Promise<string> {
179
+ let timer: ReturnType<typeof setTimeout> | undefined
180
+ const timeout = new Promise<string>((resolve) => {
181
+ timer = setTimeout(() => resolve(''), ms)
182
+ })
183
+ return Promise.race([promise.catch(() => ''), timeout]).finally(() => clearTimeout(timer))
184
+ }
185
+
186
+ /** The provider's global once its script has loaded (it may still be loading at submit). */
187
+ async function waitForGlobal(name: 'grecaptcha' | 'turnstile'): Promise<any> {
188
+ const deadline = Date.now() + CAPTCHA_TOKEN_TIMEOUT_MS
189
+ for (;;) {
190
+ const value = (window as any)[name]
191
+ if (value || Date.now() >= deadline) return value
192
+ await new Promise((resolve) => setTimeout(resolve, 100))
193
+ }
194
+ }
195
+
173
196
  async function getCaptchaToken(provider: string, siteKey: string, action: string): Promise<string> {
174
197
  if (provider === 'recaptcha') {
175
- const grecaptcha = (window as any).grecaptcha
198
+ const grecaptcha = await waitForGlobal('grecaptcha')
176
199
  if (!grecaptcha) return ''
177
200
  return new Promise((resolve) => {
178
201
  grecaptcha.ready(() => {
@@ -185,7 +208,7 @@ async function getCaptchaToken(provider: string, siteKey: string, action: string
185
208
  }
186
209
 
187
210
  if (provider === 'turnstile') {
188
- const turnstile = (window as any).turnstile
211
+ const turnstile = await waitForGlobal('turnstile')
189
212
  if (!turnstile) return ''
190
213
  return new Promise((resolve) => {
191
214
  const container = document.createElement('div')
@@ -281,14 +304,15 @@ export function Login({
281
304
  setSubmitting(true)
282
305
 
283
306
  try {
307
+ // The server decides whether a token is required; a key that doesn't load
308
+ // on this domain must not block sign-in from the browser.
284
309
  let captchaToken: string | undefined
285
310
  if (captchaConfig?.provider && captchaConfig.provider !== 'none' && captchaConfig.siteKey) {
286
- captchaToken = await getCaptchaToken(captchaConfig.provider, captchaConfig.siteKey, 'login')
287
- if (!captchaToken) {
288
- setError('CAPTCHA verification failed. Please try again.')
289
- setSubmitting(false)
290
- return
291
- }
311
+ captchaToken =
312
+ (await withTimeout(
313
+ getCaptchaToken(captchaConfig.provider, captchaConfig.siteKey, 'login'),
314
+ CAPTCHA_TOKEN_TIMEOUT_MS,
315
+ )) || undefined
292
316
  }
293
317
 
294
318
  const result = await onLogin(email.trim(), password, captchaToken)
@@ -36,7 +36,7 @@ export function CaptchaStatusCard() {
36
36
 
37
37
  useEffect(() => {
38
38
  let cancelled = false
39
- void cmsApi<PublicCaptchaConfig>('/captcha/config')
39
+ void cmsApi<PublicCaptchaConfig>('/captcha/config?for=forms')
40
40
  .then((res) => {
41
41
  if (cancelled) return
42
42
  if (res.error || !res.data) {
@@ -58,7 +58,7 @@ export function CaptchaStatusCard() {
58
58
  <div id="security-captcha">
59
59
  <SettingsCard
60
60
  title="Form CAPTCHA"
61
- description="Server-side Turnstile / reCAPTCHA verification on public form submit. Provider keys stay in environment variables."
61
+ description="Server-side Turnstile / reCAPTCHA verification for admin login and public forms, set by environment variables. reCAPTCHA v3 keys entered in Forms → Form Settings → Spam protection cover forms, and the admin login when switched on there."
62
62
  >
63
63
  {error ? (
64
64
  <p className="text-destructive text-sm">{error}</p>