@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
@@ -0,0 +1,63 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest'
3
+
4
+ type RecaptchaWindow = Window & { grecaptcha?: unknown }
5
+
6
+ /** Fires each appended reCAPTCHA script's onload with a grecaptcha bound to its key. */
7
+ function serveScripts() {
8
+ const execute = vi.fn()
9
+ const original = document.head.appendChild.bind(document.head)
10
+ vi.spyOn(document.head, 'appendChild').mockImplementation(<T extends Node>(node: T): T => {
11
+ const script = node as unknown as HTMLScriptElement
12
+ const key = decodeURIComponent(new URL(script.src).searchParams.get('render') ?? '')
13
+ // happy-dom refuses to fetch scripts and fires `error`; this stub serves them instead.
14
+ const onload = script.onload
15
+ script.onload = null
16
+ script.onerror = null
17
+ queueMicrotask(() => {
18
+ const w = window as RecaptchaWindow
19
+ // Like Google's script: the first load wins; later ones don't replace it.
20
+ w.grecaptcha ??= {
21
+ ready: (cb: () => void) => cb(),
22
+ execute: async (siteKey: string, opts: { action: string }) => {
23
+ execute(siteKey, opts)
24
+ return siteKey === key ? `token-for-${key}` : ''
25
+ },
26
+ }
27
+ onload?.call(script, new Event('load'))
28
+ })
29
+ return original(node)
30
+ })
31
+ return { execute }
32
+ }
33
+
34
+ async function freshModule() {
35
+ vi.resetModules()
36
+ return import('../../lib/recaptcha.js')
37
+ }
38
+
39
+ describe('admin reCAPTCHA loader', () => {
40
+ afterEach(() => {
41
+ vi.restoreAllMocks()
42
+ document.head.innerHTML = ''
43
+ delete (window as RecaptchaWindow).grecaptcha
44
+ })
45
+
46
+ it('reloads reCAPTCHA when the site key changes instead of reusing the old instance', async () => {
47
+ serveScripts()
48
+ const { getRecaptchaV3Token } = await freshModule()
49
+ expect(await getRecaptchaV3Token('old-key', 'login')).toBe('token-for-old-key')
50
+ expect(await getRecaptchaV3Token('new-key', 'login')).toBe('token-for-new-key')
51
+ const scripts = document.head.querySelectorAll('script[src*="/recaptcha/"]')
52
+ expect(scripts).toHaveLength(1)
53
+ expect((scripts[0] as HTMLScriptElement).src).toContain('render=new-key')
54
+ })
55
+
56
+ it('loads a key once', async () => {
57
+ serveScripts()
58
+ const { getRecaptchaV3Token } = await freshModule()
59
+ await getRecaptchaV3Token('k', 'login')
60
+ await getRecaptchaV3Token('k', 'login')
61
+ expect(document.head.appendChild).toHaveBeenCalledTimes(1)
62
+ })
63
+ })
@@ -14,10 +14,44 @@ const fetchEmailSummary = vi.fn(
14
14
  )
15
15
  const sendFormEmailTest = vi.fn(async () => ({ sentTo: 'ada@calc.io' }))
16
16
 
