@owlmeans/web-captcha-recaptcha 0.0.0-stage → 0.2.0-alpha.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 (49) hide show
  1. package/README.md +80 -2
  2. package/agent-meta/manifest.json +16 -0
  3. package/agent-meta/skills/web-captcha-recaptcha/SKILL.md +78 -0
  4. package/build/append.d.ts +8 -0
  5. package/build/append.d.ts.map +1 -0
  6. package/build/append.js +8 -0
  7. package/build/append.js.map +1 -0
  8. package/build/client.d.ts +8 -0
  9. package/build/client.d.ts.map +1 -0
  10. package/build/client.js +20 -0
  11. package/build/client.js.map +1 -0
  12. package/build/consts.d.ts +34 -0
  13. package/build/consts.d.ts.map +1 -0
  14. package/build/consts.js +76 -0
  15. package/build/consts.js.map +1 -0
  16. package/build/index.d.ts +6 -0
  17. package/build/index.d.ts.map +1 -0
  18. package/build/index.js +5 -0
  19. package/build/index.js.map +1 -0
  20. package/build/loader.d.ts +9 -0
  21. package/build/loader.d.ts.map +1 -0
  22. package/build/loader.js +105 -0
  23. package/build/loader.js.map +1 -0
  24. package/build/react/checkbox.d.ts +8 -0
  25. package/build/react/checkbox.d.ts.map +1 -0
  26. package/build/react/checkbox.js +9 -0
  27. package/build/react/checkbox.js.map +1 -0
  28. package/build/react.d.ts +2 -0
  29. package/build/react.d.ts.map +1 -0
  30. package/build/react.js +2 -0
  31. package/build/react.js.map +1 -0
  32. package/build/types.d.ts +58 -0
  33. package/build/types.d.ts.map +1 -0
  34. package/build/types.js +2 -0
  35. package/build/types.js.map +1 -0
  36. package/package.json +58 -4
  37. package/src/append.ts +12 -0
  38. package/src/client.ts +22 -0
  39. package/src/consts.ts +87 -0
  40. package/src/index.ts +5 -0
  41. package/src/loader.ts +123 -0
  42. package/src/react/checkbox.tsx +17 -0
  43. package/src/react.ts +1 -0
  44. package/src/types.ts +60 -0
  45. package/tests/client.spec.ts +63 -0
  46. package/tests/context.ts +73 -0
  47. package/tests/loader.spec.ts +120 -0
  48. package/tests/react.spec.ts +36 -0
  49. package/tsconfig.json +16 -0
package/build/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "@owlmeans/web-captcha-recaptcha",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0-alpha.0",
4
+ "description": "Google reCAPTCHA client for @owlmeans/web-captcha: the v3 loader, Google's notice in eight languages, the v2 checkbox widget (./react) and the append helper that registers it.",
5
+ "license": "MIT",
6
+ "homepage": "https://owlmeans.com/docs/",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/owlmeans/connect.git",
10
+ "directory": "packages/web-captcha-recaptcha"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/owlmeans/connect/issues"
14
+ },
15
+ "author": "Igor Tkachenko <igor.tkachenko@owlmeans.com> (https://owlmeans.com)",
16
+ "type": "module",
17
+ "scripts": {
18
+ "build": "tsc -b",
19
+ "dev": "sleep 4 && nodemon -e ts,tsx,json --watch src --exec \"tsc -p ./tsconfig.json\"",
20
+ "watch": "tsc -b -w --preserveWatchOutput --pretty",
21
+ "test": "bun test ./tests"
22
+ },
23
+ "main": "build/index.js",
24
+ "module": "build/index.js",
25
+ "types": "build/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "import": "./build/index.js",
29
+ "require": "./build/index.js",
30
+ "default": "./build/index.js",
31
+ "module": "./build/index.js",
32
+ "types": "./build/index.d.ts"
33
+ },
34
+ "./react": {
35
+ "import": "./build/react.js",
36
+ "require": "./build/react.js",
37
+ "default": "./build/react.js",
38
+ "module": "./build/react.js",
39
+ "types": "./build/react.d.ts"
40
+ }
41
+ },
42
+ "dependencies": {
43
+ "@owlmeans/web-captcha": "^0.2.0-alpha.0",
44
+ "react-google-recaptcha": "^3.1.0"
45
+ },
46
+ "peerDependencies": {
47
+ "react": "*"
48
+ },
49
+ "devDependencies": {
50
+ "@owlmeans/dep-config": "^0.2.0-alpha.0",
51
+ "@types/bun": "^1.4.4",
52
+ "@types/react": "^19.3.0",
53
+ "@types/react-google-recaptcha": "^2.1.9",
54
+ "nodemon": "^3.1.14",
55
+ "typescript": "^7.0.2"
56
+ },
57
+ "publishConfig": {
58
+ "access": "public"
59
+ }
60
+ }
package/src/append.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { captchaClients } from '@owlmeans/web-captcha'
2
+ import type { CaptchaClients } from '@owlmeans/web-captcha'
3
+ import { makeRecaptchaClient } from './client.js'
4
+ import type { RecaptchaClient, RecaptchaClientOptions } from './types.js'
5
+
6
+ /**
7
+ * Register the reCAPTCHA client in the page's captcha clients (or the registry given), so a form
8
+ * that is advertised the `recaptcha` provider finds it. Call it once while the app is set up.
9
+ */
10
+ export const appendRecaptchaClient = <W = unknown>(
11
+ options: RecaptchaClientOptions<W> = {}, clients: CaptchaClients = captchaClients
12
+ ): RecaptchaClient<W> => clients.register(makeRecaptchaClient(options))
package/src/client.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { CMOD_RECAPTCHA, RECAPTCHA_NOTICE, RECAPTCHA_PROVIDER, RECAPTCHA_TEXTS } from './consts.js'
2
+ import { recaptchaLoader } from './loader.js'
3
+ import type { RecaptchaClient, RecaptchaClientOptions } from './types.js'
4
+
5
+ /**
6
+ * The reCAPTCHA client of `@owlmeans/web-captcha`: tokens from the invisible, score-based v3 loader,
7
+ * Google's notice (the loader hides the badge) in eight languages, and — when given — an interactive
8
+ * widget (`RecaptchaCheckbox` of `./react`, the v2 checkbox) for a page that renders one.
9
+ */
10
+ export const makeRecaptchaClient = <W = unknown>(options: RecaptchaClientOptions<W> = {}): RecaptchaClient<W> => {
11
+ const loader = options.loader ?? recaptchaLoader
12
+
13
+ return {
14
+ id: RECAPTCHA_PROVIDER,
15
+ load: async siteKey => { await loader.prepare(siteKey) },
16
+ execute: async (siteKey, action) => await loader.token(siteKey, action),
17
+ notice: RECAPTCHA_NOTICE,
18
+ texts: RECAPTCHA_TEXTS,
19
+ siteKeyRecord: options.siteKeyRecord ?? CMOD_RECAPTCHA,
20
+ ...(options.widget != null ? { widget: options.widget } : {}),
21
+ }
22
+ }
package/src/consts.ts ADDED
@@ -0,0 +1,87 @@
1
+ import type { CaptchaNotice, CaptchaTexts } from '@owlmeans/web-captcha'
2
+
3
+ /**
4
+ * The provider id of Google reCAPTCHA — the id the server's provider (`@owlmeans/captcha-recaptcha`)
5
+ * advertises and a page looks this client up by.
6
+ */
7
+ export const RECAPTCHA_PROVIDER = 'recaptcha'
8
+
9
+ /** The client config record whose `value` is the site key (a Frontend record a server advertises). */
10
+ export const CMOD_RECAPTCHA = '_client-external:re-captcha'
11
+
12
+ /** Google's reCAPTCHA script; `?render=<site key>` selects the invisible, score-based (v3) widget. */
13
+ export const RECAPTCHA_SCRIPT_URL = 'https://www.google.com/recaptcha/api.js'
14
+
15
+ /** Marks the script the loader injected; its value is the site key. */
16
+ export const RECAPTCHA_SCRIPT_ATTRIBUTE = 'data-owlmeans-captcha'
17
+
18
+ /** Marks the document style that hides Google's badge. */
19
+ export const RECAPTCHA_STYLE_ATTRIBUTE = 'data-owlmeans-captcha-style'
20
+
21
+ /**
22
+ * The one document-level rule the loader adds unless told not to: Google's badge hidden. A page
23
+ * that hides it must show Google's notice (`RECAPTCHA_TEXTS[lng].notice`) itself.
24
+ */
25
+ export const RECAPTCHA_BADGE_CSS = '.grecaptcha-badge{visibility:hidden}'
26
+
27
+ /** How long the script may take to become ready, in milliseconds. */
28
+ export const RECAPTCHA_LOAD_TIMEOUT = 15_000
29
+
30
+ /** How long one `execute` may take, in milliseconds. */
31
+ export const RECAPTCHA_EXECUTE_TIMEOUT = 20_000
32
+
33
+ /** Google's documents the notice links to. */
34
+ export const RECAPTCHA_PRIVACY_URL = 'https://policies.google.com/privacy'
35
+ export const RECAPTCHA_TERMS_URL = 'https://policies.google.com/terms'
36
+
37
+ /** The notice's links, by the placeholder the sentence names them with. */
38
+ export const RECAPTCHA_NOTICE: CaptchaNotice = Object.freeze({
39
+ links: Object.freeze({ privacy: RECAPTCHA_PRIVACY_URL, terms: RECAPTCHA_TERMS_URL }),
40
+ })
41
+
42
+ /**
43
+ * Google's notice in the eight OwlMeans sign-in languages: the sentence (`{{privacy}}`, `{{terms}}`
44
+ * mark the links) and each link's label.
45
+ */
46
+ export const RECAPTCHA_TEXTS: Readonly<Record<string, CaptchaTexts>> = Object.freeze({
47
+ en: Object.freeze({
48
+ notice: 'This site is protected by reCAPTCHA and the Google {{privacy}} and {{terms}} apply.',
49
+ privacy: 'Privacy Policy',
50
+ terms: 'Terms of Service',
51
+ }),
52
+ pl: Object.freeze({
53
+ notice: 'Ta strona jest chroniona przez reCAPTCHA i obowiązują w niej {{privacy}} oraz {{terms}} Google.',
54
+ privacy: 'Polityka prywatności',
55
+ terms: 'Warunki korzystania z usług',
56
+ }),
57
+ ru: Object.freeze({
58
+ notice: 'Этот сайт защищён reCAPTCHA, и к нему применяются {{privacy}} и {{terms}} Google.',
59
+ privacy: 'Политика конфиденциальности',
60
+ terms: 'Условия использования',
61
+ }),
62
+ be: Object.freeze({
63
+ notice: 'Гэты сайт абаронены reCAPTCHA, і да яго прымяняюцца {{privacy}} і {{terms}} Google.',
64
+ privacy: 'Палітыка прыватнасці',
65
+ terms: 'Умовы выкарыстання',
66
+ }),
67
+ uk: Object.freeze({
68
+ notice: 'Цей сайт захищено reCAPTCHA, і до нього застосовуються {{privacy}} та {{terms}} Google.',
69
+ privacy: 'Політика конфіденційності',
70
+ terms: 'Умови використання',
71
+ }),
72
+ es: Object.freeze({
73
+ notice: 'Este sitio está protegido por reCAPTCHA y se aplican la {{privacy}} y los {{terms}} de Google.',
74
+ privacy: 'Política de privacidad',
75
+ terms: 'Términos del servicio',
76
+ }),
77
+ de: Object.freeze({
78
+ notice: 'Diese Website ist durch reCAPTCHA geschützt, und es gelten die {{privacy}} und die {{terms}} von Google.',
79
+ privacy: 'Datenschutzerklärung',
80
+ terms: 'Nutzungsbedingungen',
81
+ }),
82
+ fr: Object.freeze({
83
+ notice: 'Ce site est protégé par reCAPTCHA, et les {{privacy}} et les {{terms}} de Google s’appliquent.',
84
+ privacy: 'Règles de confidentialité',
85
+ terms: 'Conditions d’utilisation',
86
+ }),
87
+ })
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export type * from './types.js'
2
+ export * from './consts.js'
3
+ export * from './loader.js'
4
+ export * from './client.js'
5
+ export * from './append.js'
package/src/loader.ts ADDED
@@ -0,0 +1,123 @@
1
+ import { CaptchaLoadError } from '@owlmeans/web-captcha'
2
+ import type { CaptchaLoadErrorReason } from '@owlmeans/web-captcha'
3
+ import {
4
+ RECAPTCHA_BADGE_CSS, RECAPTCHA_EXECUTE_TIMEOUT, RECAPTCHA_LOAD_TIMEOUT, RECAPTCHA_SCRIPT_ATTRIBUTE,
5
+ RECAPTCHA_SCRIPT_URL, RECAPTCHA_STYLE_ATTRIBUTE,
6
+ } from './consts.js'
7
+ import type { Grecaptcha, RecaptchaDocument, RecaptchaLoader, RecaptchaLoaderOptions, RecaptchaWindow } from './types.js'
8
+
9
+ /**
10
+ * Google's reCAPTCHA v3 loader. Nothing touches the page until `prepare` or `token` is called, so
11
+ * the module is safe to import during server rendering and in tests.
12
+ */
13
+ export const createRecaptchaLoader = (options: RecaptchaLoaderOptions = {}): RecaptchaLoader => {
14
+ const hideBadge = options.hideBadge ?? true
15
+ const loadTimeout = options.loadTimeout ?? RECAPTCHA_LOAD_TIMEOUT
16
+ const executeTimeout = options.executeTimeout ?? RECAPTCHA_EXECUTE_TIMEOUT
17
+ const scriptUrl = options.scriptUrl ?? RECAPTCHA_SCRIPT_URL
18
+ const loads = new Map<string, Promise<Grecaptcha>>()
19
+
20
+ const documentOf = (): RecaptchaDocument | null =>
21
+ options.document ?? (typeof document !== 'undefined' ? document : null)
22
+
23
+ const windowOf = (): RecaptchaWindow | null =>
24
+ options.window ?? (typeof window !== 'undefined' ? window as unknown as RecaptchaWindow : null)
25
+
26
+ const addBadgeStyle = (page: RecaptchaDocument): void => {
27
+ if (page.querySelector(`style[${RECAPTCHA_STYLE_ATTRIBUTE}]`) != null) {
28
+ return
29
+ }
30
+ const style = page.createElement('style')
31
+ style.setAttribute(RECAPTCHA_STYLE_ATTRIBUTE, '')
32
+ style.textContent = RECAPTCHA_BADGE_CSS
33
+ page.head.appendChild(style)
34
+ }
35
+
36
+ const inject = (siteKey: string): Promise<Grecaptcha> => new Promise<Grecaptcha>((resolve, reject) => {
37
+ const page = documentOf()
38
+ const host = windowOf()
39
+ if (page == null || host == null) {
40
+ reject(new CaptchaLoadError('unavailable', 'reCAPTCHA needs a page to load into'))
41
+ return
42
+ }
43
+
44
+ const script = page.createElement('script')
45
+ let settled = false
46
+ let timer: ReturnType<typeof setTimeout> | undefined
47
+ const fail = (reason: CaptchaLoadErrorReason, message: string): void => {
48
+ if (!settled) {
49
+ settled = true
50
+ clearTimeout(timer)
51
+ script.remove()
52
+ reject(new CaptchaLoadError(reason, message))
53
+ }
54
+ }
55
+ timer = setTimeout(() => { fail('timeout', 'reCAPTCHA did not become ready in time') }, loadTimeout)
56
+
57
+ script.addEventListener('error', () => { fail('load', 'reCAPTCHA failed to load') })
58
+ script.addEventListener('load', () => {
59
+ const grecaptcha = host.grecaptcha
60
+ if (grecaptcha == null || typeof grecaptcha.ready !== 'function') {
61
+ fail('unavailable', 'reCAPTCHA loaded without its API')
62
+ return
63
+ }
64
+ grecaptcha.ready(() => {
65
+ if (!settled) {
66
+ settled = true
67
+ clearTimeout(timer)
68
+ resolve(host.grecaptcha ?? grecaptcha)
69
+ }
70
+ })
71
+ })
72
+
73
+ script.src = `${scriptUrl}${scriptUrl.includes('?') ? '&' : '?'}render=${encodeURIComponent(siteKey)}`
74
+ script.async = true
75
+ script.setAttribute(RECAPTCHA_SCRIPT_ATTRIBUTE, siteKey)
76
+ if (hideBadge) {
77
+ addBadgeStyle(page)
78
+ }
79
+ page.head.appendChild(script)
80
+ })
81
+
82
+ const readyOf = (siteKey: string): Promise<Grecaptcha> => {
83
+ const known = loads.get(siteKey)
84
+ if (known != null) {
85
+ return known
86
+ }
87
+ const loading = inject(siteKey)
88
+ loads.set(siteKey, loading)
89
+ loading.catch(() => { loads.delete(siteKey) })
90
+
91
+ return loading
92
+ }
93
+
94
+ const prepare: RecaptchaLoader['prepare'] = async siteKey => {
95
+ await readyOf(siteKey)
96
+ }
97
+
98
+ const token: RecaptchaLoader['token'] = async (siteKey, action) => {
99
+ const grecaptcha = await readyOf(siteKey)
100
+ let timer: ReturnType<typeof setTimeout> | undefined
101
+ try {
102
+ const value = await Promise.race([
103
+ Promise.resolve(grecaptcha.execute(siteKey, { action })),
104
+ new Promise<never>((_, reject) => {
105
+ timer = setTimeout(() => { reject(new Error('reCAPTCHA execute timed out')) }, executeTimeout)
106
+ }),
107
+ ])
108
+ if (typeof value !== 'string' || value === '') {
109
+ throw new Error('reCAPTCHA gave no token')
110
+ }
111
+ return value
112
+ } catch (error) {
113
+ throw new CaptchaLoadError('execute', `reCAPTCHA refused: ${String(error)}`, { cause: error })
114
+ } finally {
115
+ clearTimeout(timer)
116
+ }
117
+ }
118
+
119
+ return { prepare, token }
120
+ }
121
+
122
+ /** The shared loader of a page: one script per site key across every caller. */
123
+ export const recaptchaLoader = createRecaptchaLoader()
@@ -0,0 +1,17 @@
1
+ import ReCAPTCHA from 'react-google-recaptcha'
2
+ import type { CaptchaWidget } from '@owlmeans/web-captcha/react'
3
+
4
+ /**
5
+ * Google's reCAPTCHA v2 checkbox as a `@owlmeans/web-captcha` widget: give it to the client
6
+ * (`appendRecaptchaClient({ widget: RecaptchaCheckbox })`) and a panel's captcha sign-in renders it.
7
+ * Needs a v2 (checkbox) site key; an expired token is reported as `null`.
8
+ */
9
+ export const RecaptchaCheckbox: CaptchaWidget = ({ siteKey, onToken, onReady, onError, language }) =>
10
+ <ReCAPTCHA
11
+ sitekey={siteKey}
12
+ onChange={onToken}
13
+ onExpired={() => { onToken(null) }}
14
+ onErrored={() => { onError?.(new Error('reCAPTCHA could not load')) }}
15
+ asyncScriptOnLoad={() => { onReady?.() }}
16
+ {...(language != null ? { hl: language } : {})}
17
+ />
package/src/react.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './react/checkbox.js'
package/src/types.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { CaptchaClient } from '@owlmeans/web-captcha'
2
+
3
+ /** The part of Google's `grecaptcha` (v3, `render=<site key>`) the loader uses. */
4
+ export interface Grecaptcha {
5
+ ready: (callback: () => void) => void
6
+ execute: (siteKey: string, options: { action: string }) => PromiseLike<string>
7
+ }
8
+
9
+ /** The window as the loader reads it: only Google's global. */
10
+ export interface RecaptchaWindow {
11
+ grecaptcha?: Grecaptcha
12
+ }
13
+
14
+ /** The document as the loader uses it: one script and one style appended to its head. */
15
+ export interface RecaptchaDocument extends Pick<Document, 'createElement' | 'querySelector' | 'head'> {}
16
+
17
+ export interface RecaptchaLoaderOptions {
18
+ /** Add the document style that hides Google's badge. Default `true`. */
19
+ hideBadge?: boolean
20
+ /** Milliseconds the script may take to become ready. Default `RECAPTCHA_LOAD_TIMEOUT`. */
21
+ loadTimeout?: number
22
+ /** Milliseconds one `execute` may take. Default `RECAPTCHA_EXECUTE_TIMEOUT`. */
23
+ executeTimeout?: number
24
+ /** The script address `?render=<site key>` is added to. Default `RECAPTCHA_SCRIPT_URL`. */
25
+ scriptUrl?: string
26
+ /** The page to load into. Default: the global `document`, read at call time. */
27
+ document?: RecaptchaDocument
28
+ /** Where Google's global appears. Default: the global `window`, read at call time. */
29
+ window?: RecaptchaWindow
30
+ }
31
+
32
+ /** Google's reCAPTCHA v3, loaded on first use — never at import. */
33
+ export interface RecaptchaLoader {
34
+ /**
35
+ * Inject `api.js?render=<siteKey>` once per key (and, unless disabled, the document style that
36
+ * hides Google's badge); resolves once `grecaptcha` is ready. A failure is forgotten, so the next
37
+ * call injects again.
38
+ *
39
+ * @throws {CaptchaLoadError} `load`, `timeout` or `unavailable`.
40
+ */
41
+ prepare: (siteKey: string) => Promise<void>
42
+ /**
43
+ * A fresh token for `action`, loading the script first when needed.
44
+ *
45
+ * @throws {CaptchaLoadError} what `prepare` throws, or `execute` when Google gives no token in time.
46
+ */
47
+ token: (siteKey: string, action: string) => Promise<string>
48
+ }
49
+
50
+ export interface RecaptchaClientOptions<W = unknown> {
51
+ /** The loader the client runs on. Default: the page's shared `recaptchaLoader`. */
52
+ loader?: RecaptchaLoader
53
+ /** An interactive widget for a page that renders one — `RecaptchaCheckbox` of `./react`. */
54
+ widget?: W
55
+ /** The client config record holding the site key. Default `CMOD_RECAPTCHA`. */
56
+ siteKeyRecord?: string
57
+ }
58
+
59
+ /** The reCAPTCHA client of `@owlmeans/web-captcha`. */
60
+ export interface RecaptchaClient<W = unknown> extends CaptchaClient<W> {}
@@ -0,0 +1,63 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { captchaClients, captchaNoticeHelper, createCaptchaClients } from '@owlmeans/web-captcha'
3
+ import { appendRecaptchaClient } from '../src/append.js'
4
+ import { makeRecaptchaClient } from '../src/client.js'
5
+ import { CMOD_RECAPTCHA, RECAPTCHA_PRIVACY_URL, RECAPTCHA_PROVIDER, RECAPTCHA_TERMS_URL, RECAPTCHA_TEXTS } from '../src/consts.js'
6
+ import { createRecaptchaLoader } from '../src/loader.js'
7
+ import { makeTestPage } from './context.js'
8
+
9
+ /** The eight languages of OwlMeans sign-in. */
10
+ const LANGUAGES = ['en', 'pl', 'ru', 'be', 'uk', 'es', 'de', 'fr']
11
+
12
+ const placeholders = (text: string): string[] => [...text.matchAll(/\{\{\s*([\w-]+)\s*\}\}/g)].map(m => m[1]).sort()
13
+
14
+ describe('@owlmeans/web-captcha-recaptcha — the client', () => {
15
+ test('is the recaptcha provider\'s client: tokens through the v3 loader, the site key record named', async () => {
16
+ const page = makeTestPage()
17
+ const client = makeRecaptchaClient({ loader: createRecaptchaLoader({ document: page.document, window: page.window }) })
18
+
19
+ expect(client.id).toBe(RECAPTCHA_PROVIDER)
20
+ expect(RECAPTCHA_PROVIDER).toBe('recaptcha')
21
+ expect(client.siteKeyRecord).toBe(CMOD_RECAPTCHA)
22
+ expect(CMOD_RECAPTCHA).toBe('_client-external:re-captcha')
23
+ expect(client.widget).toBeUndefined()
24
+
25
+ const loaded = client.load('k')
26
+ page.arrive(page.scripts()[0])
27
+ await loaded
28
+ expect(await client.execute('k', 'inquiry')).toBe('token:k:inquiry')
29
+ })
30
+
31
+ test('registers in the page\'s clients — or the registry given — explicitly, never on import', () => {
32
+ expect(captchaClients.list()).toEqual([])
33
+
34
+ const clients = createCaptchaClients()
35
+ const widget = () => null
36
+ const client = appendRecaptchaClient({ widget }, clients)
37
+ expect(clients.get(RECAPTCHA_PROVIDER)).toBe(client)
38
+ expect(client.widget).toBe(widget)
39
+ expect(captchaClients.list()).toEqual([])
40
+ })
41
+
42
+ test('ships Google\'s notice in the eight languages: the same placeholders, both links, none empty', () => {
43
+ expect(Object.keys(RECAPTCHA_TEXTS).sort()).toEqual([...LANGUAGES].sort())
44
+ for (const language of LANGUAGES) {
45
+ const texts = RECAPTCHA_TEXTS[language]
46
+ expect([language, Object.keys(texts).sort()]).toEqual([language, ['notice', 'privacy', 'terms']])
47
+ expect(placeholders(texts.notice)).toEqual(['privacy', 'terms'])
48
+ for (const text of Object.values(texts)) {
49
+ expect(text.trim()).not.toBe('')
50
+ }
51
+ }
52
+
53
+ expect(captchaNoticeHelper.noticeOf(makeRecaptchaClient(), 'de-AT')).toEqual({
54
+ sentence: RECAPTCHA_TEXTS.de.notice,
55
+ links: {
56
+ privacy: { text: 'Datenschutzerklärung', href: RECAPTCHA_PRIVACY_URL },
57
+ terms: { text: 'Nutzungsbedingungen', href: RECAPTCHA_TERMS_URL },
58
+ },
59
+ })
60
+ expect(captchaNoticeHelper.noticeOf(makeRecaptchaClient(), 'it')?.sentence)
61
+ .toBe('This site is protected by reCAPTCHA and the Google {{privacy}} and {{terms}} apply.')
62
+ })
63
+ })
@@ -0,0 +1,73 @@
1
+ import type { Grecaptcha, RecaptchaDocument, RecaptchaWindow } from '../src/types.js'
2
+
3
+ /** An element as the loader uses it: attributes, listeners, `src`/`async`/`textContent`, `remove`. */
4
+ export interface PageElement {
5
+ tag: string
6
+ attributes: Record<string, string>
7
+ src?: string
8
+ async?: boolean
9
+ textContent?: string | null
10
+ removed: boolean
11
+ setAttribute: (name: string, value: string) => void
12
+ addEventListener: (type: string, listener: () => void) => void
13
+ remove: () => void
14
+ /** Run the listeners of `type`, as the browser would. */
15
+ fire: (type: string) => void
16
+ }
17
+
18
+ export interface TestPage {
19
+ document: RecaptchaDocument
20
+ window: RecaptchaWindow
21
+ /** What the loader appended to the head, in order (removed ones included, flagged). */
22
+ head: PageElement[]
23
+ /** The scripts still in the head. */
24
+ scripts: () => PageElement[]
25
+ /** Google's script arrives: `grecaptcha` (ready at once) is installed and `load` fires. */
26
+ arrive: (script: PageElement, grecaptcha?: Grecaptcha | null) => void
27
+ }
28
+
29
+ const makeElement = (tag: string): PageElement => {
30
+ const listeners: Record<string, (() => void)[]> = {}
31
+ const element: PageElement = {
32
+ tag,
33
+ attributes: {},
34
+ removed: false,
35
+ setAttribute: (name, value) => { element.attributes[name] = value },
36
+ addEventListener: (type, listener) => { (listeners[type] ??= []).push(listener) },
37
+ remove: () => { element.removed = true },
38
+ fire: type => { (listeners[type] ?? []).forEach(listener => listener()) },
39
+ }
40
+
41
+ return element
42
+ }
43
+
44
+ /** A page stand-in (document + window) for the loader's pure logic — no browser. */
45
+ export const makeTestPage = (): TestPage => {
46
+ const head: PageElement[] = []
47
+ const window: RecaptchaWindow = {}
48
+
49
+ const querySelector = (selector: string): PageElement | null => {
50
+ const [, tag, attribute] = /^(\w+)\[([^\]=]+)\]$/.exec(selector) ?? []
51
+
52
+ return head.find(element => !element.removed && element.tag === tag && attribute in element.attributes) ?? null
53
+ }
54
+
55
+ const document = {
56
+ head: { appendChild: (element: PageElement) => { head.push(element); return element } },
57
+ createElement: makeElement,
58
+ querySelector,
59
+ } as unknown as RecaptchaDocument
60
+
61
+ const arrive: TestPage['arrive'] = (script, grecaptcha) => {
62
+ window.grecaptcha = grecaptcha === null ? undefined : grecaptcha ?? {
63
+ ready: callback => { callback() },
64
+ execute: async (siteKey, { action }) => `token:${siteKey}:${action}`,
65
+ }
66
+ script.fire('load')
67
+ }
68
+
69
+ return {
70
+ document, window, head, arrive,
71
+ scripts: () => head.filter(element => element.tag === 'script' && !element.removed),
72
+ }
73
+ }
@@ -0,0 +1,120 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { CaptchaLoadError } from '@owlmeans/web-captcha'
3
+ import {
4
+ RECAPTCHA_BADGE_CSS, RECAPTCHA_EXECUTE_TIMEOUT, RECAPTCHA_LOAD_TIMEOUT, RECAPTCHA_SCRIPT_ATTRIBUTE,
5
+ RECAPTCHA_SCRIPT_URL, RECAPTCHA_STYLE_ATTRIBUTE,
6
+ } from '../src/consts.js'
7
+ import { createRecaptchaLoader, recaptchaLoader } from '../src/loader.js'
8
+ import type { RecaptchaLoaderOptions } from '../src/types.js'
9
+ import { makeTestPage } from './context.js'
10
+
11
+ const loaderOn = (page = makeTestPage(), options: RecaptchaLoaderOptions = {}) =>
12
+ ({ page, loader: createRecaptchaLoader({ document: page.document, window: page.window, ...options }) })
13
+
14
+ const failure = async (promise: Promise<unknown>): Promise<CaptchaLoadError> => {
15
+ try {
16
+ await promise
17
+ } catch (error) {
18
+ expect(error).toBeInstanceOf(CaptchaLoadError)
19
+ return error as CaptchaLoadError
20
+ }
21
+ throw new Error('expected a failure')
22
+ }
23
+
24
+ describe('@owlmeans/web-captcha-recaptcha — loader', () => {
25
+ test('keeps Google\'s script, the badge rule and the timeouts', () => {
26
+ expect(RECAPTCHA_SCRIPT_URL).toBe('https://www.google.com/recaptcha/api.js')
27
+ expect(RECAPTCHA_BADGE_CSS).toBe('.grecaptcha-badge{visibility:hidden}')
28
+ expect(RECAPTCHA_LOAD_TIMEOUT).toBe(15_000)
29
+ expect(RECAPTCHA_EXECUTE_TIMEOUT).toBe(20_000)
30
+ })
31
+
32
+ test('injects one script per site key, with the badge style once, and resolves when grecaptcha is ready', async () => {
33
+ const { page, loader } = loaderOn()
34
+
35
+ const first = loader.prepare('key one')
36
+ const again = loader.prepare('key one')
37
+ expect(page.scripts()).toHaveLength(1)
38
+ const [script] = page.scripts()
39
+ expect(script.src).toBe(`${RECAPTCHA_SCRIPT_URL}?render=key%20one`)
40
+ expect(script.async).toBe(true)
41
+ expect(script.attributes[RECAPTCHA_SCRIPT_ATTRIBUTE]).toBe('key one')
42
+
43
+ page.arrive(script)
44
+ await Promise.all([first, again])
45
+ await loader.prepare('key one')
46
+ expect(page.scripts()).toHaveLength(1)
47
+
48
+ const second = loader.prepare('key-two')
49
+ page.arrive(page.scripts()[1])
50
+ await second
51
+ expect(page.scripts()).toHaveLength(2)
52
+ const styles = page.head.filter(element => element.tag === 'style')
53
+ expect(styles).toHaveLength(1)
54
+ expect(styles[0].attributes).toHaveProperty(RECAPTCHA_STYLE_ATTRIBUTE)
55
+ expect(styles[0].textContent).toBe(RECAPTCHA_BADGE_CSS)
56
+ })
57
+
58
+ test('a load that fails or never becomes ready is refused with its reason, and forgotten', async () => {
59
+ const { page, loader } = loaderOn(makeTestPage(), { loadTimeout: 5 })
60
+
61
+ const timedOut = await failure(loader.prepare('k'))
62
+ expect(timedOut.reason).toBe('timeout')
63
+ expect(page.scripts()).toHaveLength(0)
64
+
65
+ const erroring = loader.prepare('k')
66
+ page.scripts()[0].fire('error')
67
+ expect((await failure(erroring)).reason).toBe('load')
68
+
69
+ const bare = loader.prepare('k')
70
+ page.arrive(page.scripts()[0], null)
71
+ expect((await failure(bare)).reason).toBe('unavailable')
72
+
73
+ const retried = loader.prepare('k')
74
+ page.arrive(page.scripts()[0])
75
+ await retried
76
+ expect(page.head.filter(element => element.tag === 'script')).toHaveLength(4)
77
+ expect(page.scripts()).toHaveLength(1)
78
+ })
79
+
80
+ test('without a page nothing is touched at import, and a call is unavailable', async () => {
81
+ expect(typeof (globalThis as { document?: unknown }).document).toBe('undefined')
82
+ expect((await failure(recaptchaLoader.prepare('k'))).reason).toBe('unavailable')
83
+ expect((await failure(createRecaptchaLoader().token('k', 'a'))).reason).toBe('unavailable')
84
+ })
85
+
86
+ test('hideBadge: false adds no document style; a script url with a query keeps it', async () => {
87
+ const { page, loader } = loaderOn(makeTestPage(), { hideBadge: false, scriptUrl: 'https://www.recaptcha.net/recaptcha/api.js?hl=pl' })
88
+
89
+ const ready = loader.prepare('k')
90
+ page.arrive(page.scripts()[0])
91
+ await ready
92
+ expect(page.head.map(element => element.tag)).toEqual(['script'])
93
+ expect(page.scripts()[0].src).toBe('https://www.recaptcha.net/recaptcha/api.js?hl=pl&render=k')
94
+ })
95
+ })
96
+
97
+ describe('@owlmeans/web-captcha-recaptcha — token', () => {
98
+ test('loads on demand and executes the action', async () => {
99
+ const { page, loader } = loaderOn()
100
+
101
+ const token = loader.token('k', 'email_pin')
102
+ page.arrive(page.scripts()[0])
103
+ expect(await token).toBe('token:k:email_pin')
104
+ expect(await loader.token('k', 'email_password')).toBe('token:k:email_password')
105
+ expect(page.scripts()).toHaveLength(1)
106
+ })
107
+
108
+ test('no token, a throwing or a hanging execute is an execute failure', async () => {
109
+ for (const execute of [
110
+ async () => '',
111
+ () => { throw new Error('denied') },
112
+ () => new Promise<string>(() => {}),
113
+ ]) {
114
+ const { page, loader } = loaderOn(makeTestPage(), { executeTimeout: 5 })
115
+ const token = loader.token('k', 'email_pin')
116
+ page.arrive(page.scripts()[0], { ready: callback => { callback() }, execute })
117
+ expect((await failure(token)).reason).toBe('execute')
118
+ }
119
+ })
120
+ })