17
+ const CAPTCHA_OFF = {
18
+ source: 'none' as const,
19
+ provider: 'none' as const,
20
+ siteKey: '',
21
+ hasSecret: false,
22
+ secretReadable: true,
23
+ secretLast4: null,
24
+ scoreThreshold: 0.5,
25
+ envOverride: false,
26
+ protectLogin: false,
27
+ loginDisabledByEnv: false,
28
+ updatedAt: null,
29
+ }
30
+ let captchaSettings: Record<string, unknown> = {
31
+ ...CAPTCHA_OFF,
32
+ source: 'admin',
33
+ provider: 'recaptcha',
34
+ }
35
+ const saveCaptcha = vi.fn(async (input: unknown) => ({
36
+ data: { ...captchaSettings, ...(input as object), source: 'admin', provider: 'recaptcha' },
37
+ }))
38
+
39
+ const setLoginCaptcha = vi.fn(
40
+ async (input: unknown): Promise<{ data?: Record<string, unknown>; error?: string }> => ({
41
+ data: { ...captchaSettings, protectLogin: (input as { enabled: boolean }).enabled },
42
+ }),
43
+ )
44
+ const getRecaptchaV3Token = vi.fn(async (_siteKey: string, _action: string) => 'login-token')
45
+ vi.mock('../../lib/recaptcha.js', () => ({
46
+ getRecaptchaV3Token: (siteKey: string, action: string) => getRecaptchaV3Token(siteKey, action),
47
+ }))
48
+
17
49
  vi.mock('../../lib/forms-service.js', () => ({
18
50
  fetchFormsSettings: async () => defaultSettings(),
19
51
  saveFormsSettings: (body: unknown) => saveFormsSettings(body),
20
- fetchCaptchaStatus: async () => ({ configured: true }),
52
+ fetchFormCaptchaSettings: async () => captchaSettings,
53
+ saveFormCaptchaSettings: (input: unknown) => saveCaptcha(input),
54
+ setLoginCaptcha: (input: unknown) => setLoginCaptcha(input),
21
55
  fetchSpamAiStats: async () => ({ reviewed: 4, flagged: 1, corrected: 0 }),
22
56
  fetchRetentionPreview: async () => ({ entries: 3 }),
23
57
  fetchEmailSummary: () => fetchEmailSummary(),
@@ -47,6 +81,122 @@ describe('Form settings', () => {
47
81
  expect(saved.spam.honeypot).toBe(false)
48
82
  })
49
83
 
84
+ it('saves reCAPTCHA v3 keys without sending a blank secret', async () => {
85
+ captchaSettings = { ...CAPTCHA_OFF }
86
+ saveCaptcha.mockClear()
87
+ render(<FormsSettings currentPath="/forms/settings/spam" onNavigate={vi.fn()} />)
88
+ const siteKey = await screen.findByRole('textbox', { name: 'reCAPTCHA site key' })
89
+ expect(screen.getByText('Not set up')).toBeTruthy()
90
+ fireEvent.change(siteKey, { target: { value: '6LcSiteKey0000000000000000000000000000000' } })
91
+ fireEvent.change(screen.getByLabelText('reCAPTCHA secret key'), {
92
+ target: { value: '6LcSecret00000000000000000000000000000000' },
93
+ })
94
+ fireEvent.change(screen.getByRole('spinbutton', { name: 'Score threshold' }), {
95
+ target: { value: '0.7' },
96
+ })
97
+ fireEvent.click(screen.getByRole('button', { name: 'Save keys' }))
98
+ await waitFor(() => expect(saveCaptcha).toHaveBeenCalled())
99
+ expect(saveCaptcha.mock.calls[0]![0]).toEqual({
100
+ siteKey: '6LcSiteKey0000000000000000000000000000000',
101
+ secretKey: '6LcSecret00000000000000000000000000000000',
102
+ scoreThreshold: 0.7,
103
+ })
104
+ expect(await screen.findByText('Active')).toBeTruthy()
105
+ })
106
+
107
+ it('says env keys are in charge and hides the key fields', async () => {
108
+ captchaSettings = { ...CAPTCHA_OFF, source: 'env', provider: 'recaptcha', envOverride: true }
109
+ render(<FormsSettings currentPath="/forms/settings/spam" onNavigate={vi.fn()} />)
110
+ expect(await screen.findByText('Managed by your deployment')).toBeTruthy()
111
+ expect(screen.queryByRole('textbox', { name: 'reCAPTCHA site key' })).toBeNull()
112
+ expect(screen.getByText('Google reCAPTCHA v3, set by environment variables.')).toBeTruthy()
113
+ captchaSettings = { ...CAPTCHA_OFF, source: 'admin', provider: 'recaptcha' }
114
+ })
115
+
116
+ describe('admin login protection', () => {
117
+ const SAVED_KEYS = {
118
+ ...CAPTCHA_OFF,
119
+ source: 'admin',
120
+ provider: 'recaptcha',
121
+ siteKey: '6LcSiteKey0000000000000000000000000000000',
122
+ hasSecret: true,
123
+ secretLast4: '0000',
124
+ }
125
+
126
+ it('runs reCAPTCHA in this browser before switching it on', async () => {
127
+ captchaSettings = { ...SAVED_KEYS }
128
+ setLoginCaptcha.mockClear()
129
+ render(<FormsSettings currentPath="/forms/settings/spam" onNavigate={vi.fn()} />)
130
+ const toggle = await screen.findByRole('switch', { name: 'Protect the admin login' })
131
+ expect(toggle.getAttribute('aria-checked')).toBe('false')
132
+ fireEvent.click(toggle)
133
+ await waitFor(() =>
134
+ expect(setLoginCaptcha).toHaveBeenCalledWith({ enabled: true, token: 'login-token' }),
135
+ )
136
+ expect(getRecaptchaV3Token).toHaveBeenCalledWith(SAVED_KEYS.siteKey, 'login')
137
+ await waitFor(() => expect(toggle.getAttribute('aria-checked')).toBe('true'))
138
+ captchaSettings = { ...CAPTCHA_OFF, source: 'admin', provider: 'recaptcha' }
139
+ })
140
+
141
+ it('stays off and says why when the server rejects the keys', async () => {
142
+ const { toast } = await import('sonner')
143
+ captchaSettings = { ...SAVED_KEYS }
144
+ setLoginCaptcha.mockResolvedValueOnce({ error: "These keys didn't pass on this site." })
145
+ render(<FormsSettings currentPath="/forms/settings/spam" onNavigate={vi.fn()} />)
146
+ const toggle = await screen.findByRole('switch', { name: 'Protect the admin login' })
147
+ fireEvent.click(toggle)
148
+ await waitFor(() =>
149
+ expect(toast.error).toHaveBeenCalledWith("These keys didn't pass on this site."),
150
+ )
151
+ expect(toggle.getAttribute('aria-checked')).toBe('false')
152
+ captchaSettings = { ...CAPTCHA_OFF, source: 'admin', provider: 'recaptcha' }
153
+ })
154
+
155
+ it('warns when this site can’t read the saved secret', async () => {
156
+ captchaSettings = { ...SAVED_KEYS, secretReadable: false }
157
+ render(<FormsSettings currentPath="/forms/settings/spam" onNavigate={vi.fn()} />)
158
+ expect((await screen.findByText(/can’t read the saved secret/)).textContent).toMatch(
159
+ /Enter the secret key again and save/,
160
+ )
161
+ captchaSettings = { ...CAPTCHA_OFF, source: 'admin', provider: 'recaptcha' }
162
+ })
163
+
164
+ it('does not warn when an older core leaves secretReadable out', async () => {
165
+ const { secretReadable: _omitted, ...older } = SAVED_KEYS as typeof SAVED_KEYS & {
166
+ secretReadable?: boolean
167
+ }
168
+ captchaSettings = older
169
+ render(<FormsSettings currentPath="/forms/settings/spam" onNavigate={vi.fn()} />)
170
+ await screen.findByRole('switch', { name: 'Protect the admin login' })
171
+ expect(screen.queryByText(/can’t read the saved secret/)).toBeNull()
172
+ captchaSettings = { ...CAPTCHA_OFF, source: 'admin', provider: 'recaptcha' }
173
+ })
174
+
175
+ it('is locked until keys are saved and when CAPTCHA_LOGIN=off', async () => {
176
+ captchaSettings = { ...CAPTCHA_OFF }
177
+ const { unmount } = render(
178
+ <FormsSettings currentPath="/forms/settings/spam" onNavigate={vi.fn()} />,
179
+ )
180
+ const toggle = await screen.findByRole('switch', { name: 'Protect the admin login' })
181
+ expect((toggle as HTMLButtonElement).disabled).toBe(true)
182
+ expect(
183
+ screen.getByText('Save keys first. Sign-ins are then checked with the same keys.'),
184
+ ).toBeTruthy()
185
+ unmount()
186
+
187
+ captchaSettings = { ...SAVED_KEYS, loginDisabledByEnv: true }
188
+ render(<FormsSettings currentPath="/forms/settings/spam" onNavigate={vi.fn()} />)
189
+ expect(
190
+ await screen.findByText('CAPTCHA_LOGIN=off is set, so sign-ins aren’t checked.'),
191
+ ).toBeTruthy()
192
+ expect(
193
+ (screen.getByRole('switch', { name: 'Protect the admin login' }) as HTMLButtonElement)
194
+ .disabled,
195
+ ).toBe(true)
196
+ captchaSettings = { ...CAPTCHA_OFF, source: 'admin', provider: 'recaptcha' }
197
+ })
198
+ })
199
+
50
200
  it('shows every settings tab and switches the open panel', async () => {
51
201
  const onNavigate = vi.fn()
52
202
  render(<FormsSettings currentPath="/forms/settings" onNavigate={onNavigate} />)
@@ -0,0 +1,94 @@
1
+ // @vitest-environment happy-dom
2
+ import { afterEach, describe, expect, it, vi } from 'vitest'
3
+ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
4
+
5
+ /**
6
+ * The server decides whether a login needs a CAPTCHA token. A site key that
7
+ * doesn't load on this domain (or a token that never arrives) must not stop
8
+ * the browser from sending the login.
9
+ */
10
+ vi.mock('../../lib/api.js', () => ({
11
+ cmsApi: vi.fn(async () => ({ data: {}, status: 200 })),
12
+ }))
13
+
14
+ import { Login } from '../../views/Login.js'
15
+
16
+ const captchaConfig = { provider: 'recaptcha' as const, siteKey: '6LcSiteKeyAAAAAAAAAAAAAA' }
17
+
18
+ function signIn() {
19
+ fireEvent.change(screen.getByLabelText('Email Address'), { target: { value: 'ada@calc.io' } })
20
+ fireEvent.change(screen.getByLabelText('Password'), { target: { value: 'hunter22hunter' } })
21
+ fireEvent.click(screen.getByRole('button', { name: 'Sign In' }))
22
+ }
23
+
24
+ describe('Login with a CAPTCHA site key', () => {
25
+ afterEach(() => {
26
+ delete (window as { grecaptcha?: unknown }).grecaptcha
27
+ vi.useRealTimers()
28
+ })
29
+
30
+ it('still sends the login when reCAPTCHA never loads', async () => {
31
+ vi.useFakeTimers({ shouldAdvanceTime: true })
32
+ const onLogin = vi.fn(async () => ({ success: true }))
33
+ render(<Login onLogin={onLogin} captchaConfig={captchaConfig} />)
34
+ signIn()
35
+ await act(async () => {
36
+ await vi.advanceTimersByTimeAsync(8_000)
37
+ })
38
+ await waitFor(() =>
39
+ expect(onLogin).toHaveBeenCalledWith('ada@calc.io', 'hunter22hunter', undefined),
40
+ )
41
+ expect(screen.queryByText('CAPTCHA verification failed. Please try again.')).toBeNull()
42
+ })
43
+
44
+ it('waits for a script still loading at submit and sends its token', async () => {
45
+ vi.useFakeTimers({ shouldAdvanceTime: true })
46
+ const onLogin = vi.fn(async () => ({ success: true }))
47
+ render(<Login onLogin={onLogin} captchaConfig={captchaConfig} />)
48
+ signIn()
49
+ await act(async () => {
50
+ await vi.advanceTimersByTimeAsync(1_500)
51
+ })
52
+ expect(onLogin).not.toHaveBeenCalled()
53
+ ;(window as { grecaptcha?: unknown }).grecaptcha = {
54
+ ready: (cb: () => void) => cb(),
55
+ execute: async () => 'late-token',
56
+ }
57
+ await act(async () => {
58
+ await vi.advanceTimersByTimeAsync(200)
59
+ })
60
+ await waitFor(() =>
61
+ expect(onLogin).toHaveBeenCalledWith('ada@calc.io', 'hunter22hunter', 'late-token'),
62
+ )
63
+ })
64
+
65
+ it('stops waiting for a token that never arrives', async () => {
66
+ vi.useFakeTimers({ shouldAdvanceTime: true })
67
+ ;(window as { grecaptcha?: unknown }).grecaptcha = {
68
+ ready: (cb: () => void) => cb(),
69
+ execute: () => new Promise<string>(() => {}),
70
+ }
71
+ const onLogin = vi.fn(async () => ({ success: true }))
72
+ render(<Login onLogin={onLogin} captchaConfig={captchaConfig} />)
73
+ signIn()
74
+ await act(async () => {
75
+ await vi.advanceTimersByTimeAsync(8_000)
76
+ })
77
+ await waitFor(() =>
78
+ expect(onLogin).toHaveBeenCalledWith('ada@calc.io', 'hunter22hunter', undefined),
79
+ )
80
+ })
81
+
82
+ it('sends the token when reCAPTCHA returns one', async () => {
83
+ ;(window as { grecaptcha?: unknown }).grecaptcha = {
84
+ ready: (cb: () => void) => cb(),
85
+ execute: async () => 'login-token',
86
+ }
87
+ const onLogin = vi.fn(async () => ({ success: true }))
88
+ render(<Login onLogin={onLogin} captchaConfig={captchaConfig} />)
89
+ signIn()
90
+ await waitFor(() =>
91
+ expect(onLogin).toHaveBeenCalledWith('ada@calc.io', 'hunter22hunter', 'login-token'),
92
+ )
93
+ })
94
+ })
@@ -716,8 +716,59 @@ export async function fetchConsentConfig(): Promise<{
716
716
  return res.data ?? { installed: false, bannerEnabled: false }
717
717
  }
718
718
 
719
- export async function fetchCaptchaStatus(): Promise<{ configured: boolean }> {
720
- const res = await cmsApi<{ provider?: string; siteKey?: string | null }>('/captcha/config')
721
- const configured = Boolean(res.data?.siteKey) && res.data?.provider !== 'none'
722
- return { configured }
719
+ /** Form Settings → Spam protection → CAPTCHA. The secret never comes back. */
720
+ export interface FormCaptchaSettings {
721
+ source: 'env' | 'admin' | 'none'
722
+ provider: 'recaptcha' | 'turnstile' | 'none'
723
+ siteKey: string
724
+ hasSecret: boolean
725
+ /** False when the saved secret can't be decrypted on this deployment. Older cores omit it. */
726
+ secretReadable?: boolean
727
+ secretLast4: string | null
728
+ scoreThreshold: number
729
+ envOverride: boolean
730
+ /** Admin-entered keys also protect the admin login. */
731
+ protectLogin: boolean
732
+ /** `CAPTCHA_LOGIN=off` is set, so the login is never challenged by admin keys. */
733
+ loginDisabledByEnv: boolean
734
+ updatedAt: string | null
735
+ }
736
+
737
+ export interface FormCaptchaSettingsInput {
738
+ siteKey?: string
739
+ /** Omit to keep the saved secret. */
740
+ secretKey?: string
741
+ scoreThreshold?: number
742
+ clear?: boolean
743
+ }
744
+
745
+ export async function fetchFormCaptchaSettings(): Promise<FormCaptchaSettings | null> {
746
+ const res = await cmsApi<FormCaptchaSettings>('/forms/captcha-settings')
747
+ return res.data ?? null
748
+ }
749
+
750
+ export async function saveFormCaptchaSettings(
751
+ input: FormCaptchaSettingsInput,
752
+ ): Promise<{ data?: FormCaptchaSettings; fields?: Record<string, string>; error?: string }> {
753
+ const res = await cmsApi<FormCaptchaSettings>('/forms/captcha-settings', {
754
+ method: 'PUT',
755
+ body: JSON.stringify(input),
756
+ })
757
+ if (res.error) {
758
+ const fields = (res.errorBody as { fields?: Record<string, string> } | undefined)?.fields
759
+ return { fields, error: res.error }
760
+ }
761
+ return { data: res.data }
762
+ }
763
+
764
+ /** Switch login protection; turning it on needs a fresh `login` token from this browser. */
765
+ export async function setLoginCaptcha(input: {
766
+ enabled: boolean
767
+ token?: string
768
+ }): Promise<{ data?: FormCaptchaSettings; error?: string }> {
769
+ const res = await cmsApi<FormCaptchaSettings>('/forms/captcha-settings/login', {
770
+ method: 'POST',
771
+ body: JSON.stringify(input),
772
+ })
773
+ return res.error ? { error: res.error } : { data: res.data }
723
774
  }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Google reCAPTCHA v3 in the admin, used to prove saved keys work on this
3
+ * domain before they protect the login. Tokens are single-use and expire after
4
+ * two minutes, so one is fetched per check.
5
+ */
6
+
7
+ interface Grecaptcha {
8
+ ready: (callback: () => void) => void
9
+ execute: (siteKey: string, options: { action: string }) => Promise<string>
10
+ }
11
+
12
+ type RecaptchaWindow = Window & { grecaptcha?: Grecaptcha; ___grecaptcha_cfg?: unknown }
13
+
14
+ const LOAD_TIMEOUT_MS = 15_000
15
+
16
+ let active: { siteKey: string; load: Promise<Grecaptcha> } | null = null
17
+
18
+ // `window.grecaptcha` belongs to the first site key that loaded it; a second
19
+ // `api.js?render=` script doesn't replace it. Switching keys (after saving new
20
+ // ones, or after the login page loaded the old ones) starts from scratch.
21
+ function unloadRecaptcha(): void {
22
+ document.querySelectorAll('script[src*="/recaptcha/"]').forEach((script) => script.remove())
23
+ document.querySelectorAll('.grecaptcha-badge').forEach((badge) => badge.parentElement?.remove())
24
+ const w = window as RecaptchaWindow
25
+ delete w.grecaptcha
26
+ delete w.___grecaptcha_cfg
27
+ }
28
+
29
+ function loadRecaptchaV3(siteKey: string): Promise<Grecaptcha> {
30
+ if (active?.siteKey === siteKey) return active.load
31
+ unloadRecaptcha()
32
+ const load = new Promise<Grecaptcha>((resolve, reject) => {
33
+ const script = document.createElement('script')
34
+ const timer = setTimeout(() => {
35
+ script.remove()
36
+ reject(new Error('reCAPTCHA did not load'))
37
+ }, LOAD_TIMEOUT_MS)
38
+ script.src = `https://www.google.com/recaptcha/api.js?render=${encodeURIComponent(siteKey)}`
39
+ script.async = true
40
+ script.onload = () => {
41
+ const g = (window as RecaptchaWindow).grecaptcha
42
+ if (!g) {
43
+ clearTimeout(timer)
44
+ reject(new Error('reCAPTCHA did not load'))
45
+ return
46
+ }
47
+ g.ready(() => {
48
+ clearTimeout(timer)
49
+ resolve(g)
50
+ })
51
+ }
52
+ script.onerror = () => {
53
+ clearTimeout(timer)
54
+ reject(new Error('reCAPTCHA did not load'))
55
+ }
56
+ document.head.appendChild(script)
57
+ })
58
+ const entry = { siteKey, load }
59
+ active = entry
60
+ load.catch(() => {
61
+ if (active === entry) active = null
62
+ })
63
+ return load
64
+ }
65
+
66
+ /** A fresh token for `action`, or a rejection after `timeoutMs`. */
67
+ export async function getRecaptchaV3Token(
68
+ siteKey: string,
69
+ action: string,
70
+ timeoutMs = 10_000,
71
+ ): Promise<string> {
72
+ let timer: ReturnType<typeof setTimeout> | undefined
73
+ const timeout = new Promise<never>((_, reject) => {
74
+ timer = setTimeout(() => reject(new Error('reCAPTCHA timed out')), timeoutMs)
75
+ })
76
+ try {
77
+ const g = await Promise.race([loadRecaptchaV3(siteKey), timeout])
78
+ const token = await Promise.race([g.execute(siteKey, { action }), timeout])
79
+ if (!token) throw new Error('reCAPTCHA returned no token')
80
+ return token
81
+ } finally {
82
+ clearTimeout(timer)
83
+ }
84
+ }