@reblu/site-next 1.10.0 → 1.12.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/CHANGELOG.md +63 -0
- package/README.md +134 -19
- package/dist/recaptcha-provider.cjs +86 -0
- package/dist/recaptcha-provider.cjs.map +1 -0
- package/dist/recaptcha-provider.d.cts +41 -0
- package/dist/recaptcha-provider.d.ts +41 -0
- package/dist/recaptcha-provider.js +68 -0
- package/dist/recaptcha-provider.js.map +1 -0
- package/dist/recaptcha.cjs.map +1 -1
- package/dist/recaptcha.d.cts +33 -4
- package/dist/recaptcha.d.ts +33 -4
- package/dist/recaptcha.js.map +1 -1
- package/dist/shop-server.cjs +198 -0
- package/dist/shop-server.cjs.map +1 -0
- package/dist/shop-server.d.cts +106 -0
- package/dist/shop-server.d.ts +106 -0
- package/dist/shop-server.js +167 -0
- package/dist/shop-server.js.map +1 -0
- package/dist/shop.cjs +212 -0
- package/dist/shop.cjs.map +1 -0
- package/dist/shop.d.cts +20 -0
- package/dist/shop.d.ts +20 -0
- package/dist/shop.js +181 -0
- package/dist/shop.js.map +1 -0
- package/package.json +40 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/recaptcha-provider.tsx","../src/recaptcha.ts"],"sourcesContent":["'use client'\n\n/**\n * `@reblu/site-next/recaptcha-provider` — the FIX for REB-793.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * THE BUG THIS EXISTS TO CLOSE\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `deferredRecaptchaKey` (`./recaptcha`, REB-588) returns `''` until `armed`,\n * on the documented claim that `<GoogleReCaptchaProvider reCaptchaKey={...}>`\n * swaps the key in later without remounting. That claim is only half true.\n * Verified directly in `react-google-recaptcha-v3@1.11.0`'s own dist\n * (`dist/react-google-recaptcha-v3.esm.js`):\n *\n * var x = useRef(reCaptchaKey) // captured ONCE, on first mount\n * …\n * window[onLoadCallbackName] = () => { x.current = grecaptcha.render(…) }\n * …\n * executeRecaptcha = () => grecaptcha.execute(x.current, { action })\n *\n * `x.current` is reassigned ONLY inside the `onLoadCallbackName` global the\n * library wires into the script URL's `&onload=` query param — and that param\n * is only added when `render === 'explicit'`, i.e. when a visible widget\n * `container` is configured. Invisible v3 (no `container`, the ONLY mode this\n * SDK or any Reblu SITE uses) never sets that param, so `x.current` never\n * updates: every `executeRecaptcha()` call keeps sending the EMPTY first-mount\n * key to `grecaptcha.execute('', { action })`, which throws, which the SITE's\n * submit handler swallows into \"reCAPTCHA no está disponible\" — no token,\n * every submission dead on arrival. Found 29-Sep in the first real\n * contact-form test on dermamedicin preprod: zero requests ever reached\n * `/api/site/contact-form`.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * THE FIX — REMOUNT THE VENDOR, NOT THE SITE'S FORM\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `useRef`'s initial value is captured on FIRST MOUNT and nothing short of\n * unmounting-and-remounting the element changes that — the vendor gives us no\n * other hook. So the element that eventually loads Google's script must never\n * have been mounted with any key other than the real one: `key={reCaptchaKey}`\n * on `<GoogleReCaptchaProvider>` does exactly that. React treats a `key`\n * change as a different element identity and discards the old subtree instead\n * of re-rendering it, so arming does not swap a prop on a live instance — it\n * unmounts the empty-key instance (which never loaded anything, so there is\n * nothing to tear down) and mounts a BRAND NEW one whose `useRef` captures the\n * real key from its very first render.\n *\n * A first version of this fix put the SITE's own `children` directly inside\n * that keyed element. It closes the ref bug, but it also means the SITE's\n * form — every typed field, and any in-flight submit closure reading\n * `executeRecaptcha` — gets unmounted and remounted at the exact moment arming\n * happens. For the common case (arm on first focus, before any text exists)\n * that only costs a moment of focus. For demo-site's actual \"visitor tabs\n * straight to submit\" fallback (`waitForRecaptchaReady` in\n * `contact-form.section.tsx`) it is fatal: arming happens FROM INSIDE the\n * form's own submit handler, so remounting the form destroys the very\n * component instance that is awaiting the result — the typed values vanish\n * and the poll never resolves, reproduced by\n * `contact-form.section.recaptcha-submit.test.tsx` going red under that\n * design.\n *\n * So the vendor `<GoogleReCaptchaProvider>` here wraps ONLY an invisible\n * bridge component, never the SITE's `children`. The bridge reads the\n * vendor's `useGoogleReCaptcha()` — correct by construction, because it lives\n * inside the freshly, correctly keyed instance — and republishes\n * `executeRecaptcha` into `DeferredRecaptchaContext`, a context on a STABLE\n * element that is never keyed and never remounts. `children` renders as a\n * SIBLING of the vendor provider, under that stable context, and consumes the\n * function via `useDeferredRecaptcha()` (this module's own replacement for\n * the vendor's `useGoogleReCaptcha()`). Arming remounts the invisible bridge;\n * it never touches the SITE's form.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHY THIS IS A SEPARATE SUBPATH, NOT PART OF `./recaptcha`\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `./recaptcha` is guarded by `tests/recaptcha-subpath-isolation.test.ts` to\n * import NOTHING — not React, not `react-google-recaptcha-v3` — so a Server\n * Component can call `resolveContactFormAvailability` without paying for\n * Google's loader library. This component unavoidably imports both. Same R4\n * rule as `auth`/`academy`/`consent`: a `'use client'` directive is only\n * preserved by esbuild when the ENTRY FILE itself declares it, never when\n * merely re-exported — so this file is tsup's OWN entry (`recaptcha-provider`\n * in `../tsup.config.ts`), not folded into `./recaptcha` or the root barrel.\n *\n * `react-google-recaptcha-v3` stays the consuming SITE's OWN dependency\n * (an optional `peerDependencies` entry here, exactly as `./recaptcha`'s\n * README section already promises) — this package never bundles it.\n */\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ComponentProps,\n type ReactNode,\n} from 'react'\nimport { GoogleReCaptchaProvider, useGoogleReCaptcha } from 'react-google-recaptcha-v3'\n\nimport { deferredRecaptchaKey } from './recaptcha'\n\n/** The one thing a SITE needs, in the same shape the vendor's own hook returns it. */\nexport interface DeferredRecaptchaContextValue {\n /** `undefined` until Google's script has loaded under the ARMED key. */\n executeRecaptcha: ((action?: string) => Promise<string>) | undefined\n}\n\nconst UNARMED: DeferredRecaptchaContextValue = { executeRecaptcha: undefined }\n\nconst DeferredRecaptchaContext = createContext<DeferredRecaptchaContextValue>(UNARMED)\n\n/**\n * Lives INSIDE the keyed vendor provider — the only place the vendor's own\n * `executeRecaptcha` is ever correct — and republishes it to the stable\n * context above. Renders nothing; it is pure plumbing.\n */\nfunction ExecuteBridge({\n onChange,\n}: {\n onChange: (fn: DeferredRecaptchaContextValue['executeRecaptcha']) => void\n}) {\n const { executeRecaptcha } = useGoogleReCaptcha()\n useEffect(() => {\n onChange(executeRecaptcha)\n }, [executeRecaptcha, onChange])\n return null\n}\n\ntype ProviderPassthroughProps = Omit<\n ComponentProps<typeof GoogleReCaptchaProvider>,\n 'reCaptchaKey' | 'children'\n>\n\nexport interface DeferredRecaptchaProviderProps extends ProviderPassthroughProps {\n /** The tenant's public reCAPTCHA site key — `resolveContactFormAvailability`'s `recaptchaSiteKey`. */\n siteKey: string\n /** Whether the visitor has interacted with the form yet (REB-588 arming signal). */\n armed: boolean\n children: ReactNode\n}\n\n/**\n * Drop-in replacement for wiring `deferredRecaptchaKey` directly into\n * `<GoogleReCaptchaProvider reCaptchaKey={...}>` — see the module docs above\n * for why that direct wiring never mints a real token. Pair with\n * `useDeferredRecaptcha()` instead of the vendor's `useGoogleReCaptcha()`.\n *\n * ```tsx\n * <DeferredRecaptchaProvider siteKey={siteKey} armed={armed}>\n * <form onFocusCapture={arm} onPointerDown={arm}>…</form>\n * </DeferredRecaptchaProvider>\n * ```\n */\nexport function DeferredRecaptchaProvider({\n siteKey,\n armed,\n children,\n ...providerProps\n}: DeferredRecaptchaProviderProps) {\n const reCaptchaKey = deferredRecaptchaKey(siteKey, armed)\n const [executeRecaptcha, setExecuteRecaptcha] =\n useState<DeferredRecaptchaContextValue['executeRecaptcha']>(undefined)\n\n // No separate \"reset to undefined on key change\" effect is needed here,\n // and deliberately so: `reCaptchaKey` changing remounts `ExecuteBridge`\n // (it lives inside the keyed `GoogleReCaptchaProvider`), and a FRESH bridge\n // instance's very first effect run already reports the fresh instance's\n // own `executeRecaptcha` — `undefined` until that instance's own script has\n // loaded, never a value carried over from the instance that just unmounted.\n // An extra reset effect on THIS component was tried and reverted: as the\n // parent, its effects fire AFTER its children's on the same commit, so it\n // clobbered the bridge's own report back to `undefined` on every mount —\n // caught by `contact-form.section.test.tsx`, whose mocked\n // `useGoogleReCaptcha()` reports a working function synchronously.\n const handleChange = useCallback(\n (fn: DeferredRecaptchaContextValue['executeRecaptcha']) => setExecuteRecaptcha(() => fn),\n [],\n )\n\n // Memoized so every consumer of `useDeferredRecaptcha()` re-renders only\n // when `executeRecaptcha` itself actually changes, not on every render of\n // this provider (e.g. from an unrelated `providerProps` change).\n const contextValue = useMemo(() => ({ executeRecaptcha }), [executeRecaptcha])\n\n return (\n <DeferredRecaptchaContext.Provider value={contextValue}>\n <GoogleReCaptchaProvider key={reCaptchaKey} reCaptchaKey={reCaptchaKey} {...providerProps}>\n <ExecuteBridge onChange={handleChange} />\n </GoogleReCaptchaProvider>\n {children}\n </DeferredRecaptchaContext.Provider>\n )\n}\n\n/**\n * The SITE's replacement for `react-google-recaptcha-v3`'s own\n * `useGoogleReCaptcha()` when the form is wrapped in\n * `<DeferredRecaptchaProvider>`. Same shape (`{ executeRecaptcha }`), but\n * reads the STABLE context republished by `ExecuteBridge`, which never\n * remounts on arm — unlike the vendor's own context, which lives on the\n * element `DeferredRecaptchaProvider` deliberately keys and remounts.\n */\nexport function useDeferredRecaptcha(): DeferredRecaptchaContextValue {\n return useContext(DeferredRecaptchaContext)\n}\n","/**\n * reCAPTCHA v3 — the SITE's half of the contract (REB-588).\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHICH HALF LIVES WHERE, AND WHY\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * reCAPTCHA is two secrets and two steps, and they are deliberately split across\n * a trust boundary:\n *\n * SITE KEY — public by design. It ships to the browser inside the script URL,\n * so the tenant serves it from `/api/site/analytics`. This module\n * handles it.\n * SECRET — never leaves base-api. It is stored per tenant in\n * `site_integration_config.recaptchaSecretKey` and read only by\n * `serverCaptchaVerify` when `POST /api/site/contact-form` runs.\n *\n * **Nothing in this module, in this package, or anywhere in the `@reblu/site-*`\n * SDK ever sees the secret, and nothing here calls Google's `siteverify`.** A\n * SITE holding the secret would be a SITE that could be tricked into approving\n * its own tokens, and a distributable SDK is the worst possible place to put a\n * credential. Verification is base-api's job and already works: the SITE mints a\n * token, posts it as `ContactFormInput.captcha`, and base-api decides.\n *\n * That is also why this module is NOT \"reCAPTCHA support\" in the round. It is\n * the three decisions every SITE was otherwise making alone and differently:\n * which action to name, whether a form may be shown at all, and when Google's\n * script is allowed to load.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHY IT IS IN THE SDK AT ALL\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * Because it was already being written four times. `apps/base-api`,\n * `apps/demo-site` and the external `reblu-site-dermamedicin` each grew their\n * own copy of this flow, and they had already drifted — different action\n * strings, different mount timing, a retry loop in one of them. A score that\n * reCAPTCHA reports per action is not comparable across SITEs that name the\n * action differently, and a defect fixed in one copy stays live in the other\n * two. The SDK is where a decision gets made once.\n *\n * This module has ZERO runtime dependencies and imports nothing — not React, not\n * `next`, not `react-google-recaptcha-v3`, not `@reblu/site-ui`. It is pure\n * functions over plain data, callable from a Server Component deciding whether\n * to render a form and from the Client Component that renders it. The subpath is\n * kept dependency-free by `tests/recaptcha-subpath-isolation.test.ts`.\n */\n\nimport type { Analytics, ContactFormMode } from '@reblu/site-contracts'\n\n/**\n * The action name every Reblu SITE mints its contact-form token under.\n *\n * reCAPTCHA v3 scores PER ACTION, and a score is only interpretable against a\n * stable one: Google's own admin console charts each action separately, and a\n * threshold tuned on one action says nothing about another. Two SITEs calling\n * `executeRecaptcha('submit_form')` and `executeRecaptcha('contact_form')` are\n * building two unrelated score histories for the same feature — which is exactly\n * the state the repo was in before this constant existed.\n *\n * `contact_form` over `submit_form` because it names the form, not the verb;\n * a second protected form would need its own action, and `submit_form` would\n * have nothing left to call it.\n *\n * ── WHAT THIS CONSTANT DOES **NOT** BUY, STATED PLAINLY ──\n *\n * It buys comparable scores. It does NOT bind a token to this form, because\n * `serverCaptchaVerify` in base-api checks only `success` and `score`, and never\n * reads the `action` field Google returns. A token minted for any other action\n * on the same site verifies here exactly as well. Making the action load-bearing\n * requires base-api to assert `action === RECAPTCHA_ACTION` on verify; until it\n * does, do not read this constant as a security control.\n */\nexport const RECAPTCHA_ACTION = 'contact_form'\n\n/**\n * The shape a site key must have before this SDK will hand it to Google.\n *\n * ── WHAT THIS IS, AND EMPHATICALLY WHAT IT IS NOT ──\n *\n * It is a SINK-SAFETY guard, not a guess at Google's key format. The key is\n * interpolated into the loader's script URL as a query parameter, so what\n * matters here is that it cannot carry a space, a quote, a newline, an `&`, or a\n * `#` — characters that make a URL mean something other than what was intended.\n * The base64url alphabet Google actually issues from (`A-Z a-z 0-9 - _`) is a\n * strict subset of \"safe\", so a real key passes by construction.\n *\n * The length bounds are deliberately far wider than any key Google issues\n * (theirs are 40 characters). A bound tight enough to be a real format check\n * would be a bound tight enough to take a WORKING tenant's contact form offline\n * the day Google changes its key length — which is strictly worse than the\n * malformed key it was meant to catch. If you are tempted to tighten this,\n * the thing to tighten is the nexus write path, where an owner can still see\n * and fix the error, not this read path where they cannot.\n *\n * ── WHY THE SDK RE-VALIDATES AT ALL ──\n *\n * Same reason `@reblu/site-next/analytics` re-checks `gaId` and `clarityId`\n * (REB-617): base-api is not the only thing a SITE ever talks to, and the layer\n * that owns the value is not the layer that suffers from it being wrong. As of\n * REB-588 this column has NO validation anywhere — not in the nexus form, not on\n * the way out of `/api/site/analytics`, not in the response contract, which is\n * the one asymmetry `gaId`/`clarityId` do not share. Until that is fixed\n * upstream, this is the only guard between a mistyped key and a contact form\n * that renders, looks live, and silently eats every enquiry.\n */\nexport const RECAPTCHA_SITE_KEY_PATTERN = /^[A-Za-z0-9_-]{16,128}$/\n\n/**\n * Whether `value` is a site key safe to put in the loader's script URL.\n *\n * Takes `unknown` on purpose: the value arrives over HTTP, so the contract's\n * `string | null` is a promise about the shape, not a guarantee about the bytes.\n */\nexport function isSafeRecaptchaSiteKey(value: unknown): value is string {\n return typeof value === 'string' && RECAPTCHA_SITE_KEY_PATTERN.test(value)\n}\n\n/**\n * The modes in which base-api will actually accept a submission.\n *\n * An ALLOW-LIST, never `mode !== 'DISABLED'`. The three differ only in what\n * base-api DOES with the payload — a row, a webhook, an email — and the SITE\n * must not care and must never learn the destination: a webhook URL or a Resend\n * key is a tenant secret with no business in a public site.\n *\n * The deny-list version of this is a real incident, not a hypothetical: a page\n * that hid the form on `DISABLED` and rendered it otherwise rendered it for\n * `NOT_CONFIGURED` too — which is what EVERY freshly provisioned tenant carries\n * until someone finishes the wizard (REB-586). A visitor typed out a medical\n * enquiry, pressed send, and got `503 Contact form is disabled`. They learned\n * the clinic could not be reached only after writing to it.\n */\nexport const CONTACT_FORM_OPERATIONAL_MODES = ['DB_ONLY', 'WEBHOOK', 'RESEND'] as const\n\n/** A mode in which the form may be shown. */\nexport type ContactFormOperationalMode = (typeof CONTACT_FORM_OPERATIONAL_MODES)[number]\n\n/**\n * The modes deliberately declined. A TYPE, never a value: the runtime must never\n * read it, because an allow-list must not be expressible as \"everything except\n * this list\", and this subpath's defining property is that it ships nothing it\n * does not need. It exists only to feed {@link ContactFormModeExhaustiveCheck}.\n */\ntype DeclinedMode = 'NOT_CONFIGURED' | 'DISABLED'\n\n/**\n * Compile-time exhaustiveness guard over `ContactFormMode`.\n *\n * `Missing` is constrained to `never` and DEFAULTS to the contract modes that\n * are neither accepted nor explicitly declined, so a default violating its own\n * constraint breaks the build the moment `@reblu/site-contracts` gains a mode.\n *\n * At runtime a new mode already fails closed, which is correct but SILENT — and\n * silence is how a tenant switches their form on in nexus and watches nothing\n * appear. This forces a human to make the call in a diff instead.\n *\n * Exported so it is never reported as an unused symbol.\n */\nexport type ContactFormModeExhaustiveCheck<\n Missing extends never = Exclude<ContactFormMode, ContactFormOperationalMode | DeclinedMode>,\n> = Missing\n\n/** Why the form is not being shown. Drives diagnostics, never visitor-facing copy. */\nexport type ContactFormUnavailableReason =\n /** The analytics read failed or was never made — no answer at all. */\n | 'unreadable'\n /** The tenant's mode is not one base-api accepts submissions in. */\n | 'mode-not-operational'\n /** Accepting mode, but no site key: the browser cannot mint a token. */\n | 'missing-recaptcha-key'\n /** A site key is present but cannot be a key — see {@link RECAPTCHA_SITE_KEY_PATTERN}. */\n | 'malformed-recaptcha-key'\n\nexport type ContactFormAvailability =\n /**\n * Confirmed: base-api accepts submissions AND a usable site key exists. The\n * key travels inside the `available` case on purpose — a component that has\n * proven the form may render should not have to re-read (and re-null-check)\n * the payload to find out what to render it WITH.\n */\n | { state: 'available'; mode: ContactFormOperationalMode; recaptchaSiteKey: string }\n | { state: 'unavailable'; reason: ContactFormUnavailableReason }\n\n/** Whitespace-only is absent — a key someone saved blank is not a key. */\nfunction trimmed(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const text = value.trim()\n return text.length > 0 ? text : null\n}\n\nfunction isOperationalMode(mode: unknown): mode is ContactFormOperationalMode {\n // Widened to `unknown` deliberately: see isSafeRecaptchaSiteKey. A base-api\n // newer than this SDK sends a string TypeScript has never heard of, and it\n // must fail closed rather than be assumed accepting.\n return (CONTACT_FORM_OPERATIONAL_MODES as readonly string[]).includes(mode as string)\n}\n\n/**\n * Resolve whether a contact form may be rendered for this tenant.\n *\n * We offer what we can CONFIRM, never what we have merely failed to disprove: an\n * unknown mode, a mode from a runtime newer than this build, and a config read\n * that threw all resolve to the same answer — no form. The page still shows the\n * phone, the email and the address, so a hidden form costs a visitor one extra\n * glance; a form that eats their message costs them the message.\n *\n * Order matters. The mode is checked BEFORE the key, because \"the tenant has not\n * switched the form on\" is the actionable half of a double failure — a site key\n * for a form nobody enabled is not the problem to fix first.\n */\nexport function resolveContactFormAvailability(\n analytics: Analytics | null | undefined,\n): ContactFormAvailability {\n if (!analytics) return { state: 'unavailable', reason: 'unreadable' }\n\n const mode = analytics.contactFormMode\n if (!isOperationalMode(mode)) return { state: 'unavailable', reason: 'mode-not-operational' }\n\n // `ContactFormInput.captcha` is REQUIRED and base-api verifies it, so an\n // accepting mode with no usable key is still a form whose every submission is\n // dead on arrival. \"Missing\" and \"malformed\" are separated because they call\n // for different fixes by different people: one owner never filled the field,\n // the other filled it with the wrong thing.\n const recaptchaSiteKey = trimmed(analytics.recaptchaSiteKey)\n if (!recaptchaSiteKey) return { state: 'unavailable', reason: 'missing-recaptcha-key' }\n if (!isSafeRecaptchaSiteKey(recaptchaSiteKey)) {\n return { state: 'unavailable', reason: 'malformed-recaptcha-key' }\n }\n\n return { state: 'available', mode, recaptchaSiteKey }\n}\n\n/** Narrowing helper — the single question a renderer should ask. */\nexport function isContactFormAvailable(\n availability: ContactFormAvailability,\n): availability is Extract<ContactFormAvailability, { state: 'available' }> {\n return availability.state === 'available'\n}\n\n/**\n * The key to hand `GoogleReCaptchaProvider` on this render — `''` until `armed`.\n *\n * @deprecated **Wiring this return value directly into\n * `<GoogleReCaptchaProvider reCaptchaKey={deferredRecaptchaKey(siteKey, armed)}>`\n * is the exact REB-793 bug**: `react-google-recaptcha-v3@1.11.0` captures\n * `reCaptchaKey` in a `useRef` on FIRST MOUNT and never re-reads the prop for\n * invisible v3 (no visible `container`), so `executeRecaptcha` keeps sending\n * the STALE `''` from before arming to `grecaptcha.execute` forever — the\n * script loads with the right key, but every token mint throws, and every\n * contact-form submission is silently dead on arrival. Verified on\n * dermamedicin preprod 29-Sep: zero requests ever reached\n * `/api/site/contact-form`. Use `DeferredRecaptchaProvider` from\n * `@reblu/site-next/recaptcha-provider` instead — it applies this exact same\n * value as BOTH the `key` and the `reCaptchaKey` prop, which forces a full\n * remount on arm instead of a prop swap, so the mounted instance's `useRef`\n * never sees any key but the real one. This function stays exported,\n * unchanged, because `DeferredRecaptchaProvider` calls it internally and\n * external SITEs may already depend on its signature for other purposes\n * (e.g. rendering their own diagnostics) — this is a documentation-only\n * deprecation, not a behavior or breaking change.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHAT THIS BUYS\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `GoogleReCaptchaProvider` loads Google's `api.js` the moment it MOUNTS. Mount\n * it with the form and every visitor who merely lands on the page to read the\n * phone number has contacted Google — on a clinic's contact page, a third-party\n * request nobody asked for, on a route whose whole subject is personal data.\n *\n * Arming on first interaction with the form (focus, first keystroke) means\n * Google is contacted only for a visitor who is actually about to submit, which\n * is the only visitor whose token is worth anything. It is a smaller page, a\n * faster one, and a materially smaller consent surface.\n *\n * **This is NOT a cookie-consent implementation.** Deferring the script narrows\n * the exposure; it does not gate it on a lawful basis. Full consent gating for\n * third parties is REB-642 and has its own owner.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * HOW, WITHOUT A HACK — MEASURED, NOT ASSUMED\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `react-google-recaptcha-v3` injects the script from an effect shaped\n *\n * useEffect(() => { if (reCaptchaKey) { …inject…; return cleanup } … },\n * [ …, reCaptchaKey, … ])\n *\n * Two facts fall out, and together they are the whole mechanism:\n *\n * 1. An EMPTY key mounts the provider and injects NOTHING.\n * 2. `reCaptchaKey` is a dependency, so swapping the real key in later re-runs\n * the effect and injects the script then.\n *\n * Crucially the provider element never leaves the tree, so its children are\n * never remounted merely because `reCaptchaKey` changed on a LIVE instance:\n * no imperative script injection, no reaching into the DOM, no fork.\n *\n * **This describes script LOADING only, not token MINTING.** REB-793 found\n * the gap: the same swapped prop that safely re-runs this effect is also\n * where `react-google-recaptcha-v3` caches `reCaptchaKey` in a `useRef` — set\n * once, on first mount, and (for invisible v3) never reassigned. The script\n * loads with the swapped-in real key; `executeRecaptcha` keeps sending the\n * key from BEFORE the swap. Wiring this function's return value straight\n * into `<GoogleReCaptchaProvider reCaptchaKey={...}>`, the pattern this\n * whole comment used to recommend, is exactly that bug — see the\n * `@deprecated` note above and `@reblu/site-next/recaptcha-provider`'s\n * `DeferredRecaptchaProvider`, which fixes it by forcing a real remount\n * instead of relying on this same prop swap.\n *\n * Both facts are pinned by `tests/recaptcha-deferred-oracle.test.tsx`, which\n * drives the REAL library and counts script tags in the DOM. They are claims\n * about someone else's code, so prose asserting them is not enough — if a future\n * version of the library injects eagerly, that test goes red and this whole\n * optimisation is known to be void.\n *\n * ── THE ONE COST, MEASURED ──\n *\n * On the empty-key render the library calls its own warn helper, which is\n * written inverted, so the warning fires in PRODUCTION and stays silent in\n * development. A visitor who opens devtools before touching a field sees one\n * `\"<GoogleReCaptchaProvider /> recaptcha key not provided\"`. Cosmetic console\n * noise, traded against a third-party request on every view of the page. Worth\n * it, and recorded here so the next reader knows it is expected.\n *\n * ── AND NO FALLBACK KEY, EVER ──\n *\n * `''` for a blank OR malformed key however armed. There is no hardcoded\n * fallback anywhere in this module, because a captcha key that is not the\n * tenant's fails Google's verification while LOOKING configured — converting a\n * visible gap an owner can fix in nexus into a silent one nobody can.\n * {@link resolveContactFormAvailability} hides the form in that case; this is\n * the second lock on the same door.\n */\nexport function deferredRecaptchaKey(siteKey: string, armed: boolean): string {\n if (!armed) return ''\n const key = trimmed(siteKey)\n return key && isSafeRecaptchaSiteKey(key) ? key : ''\n}\n"],"mappings":";;;AA0FA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,yBAAyB,0BAA0B;;;ACMrD,IAAM,6BAA6B;AAQnC,SAAS,uBAAuB,OAAiC;AACtE,SAAO,OAAO,UAAU,YAAY,2BAA2B,KAAK,KAAK;AAC3E;AAqEA,SAAS,QAAQ,OAA+B;AAC9C,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,OAAO,MAAM,KAAK;AACxB,SAAO,KAAK,SAAS,IAAI,OAAO;AAClC;AAkJO,SAAS,qBAAqB,SAAiB,OAAwB;AAC5E,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,MAAM,QAAQ,OAAO;AAC3B,SAAO,OAAO,uBAAuB,GAAG,IAAI,MAAM;AACpD;;;ADvJI,SAEI,KAFJ;AA9EJ,IAAM,UAAyC,EAAE,kBAAkB,OAAU;AAE7E,IAAM,2BAA2B,cAA6C,OAAO;AAOrF,SAAS,cAAc;AAAA,EACrB;AACF,GAEG;AACD,QAAM,EAAE,iBAAiB,IAAI,mBAAmB;AAChD,YAAU,MAAM;AACd,aAAS,gBAAgB;AAAA,EAC3B,GAAG,CAAC,kBAAkB,QAAQ,CAAC;AAC/B,SAAO;AACT;AA2BO,SAAS,0BAA0B;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAAmC;AACjC,QAAM,eAAe,qBAAqB,SAAS,KAAK;AACxD,QAAM,CAAC,kBAAkB,mBAAmB,IAC1C,SAA4D,MAAS;AAavE,QAAM,eAAe;AAAA,IACnB,CAAC,OAA0D,oBAAoB,MAAM,EAAE;AAAA,IACvF,CAAC;AAAA,EACH;AAKA,QAAM,eAAe,QAAQ,OAAO,EAAE,iBAAiB,IAAI,CAAC,gBAAgB,CAAC;AAE7E,SACE,qBAAC,yBAAyB,UAAzB,EAAkC,OAAO,cACxC;AAAA,wBAAC,2BAA2C,cAA6B,GAAG,eAC1E,8BAAC,iBAAc,UAAU,cAAc,KADX,YAE9B;AAAA,IACC;AAAA,KACH;AAEJ;AAUO,SAAS,uBAAsD;AACpE,SAAO,WAAW,wBAAwB;AAC5C;","names":[]}
|
package/dist/recaptcha.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/recaptcha.ts"],"sourcesContent":["/**\n * reCAPTCHA v3 — the SITE's half of the contract (REB-588).\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHICH HALF LIVES WHERE, AND WHY\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * reCAPTCHA is two secrets and two steps, and they are deliberately split across\n * a trust boundary:\n *\n * SITE KEY — public by design. It ships to the browser inside the script URL,\n * so the tenant serves it from `/api/site/analytics`. This module\n * handles it.\n * SECRET — never leaves base-api. It is stored per tenant in\n * `site_integration_config.recaptchaSecretKey` and read only by\n * `serverCaptchaVerify` when `POST /api/site/contact-form` runs.\n *\n * **Nothing in this module, in this package, or anywhere in the `@reblu/site-*`\n * SDK ever sees the secret, and nothing here calls Google's `siteverify`.** A\n * SITE holding the secret would be a SITE that could be tricked into approving\n * its own tokens, and a distributable SDK is the worst possible place to put a\n * credential. Verification is base-api's job and already works: the SITE mints a\n * token, posts it as `ContactFormInput.captcha`, and base-api decides.\n *\n * That is also why this module is NOT \"reCAPTCHA support\" in the round. It is\n * the three decisions every SITE was otherwise making alone and differently:\n * which action to name, whether a form may be shown at all, and when Google's\n * script is allowed to load.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHY IT IS IN THE SDK AT ALL\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * Because it was already being written four times. `apps/base-api`,\n * `apps/demo-site` and the external `reblu-site-dermamedicin` each grew their\n * own copy of this flow, and they had already drifted — different action\n * strings, different mount timing, a retry loop in one of them. A score that\n * reCAPTCHA reports per action is not comparable across SITEs that name the\n * action differently, and a defect fixed in one copy stays live in the other\n * two. The SDK is where a decision gets made once.\n *\n * This module has ZERO runtime dependencies and imports nothing — not React, not\n * `next`, not `react-google-recaptcha-v3`, not `@reblu/site-ui`. It is pure\n * functions over plain data, callable from a Server Component deciding whether\n * to render a form and from the Client Component that renders it. The subpath is\n * kept dependency-free by `tests/recaptcha-subpath-isolation.test.ts`.\n */\n\nimport type { Analytics, ContactFormMode } from '@reblu/site-contracts'\n\n/**\n * The action name every Reblu SITE mints its contact-form token under.\n *\n * reCAPTCHA v3 scores PER ACTION, and a score is only interpretable against a\n * stable one: Google's own admin console charts each action separately, and a\n * threshold tuned on one action says nothing about another. Two SITEs calling\n * `executeRecaptcha('submit_form')` and `executeRecaptcha('contact_form')` are\n * building two unrelated score histories for the same feature — which is exactly\n * the state the repo was in before this constant existed.\n *\n * `contact_form` over `submit_form` because it names the form, not the verb;\n * a second protected form would need its own action, and `submit_form` would\n * have nothing left to call it.\n *\n * ── WHAT THIS CONSTANT DOES **NOT** BUY, STATED PLAINLY ──\n *\n * It buys comparable scores. It does NOT bind a token to this form, because\n * `serverCaptchaVerify` in base-api checks only `success` and `score`, and never\n * reads the `action` field Google returns. A token minted for any other action\n * on the same site verifies here exactly as well. Making the action load-bearing\n * requires base-api to assert `action === RECAPTCHA_ACTION` on verify; until it\n * does, do not read this constant as a security control.\n */\nexport const RECAPTCHA_ACTION = 'contact_form'\n\n/**\n * The shape a site key must have before this SDK will hand it to Google.\n *\n * ── WHAT THIS IS, AND EMPHATICALLY WHAT IT IS NOT ──\n *\n * It is a SINK-SAFETY guard, not a guess at Google's key format. The key is\n * interpolated into the loader's script URL as a query parameter, so what\n * matters here is that it cannot carry a space, a quote, a newline, an `&`, or a\n * `#` — characters that make a URL mean something other than what was intended.\n * The base64url alphabet Google actually issues from (`A-Z a-z 0-9 - _`) is a\n * strict subset of \"safe\", so a real key passes by construction.\n *\n * The length bounds are deliberately far wider than any key Google issues\n * (theirs are 40 characters). A bound tight enough to be a real format check\n * would be a bound tight enough to take a WORKING tenant's contact form offline\n * the day Google changes its key length — which is strictly worse than the\n * malformed key it was meant to catch. If you are tempted to tighten this,\n * the thing to tighten is the nexus write path, where an owner can still see\n * and fix the error, not this read path where they cannot.\n *\n * ── WHY THE SDK RE-VALIDATES AT ALL ──\n *\n * Same reason `@reblu/site-next/analytics` re-checks `gaId` and `clarityId`\n * (REB-617): base-api is not the only thing a SITE ever talks to, and the layer\n * that owns the value is not the layer that suffers from it being wrong. As of\n * REB-588 this column has NO validation anywhere — not in the nexus form, not on\n * the way out of `/api/site/analytics`, not in the response contract, which is\n * the one asymmetry `gaId`/`clarityId` do not share. Until that is fixed\n * upstream, this is the only guard between a mistyped key and a contact form\n * that renders, looks live, and silently eats every enquiry.\n */\nexport const RECAPTCHA_SITE_KEY_PATTERN = /^[A-Za-z0-9_-]{16,128}$/\n\n/**\n * Whether `value` is a site key safe to put in the loader's script URL.\n *\n * Takes `unknown` on purpose: the value arrives over HTTP, so the contract's\n * `string | null` is a promise about the shape, not a guarantee about the bytes.\n */\nexport function isSafeRecaptchaSiteKey(value: unknown): value is string {\n return typeof value === 'string' && RECAPTCHA_SITE_KEY_PATTERN.test(value)\n}\n\n/**\n * The modes in which base-api will actually accept a submission.\n *\n * An ALLOW-LIST, never `mode !== 'DISABLED'`. The three differ only in what\n * base-api DOES with the payload — a row, a webhook, an email — and the SITE\n * must not care and must never learn the destination: a webhook URL or a Resend\n * key is a tenant secret with no business in a public site.\n *\n * The deny-list version of this is a real incident, not a hypothetical: a page\n * that hid the form on `DISABLED` and rendered it otherwise rendered it for\n * `NOT_CONFIGURED` too — which is what EVERY freshly provisioned tenant carries\n * until someone finishes the wizard (REB-586). A visitor typed out a medical\n * enquiry, pressed send, and got `503 Contact form is disabled`. They learned\n * the clinic could not be reached only after writing to it.\n */\nexport const CONTACT_FORM_OPERATIONAL_MODES = ['DB_ONLY', 'WEBHOOK', 'RESEND'] as const\n\n/** A mode in which the form may be shown. */\nexport type ContactFormOperationalMode = (typeof CONTACT_FORM_OPERATIONAL_MODES)[number]\n\n/**\n * The modes deliberately declined. A TYPE, never a value: the runtime must never\n * read it, because an allow-list must not be expressible as \"everything except\n * this list\", and this subpath's defining property is that it ships nothing it\n * does not need. It exists only to feed {@link ContactFormModeExhaustiveCheck}.\n */\ntype DeclinedMode = 'NOT_CONFIGURED' | 'DISABLED'\n\n/**\n * Compile-time exhaustiveness guard over `ContactFormMode`.\n *\n * `Missing` is constrained to `never` and DEFAULTS to the contract modes that\n * are neither accepted nor explicitly declined, so a default violating its own\n * constraint breaks the build the moment `@reblu/site-contracts` gains a mode.\n *\n * At runtime a new mode already fails closed, which is correct but SILENT — and\n * silence is how a tenant switches their form on in nexus and watches nothing\n * appear. This forces a human to make the call in a diff instead.\n *\n * Exported so it is never reported as an unused symbol.\n */\nexport type ContactFormModeExhaustiveCheck<\n Missing extends never = Exclude<ContactFormMode, ContactFormOperationalMode | DeclinedMode>,\n> = Missing\n\n/** Why the form is not being shown. Drives diagnostics, never visitor-facing copy. */\nexport type ContactFormUnavailableReason =\n /** The analytics read failed or was never made — no answer at all. */\n | 'unreadable'\n /** The tenant's mode is not one base-api accepts submissions in. */\n | 'mode-not-operational'\n /** Accepting mode, but no site key: the browser cannot mint a token. */\n | 'missing-recaptcha-key'\n /** A site key is present but cannot be a key — see {@link RECAPTCHA_SITE_KEY_PATTERN}. */\n | 'malformed-recaptcha-key'\n\nexport type ContactFormAvailability =\n /**\n * Confirmed: base-api accepts submissions AND a usable site key exists. The\n * key travels inside the `available` case on purpose — a component that has\n * proven the form may render should not have to re-read (and re-null-check)\n * the payload to find out what to render it WITH.\n */\n | { state: 'available'; mode: ContactFormOperationalMode; recaptchaSiteKey: string }\n | { state: 'unavailable'; reason: ContactFormUnavailableReason }\n\n/** Whitespace-only is absent — a key someone saved blank is not a key. */\nfunction trimmed(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const text = value.trim()\n return text.length > 0 ? text : null\n}\n\nfunction isOperationalMode(mode: unknown): mode is ContactFormOperationalMode {\n // Widened to `unknown` deliberately: see isSafeRecaptchaSiteKey. A base-api\n // newer than this SDK sends a string TypeScript has never heard of, and it\n // must fail closed rather than be assumed accepting.\n return (CONTACT_FORM_OPERATIONAL_MODES as readonly string[]).includes(mode as string)\n}\n\n/**\n * Resolve whether a contact form may be rendered for this tenant.\n *\n * We offer what we can CONFIRM, never what we have merely failed to disprove: an\n * unknown mode, a mode from a runtime newer than this build, and a config read\n * that threw all resolve to the same answer — no form. The page still shows the\n * phone, the email and the address, so a hidden form costs a visitor one extra\n * glance; a form that eats their message costs them the message.\n *\n * Order matters. The mode is checked BEFORE the key, because \"the tenant has not\n * switched the form on\" is the actionable half of a double failure — a site key\n * for a form nobody enabled is not the problem to fix first.\n */\nexport function resolveContactFormAvailability(\n analytics: Analytics | null | undefined,\n): ContactFormAvailability {\n if (!analytics) return { state: 'unavailable', reason: 'unreadable' }\n\n const mode = analytics.contactFormMode\n if (!isOperationalMode(mode)) return { state: 'unavailable', reason: 'mode-not-operational' }\n\n // `ContactFormInput.captcha` is REQUIRED and base-api verifies it, so an\n // accepting mode with no usable key is still a form whose every submission is\n // dead on arrival. \"Missing\" and \"malformed\" are separated because they call\n // for different fixes by different people: one owner never filled the field,\n // the other filled it with the wrong thing.\n const recaptchaSiteKey = trimmed(analytics.recaptchaSiteKey)\n if (!recaptchaSiteKey) return { state: 'unavailable', reason: 'missing-recaptcha-key' }\n if (!isSafeRecaptchaSiteKey(recaptchaSiteKey)) {\n return { state: 'unavailable', reason: 'malformed-recaptcha-key' }\n }\n\n return { state: 'available', mode, recaptchaSiteKey }\n}\n\n/** Narrowing helper — the single question a renderer should ask. */\nexport function isContactFormAvailable(\n availability: ContactFormAvailability,\n): availability is Extract<ContactFormAvailability, { state: 'available' }> {\n return availability.state === 'available'\n}\n\n/**\n * The key to hand `GoogleReCaptchaProvider` on this render — `''` until `armed`.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHAT THIS BUYS\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `GoogleReCaptchaProvider` loads Google's `api.js` the moment it MOUNTS. Mount\n * it with the form and every visitor who merely lands on the page to read the\n * phone number has contacted Google — on a clinic's contact page, a third-party\n * request nobody asked for, on a route whose whole subject is personal data.\n *\n * Arming on first interaction with the form (focus, first keystroke) means\n * Google is contacted only for a visitor who is actually about to submit, which\n * is the only visitor whose token is worth anything. It is a smaller page, a\n * faster one, and a materially smaller consent surface.\n *\n * **This is NOT a cookie-consent implementation.** Deferring the script narrows\n * the exposure; it does not gate it on a lawful basis. Full consent gating for\n * third parties is REB-642 and has its own owner.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * HOW, WITHOUT A HACK — MEASURED, NOT ASSUMED\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `react-google-recaptcha-v3` injects the script from an effect shaped\n *\n * useEffect(() => { if (reCaptchaKey) { …inject…; return cleanup } … },\n * [ …, reCaptchaKey, … ])\n *\n * Two facts fall out, and together they are the whole mechanism:\n *\n * 1. An EMPTY key mounts the provider and injects NOTHING.\n * 2. `reCaptchaKey` is a dependency, so swapping the real key in later re-runs\n * the effect and injects the script then.\n *\n * Crucially the provider element never leaves the tree, so its children are\n * never remounted: the visitor does not lose focus, a half-typed word, or the\n * caret position at the instant the script arrives. This is the library's own\n * documented prop doing its documented job — no imperative script injection, no\n * reaching into the DOM, no fork.\n *\n * Both facts are pinned by `tests/recaptcha-deferred-oracle.test.tsx`, which\n * drives the REAL library and counts script tags in the DOM. They are claims\n * about someone else's code, so prose asserting them is not enough — if a future\n * version of the library injects eagerly, that test goes red and this whole\n * optimisation is known to be void.\n *\n * ── THE ONE COST, MEASURED ──\n *\n * On the empty-key render the library calls its own warn helper, which is\n * written inverted, so the warning fires in PRODUCTION and stays silent in\n * development. A visitor who opens devtools before touching a field sees one\n * `\"<GoogleReCaptchaProvider /> recaptcha key not provided\"`. Cosmetic console\n * noise, traded against a third-party request on every view of the page. Worth\n * it, and recorded here so the next reader knows it is expected.\n *\n * ── AND NO FALLBACK KEY, EVER ──\n *\n * `''` for a blank OR malformed key however armed. There is no hardcoded\n * fallback anywhere in this module, because a captcha key that is not the\n * tenant's fails Google's verification while LOOKING configured — converting a\n * visible gap an owner can fix in nexus into a silent one nobody can.\n * {@link resolveContactFormAvailability} hides the form in that case; this is\n * the second lock on the same door.\n */\nexport function deferredRecaptchaKey(siteKey: string, armed: boolean): string {\n if (!armed) return ''\n const key = trimmed(siteKey)\n return key && isSafeRecaptchaSiteKey(key) ? key : ''\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyEO,IAAM,mBAAmB;AAiCzB,IAAM,6BAA6B;AAQnC,SAAS,uBAAuB,OAAiC;AACtE,SAAO,OAAO,UAAU,YAAY,2BAA2B,KAAK,KAAK;AAC3E;AAiBO,IAAM,iCAAiC,CAAC,WAAW,WAAW,QAAQ;AAoD7E,SAAS,QAAQ,OAA+B;AAC9C,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,OAAO,MAAM,KAAK;AACxB,SAAO,KAAK,SAAS,IAAI,OAAO;AAClC;AAEA,SAAS,kBAAkB,MAAmD;AAI5E,SAAQ,+BAAqD,SAAS,IAAc;AACtF;AAeO,SAAS,+BACd,WACyB;AACzB,MAAI,CAAC,UAAW,QAAO,EAAE,OAAO,eAAe,QAAQ,aAAa;AAEpE,QAAM,OAAO,UAAU;AACvB,MAAI,CAAC,kBAAkB,IAAI,EAAG,QAAO,EAAE,OAAO,eAAe,QAAQ,uBAAuB;AAO5F,QAAM,mBAAmB,QAAQ,UAAU,gBAAgB;AAC3D,MAAI,CAAC,iBAAkB,QAAO,EAAE,OAAO,eAAe,QAAQ,wBAAwB;AACtF,MAAI,CAAC,uBAAuB,gBAAgB,GAAG;AAC7C,WAAO,EAAE,OAAO,eAAe,QAAQ,0BAA0B;AAAA,EACnE;AAEA,SAAO,EAAE,OAAO,aAAa,MAAM,iBAAiB;AACtD;AAGO,SAAS,uBACd,cAC0E;AAC1E,SAAO,aAAa,UAAU;AAChC;AAoEO,SAAS,qBAAqB,SAAiB,OAAwB;AAC5E,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,MAAM,QAAQ,OAAO;AAC3B,SAAO,OAAO,uBAAuB,GAAG,IAAI,MAAM;AACpD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/recaptcha.ts"],"sourcesContent":["/**\n * reCAPTCHA v3 — the SITE's half of the contract (REB-588).\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHICH HALF LIVES WHERE, AND WHY\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * reCAPTCHA is two secrets and two steps, and they are deliberately split across\n * a trust boundary:\n *\n * SITE KEY — public by design. It ships to the browser inside the script URL,\n * so the tenant serves it from `/api/site/analytics`. This module\n * handles it.\n * SECRET — never leaves base-api. It is stored per tenant in\n * `site_integration_config.recaptchaSecretKey` and read only by\n * `serverCaptchaVerify` when `POST /api/site/contact-form` runs.\n *\n * **Nothing in this module, in this package, or anywhere in the `@reblu/site-*`\n * SDK ever sees the secret, and nothing here calls Google's `siteverify`.** A\n * SITE holding the secret would be a SITE that could be tricked into approving\n * its own tokens, and a distributable SDK is the worst possible place to put a\n * credential. Verification is base-api's job and already works: the SITE mints a\n * token, posts it as `ContactFormInput.captcha`, and base-api decides.\n *\n * That is also why this module is NOT \"reCAPTCHA support\" in the round. It is\n * the three decisions every SITE was otherwise making alone and differently:\n * which action to name, whether a form may be shown at all, and when Google's\n * script is allowed to load.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHY IT IS IN THE SDK AT ALL\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * Because it was already being written four times. `apps/base-api`,\n * `apps/demo-site` and the external `reblu-site-dermamedicin` each grew their\n * own copy of this flow, and they had already drifted — different action\n * strings, different mount timing, a retry loop in one of them. A score that\n * reCAPTCHA reports per action is not comparable across SITEs that name the\n * action differently, and a defect fixed in one copy stays live in the other\n * two. The SDK is where a decision gets made once.\n *\n * This module has ZERO runtime dependencies and imports nothing — not React, not\n * `next`, not `react-google-recaptcha-v3`, not `@reblu/site-ui`. It is pure\n * functions over plain data, callable from a Server Component deciding whether\n * to render a form and from the Client Component that renders it. The subpath is\n * kept dependency-free by `tests/recaptcha-subpath-isolation.test.ts`.\n */\n\nimport type { Analytics, ContactFormMode } from '@reblu/site-contracts'\n\n/**\n * The action name every Reblu SITE mints its contact-form token under.\n *\n * reCAPTCHA v3 scores PER ACTION, and a score is only interpretable against a\n * stable one: Google's own admin console charts each action separately, and a\n * threshold tuned on one action says nothing about another. Two SITEs calling\n * `executeRecaptcha('submit_form')` and `executeRecaptcha('contact_form')` are\n * building two unrelated score histories for the same feature — which is exactly\n * the state the repo was in before this constant existed.\n *\n * `contact_form` over `submit_form` because it names the form, not the verb;\n * a second protected form would need its own action, and `submit_form` would\n * have nothing left to call it.\n *\n * ── WHAT THIS CONSTANT DOES **NOT** BUY, STATED PLAINLY ──\n *\n * It buys comparable scores. It does NOT bind a token to this form, because\n * `serverCaptchaVerify` in base-api checks only `success` and `score`, and never\n * reads the `action` field Google returns. A token minted for any other action\n * on the same site verifies here exactly as well. Making the action load-bearing\n * requires base-api to assert `action === RECAPTCHA_ACTION` on verify; until it\n * does, do not read this constant as a security control.\n */\nexport const RECAPTCHA_ACTION = 'contact_form'\n\n/**\n * The shape a site key must have before this SDK will hand it to Google.\n *\n * ── WHAT THIS IS, AND EMPHATICALLY WHAT IT IS NOT ──\n *\n * It is a SINK-SAFETY guard, not a guess at Google's key format. The key is\n * interpolated into the loader's script URL as a query parameter, so what\n * matters here is that it cannot carry a space, a quote, a newline, an `&`, or a\n * `#` — characters that make a URL mean something other than what was intended.\n * The base64url alphabet Google actually issues from (`A-Z a-z 0-9 - _`) is a\n * strict subset of \"safe\", so a real key passes by construction.\n *\n * The length bounds are deliberately far wider than any key Google issues\n * (theirs are 40 characters). A bound tight enough to be a real format check\n * would be a bound tight enough to take a WORKING tenant's contact form offline\n * the day Google changes its key length — which is strictly worse than the\n * malformed key it was meant to catch. If you are tempted to tighten this,\n * the thing to tighten is the nexus write path, where an owner can still see\n * and fix the error, not this read path where they cannot.\n *\n * ── WHY THE SDK RE-VALIDATES AT ALL ──\n *\n * Same reason `@reblu/site-next/analytics` re-checks `gaId` and `clarityId`\n * (REB-617): base-api is not the only thing a SITE ever talks to, and the layer\n * that owns the value is not the layer that suffers from it being wrong. As of\n * REB-588 this column has NO validation anywhere — not in the nexus form, not on\n * the way out of `/api/site/analytics`, not in the response contract, which is\n * the one asymmetry `gaId`/`clarityId` do not share. Until that is fixed\n * upstream, this is the only guard between a mistyped key and a contact form\n * that renders, looks live, and silently eats every enquiry.\n */\nexport const RECAPTCHA_SITE_KEY_PATTERN = /^[A-Za-z0-9_-]{16,128}$/\n\n/**\n * Whether `value` is a site key safe to put in the loader's script URL.\n *\n * Takes `unknown` on purpose: the value arrives over HTTP, so the contract's\n * `string | null` is a promise about the shape, not a guarantee about the bytes.\n */\nexport function isSafeRecaptchaSiteKey(value: unknown): value is string {\n return typeof value === 'string' && RECAPTCHA_SITE_KEY_PATTERN.test(value)\n}\n\n/**\n * The modes in which base-api will actually accept a submission.\n *\n * An ALLOW-LIST, never `mode !== 'DISABLED'`. The three differ only in what\n * base-api DOES with the payload — a row, a webhook, an email — and the SITE\n * must not care and must never learn the destination: a webhook URL or a Resend\n * key is a tenant secret with no business in a public site.\n *\n * The deny-list version of this is a real incident, not a hypothetical: a page\n * that hid the form on `DISABLED` and rendered it otherwise rendered it for\n * `NOT_CONFIGURED` too — which is what EVERY freshly provisioned tenant carries\n * until someone finishes the wizard (REB-586). A visitor typed out a medical\n * enquiry, pressed send, and got `503 Contact form is disabled`. They learned\n * the clinic could not be reached only after writing to it.\n */\nexport const CONTACT_FORM_OPERATIONAL_MODES = ['DB_ONLY', 'WEBHOOK', 'RESEND'] as const\n\n/** A mode in which the form may be shown. */\nexport type ContactFormOperationalMode = (typeof CONTACT_FORM_OPERATIONAL_MODES)[number]\n\n/**\n * The modes deliberately declined. A TYPE, never a value: the runtime must never\n * read it, because an allow-list must not be expressible as \"everything except\n * this list\", and this subpath's defining property is that it ships nothing it\n * does not need. It exists only to feed {@link ContactFormModeExhaustiveCheck}.\n */\ntype DeclinedMode = 'NOT_CONFIGURED' | 'DISABLED'\n\n/**\n * Compile-time exhaustiveness guard over `ContactFormMode`.\n *\n * `Missing` is constrained to `never` and DEFAULTS to the contract modes that\n * are neither accepted nor explicitly declined, so a default violating its own\n * constraint breaks the build the moment `@reblu/site-contracts` gains a mode.\n *\n * At runtime a new mode already fails closed, which is correct but SILENT — and\n * silence is how a tenant switches their form on in nexus and watches nothing\n * appear. This forces a human to make the call in a diff instead.\n *\n * Exported so it is never reported as an unused symbol.\n */\nexport type ContactFormModeExhaustiveCheck<\n Missing extends never = Exclude<ContactFormMode, ContactFormOperationalMode | DeclinedMode>,\n> = Missing\n\n/** Why the form is not being shown. Drives diagnostics, never visitor-facing copy. */\nexport type ContactFormUnavailableReason =\n /** The analytics read failed or was never made — no answer at all. */\n | 'unreadable'\n /** The tenant's mode is not one base-api accepts submissions in. */\n | 'mode-not-operational'\n /** Accepting mode, but no site key: the browser cannot mint a token. */\n | 'missing-recaptcha-key'\n /** A site key is present but cannot be a key — see {@link RECAPTCHA_SITE_KEY_PATTERN}. */\n | 'malformed-recaptcha-key'\n\nexport type ContactFormAvailability =\n /**\n * Confirmed: base-api accepts submissions AND a usable site key exists. The\n * key travels inside the `available` case on purpose — a component that has\n * proven the form may render should not have to re-read (and re-null-check)\n * the payload to find out what to render it WITH.\n */\n | { state: 'available'; mode: ContactFormOperationalMode; recaptchaSiteKey: string }\n | { state: 'unavailable'; reason: ContactFormUnavailableReason }\n\n/** Whitespace-only is absent — a key someone saved blank is not a key. */\nfunction trimmed(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const text = value.trim()\n return text.length > 0 ? text : null\n}\n\nfunction isOperationalMode(mode: unknown): mode is ContactFormOperationalMode {\n // Widened to `unknown` deliberately: see isSafeRecaptchaSiteKey. A base-api\n // newer than this SDK sends a string TypeScript has never heard of, and it\n // must fail closed rather than be assumed accepting.\n return (CONTACT_FORM_OPERATIONAL_MODES as readonly string[]).includes(mode as string)\n}\n\n/**\n * Resolve whether a contact form may be rendered for this tenant.\n *\n * We offer what we can CONFIRM, never what we have merely failed to disprove: an\n * unknown mode, a mode from a runtime newer than this build, and a config read\n * that threw all resolve to the same answer — no form. The page still shows the\n * phone, the email and the address, so a hidden form costs a visitor one extra\n * glance; a form that eats their message costs them the message.\n *\n * Order matters. The mode is checked BEFORE the key, because \"the tenant has not\n * switched the form on\" is the actionable half of a double failure — a site key\n * for a form nobody enabled is not the problem to fix first.\n */\nexport function resolveContactFormAvailability(\n analytics: Analytics | null | undefined,\n): ContactFormAvailability {\n if (!analytics) return { state: 'unavailable', reason: 'unreadable' }\n\n const mode = analytics.contactFormMode\n if (!isOperationalMode(mode)) return { state: 'unavailable', reason: 'mode-not-operational' }\n\n // `ContactFormInput.captcha` is REQUIRED and base-api verifies it, so an\n // accepting mode with no usable key is still a form whose every submission is\n // dead on arrival. \"Missing\" and \"malformed\" are separated because they call\n // for different fixes by different people: one owner never filled the field,\n // the other filled it with the wrong thing.\n const recaptchaSiteKey = trimmed(analytics.recaptchaSiteKey)\n if (!recaptchaSiteKey) return { state: 'unavailable', reason: 'missing-recaptcha-key' }\n if (!isSafeRecaptchaSiteKey(recaptchaSiteKey)) {\n return { state: 'unavailable', reason: 'malformed-recaptcha-key' }\n }\n\n return { state: 'available', mode, recaptchaSiteKey }\n}\n\n/** Narrowing helper — the single question a renderer should ask. */\nexport function isContactFormAvailable(\n availability: ContactFormAvailability,\n): availability is Extract<ContactFormAvailability, { state: 'available' }> {\n return availability.state === 'available'\n}\n\n/**\n * The key to hand `GoogleReCaptchaProvider` on this render — `''` until `armed`.\n *\n * @deprecated **Wiring this return value directly into\n * `<GoogleReCaptchaProvider reCaptchaKey={deferredRecaptchaKey(siteKey, armed)}>`\n * is the exact REB-793 bug**: `react-google-recaptcha-v3@1.11.0` captures\n * `reCaptchaKey` in a `useRef` on FIRST MOUNT and never re-reads the prop for\n * invisible v3 (no visible `container`), so `executeRecaptcha` keeps sending\n * the STALE `''` from before arming to `grecaptcha.execute` forever — the\n * script loads with the right key, but every token mint throws, and every\n * contact-form submission is silently dead on arrival. Verified on\n * dermamedicin preprod 29-Sep: zero requests ever reached\n * `/api/site/contact-form`. Use `DeferredRecaptchaProvider` from\n * `@reblu/site-next/recaptcha-provider` instead — it applies this exact same\n * value as BOTH the `key` and the `reCaptchaKey` prop, which forces a full\n * remount on arm instead of a prop swap, so the mounted instance's `useRef`\n * never sees any key but the real one. This function stays exported,\n * unchanged, because `DeferredRecaptchaProvider` calls it internally and\n * external SITEs may already depend on its signature for other purposes\n * (e.g. rendering their own diagnostics) — this is a documentation-only\n * deprecation, not a behavior or breaking change.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHAT THIS BUYS\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `GoogleReCaptchaProvider` loads Google's `api.js` the moment it MOUNTS. Mount\n * it with the form and every visitor who merely lands on the page to read the\n * phone number has contacted Google — on a clinic's contact page, a third-party\n * request nobody asked for, on a route whose whole subject is personal data.\n *\n * Arming on first interaction with the form (focus, first keystroke) means\n * Google is contacted only for a visitor who is actually about to submit, which\n * is the only visitor whose token is worth anything. It is a smaller page, a\n * faster one, and a materially smaller consent surface.\n *\n * **This is NOT a cookie-consent implementation.** Deferring the script narrows\n * the exposure; it does not gate it on a lawful basis. Full consent gating for\n * third parties is REB-642 and has its own owner.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * HOW, WITHOUT A HACK — MEASURED, NOT ASSUMED\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `react-google-recaptcha-v3` injects the script from an effect shaped\n *\n * useEffect(() => { if (reCaptchaKey) { …inject…; return cleanup } … },\n * [ …, reCaptchaKey, … ])\n *\n * Two facts fall out, and together they are the whole mechanism:\n *\n * 1. An EMPTY key mounts the provider and injects NOTHING.\n * 2. `reCaptchaKey` is a dependency, so swapping the real key in later re-runs\n * the effect and injects the script then.\n *\n * Crucially the provider element never leaves the tree, so its children are\n * never remounted merely because `reCaptchaKey` changed on a LIVE instance:\n * no imperative script injection, no reaching into the DOM, no fork.\n *\n * **This describes script LOADING only, not token MINTING.** REB-793 found\n * the gap: the same swapped prop that safely re-runs this effect is also\n * where `react-google-recaptcha-v3` caches `reCaptchaKey` in a `useRef` — set\n * once, on first mount, and (for invisible v3) never reassigned. The script\n * loads with the swapped-in real key; `executeRecaptcha` keeps sending the\n * key from BEFORE the swap. Wiring this function's return value straight\n * into `<GoogleReCaptchaProvider reCaptchaKey={...}>`, the pattern this\n * whole comment used to recommend, is exactly that bug — see the\n * `@deprecated` note above and `@reblu/site-next/recaptcha-provider`'s\n * `DeferredRecaptchaProvider`, which fixes it by forcing a real remount\n * instead of relying on this same prop swap.\n *\n * Both facts are pinned by `tests/recaptcha-deferred-oracle.test.tsx`, which\n * drives the REAL library and counts script tags in the DOM. They are claims\n * about someone else's code, so prose asserting them is not enough — if a future\n * version of the library injects eagerly, that test goes red and this whole\n * optimisation is known to be void.\n *\n * ── THE ONE COST, MEASURED ──\n *\n * On the empty-key render the library calls its own warn helper, which is\n * written inverted, so the warning fires in PRODUCTION and stays silent in\n * development. A visitor who opens devtools before touching a field sees one\n * `\"<GoogleReCaptchaProvider /> recaptcha key not provided\"`. Cosmetic console\n * noise, traded against a third-party request on every view of the page. Worth\n * it, and recorded here so the next reader knows it is expected.\n *\n * ── AND NO FALLBACK KEY, EVER ──\n *\n * `''` for a blank OR malformed key however armed. There is no hardcoded\n * fallback anywhere in this module, because a captcha key that is not the\n * tenant's fails Google's verification while LOOKING configured — converting a\n * visible gap an owner can fix in nexus into a silent one nobody can.\n * {@link resolveContactFormAvailability} hides the form in that case; this is\n * the second lock on the same door.\n */\nexport function deferredRecaptchaKey(siteKey: string, armed: boolean): string {\n if (!armed) return ''\n const key = trimmed(siteKey)\n return key && isSafeRecaptchaSiteKey(key) ? key : ''\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyEO,IAAM,mBAAmB;AAiCzB,IAAM,6BAA6B;AAQnC,SAAS,uBAAuB,OAAiC;AACtE,SAAO,OAAO,UAAU,YAAY,2BAA2B,KAAK,KAAK;AAC3E;AAiBO,IAAM,iCAAiC,CAAC,WAAW,WAAW,QAAQ;AAoD7E,SAAS,QAAQ,OAA+B;AAC9C,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,OAAO,MAAM,KAAK;AACxB,SAAO,KAAK,SAAS,IAAI,OAAO;AAClC;AAEA,SAAS,kBAAkB,MAAmD;AAI5E,SAAQ,+BAAqD,SAAS,IAAc;AACtF;AAeO,SAAS,+BACd,WACyB;AACzB,MAAI,CAAC,UAAW,QAAO,EAAE,OAAO,eAAe,QAAQ,aAAa;AAEpE,QAAM,OAAO,UAAU;AACvB,MAAI,CAAC,kBAAkB,IAAI,EAAG,QAAO,EAAE,OAAO,eAAe,QAAQ,uBAAuB;AAO5F,QAAM,mBAAmB,QAAQ,UAAU,gBAAgB;AAC3D,MAAI,CAAC,iBAAkB,QAAO,EAAE,OAAO,eAAe,QAAQ,wBAAwB;AACtF,MAAI,CAAC,uBAAuB,gBAAgB,GAAG;AAC7C,WAAO,EAAE,OAAO,eAAe,QAAQ,0BAA0B;AAAA,EACnE;AAEA,SAAO,EAAE,OAAO,aAAa,MAAM,iBAAiB;AACtD;AAGO,SAAS,uBACd,cAC0E;AAC1E,SAAO,aAAa,UAAU;AAChC;AAiGO,SAAS,qBAAqB,SAAiB,OAAwB;AAC5E,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,MAAM,QAAQ,OAAO;AAC3B,SAAO,OAAO,uBAAuB,GAAG,IAAI,MAAM;AACpD;","names":[]}
|
package/dist/recaptcha.d.cts
CHANGED
|
@@ -196,6 +196,25 @@ declare function isContactFormAvailable(availability: ContactFormAvailability):
|
|
|
196
196
|
/**
|
|
197
197
|
* The key to hand `GoogleReCaptchaProvider` on this render — `''` until `armed`.
|
|
198
198
|
*
|
|
199
|
+
* @deprecated **Wiring this return value directly into
|
|
200
|
+
* `<GoogleReCaptchaProvider reCaptchaKey={deferredRecaptchaKey(siteKey, armed)}>`
|
|
201
|
+
* is the exact REB-793 bug**: `react-google-recaptcha-v3@1.11.0` captures
|
|
202
|
+
* `reCaptchaKey` in a `useRef` on FIRST MOUNT and never re-reads the prop for
|
|
203
|
+
* invisible v3 (no visible `container`), so `executeRecaptcha` keeps sending
|
|
204
|
+
* the STALE `''` from before arming to `grecaptcha.execute` forever — the
|
|
205
|
+
* script loads with the right key, but every token mint throws, and every
|
|
206
|
+
* contact-form submission is silently dead on arrival. Verified on
|
|
207
|
+
* dermamedicin preprod 29-Sep: zero requests ever reached
|
|
208
|
+
* `/api/site/contact-form`. Use `DeferredRecaptchaProvider` from
|
|
209
|
+
* `@reblu/site-next/recaptcha-provider` instead — it applies this exact same
|
|
210
|
+
* value as BOTH the `key` and the `reCaptchaKey` prop, which forces a full
|
|
211
|
+
* remount on arm instead of a prop swap, so the mounted instance's `useRef`
|
|
212
|
+
* never sees any key but the real one. This function stays exported,
|
|
213
|
+
* unchanged, because `DeferredRecaptchaProvider` calls it internally and
|
|
214
|
+
* external SITEs may already depend on its signature for other purposes
|
|
215
|
+
* (e.g. rendering their own diagnostics) — this is a documentation-only
|
|
216
|
+
* deprecation, not a behavior or breaking change.
|
|
217
|
+
*
|
|
199
218
|
* ─────────────────────────────────────────────────────────────────────────────
|
|
200
219
|
* WHAT THIS BUYS
|
|
201
220
|
* ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -230,10 +249,20 @@ declare function isContactFormAvailable(availability: ContactFormAvailability):
|
|
|
230
249
|
* the effect and injects the script then.
|
|
231
250
|
*
|
|
232
251
|
* Crucially the provider element never leaves the tree, so its children are
|
|
233
|
-
* never remounted
|
|
234
|
-
*
|
|
235
|
-
*
|
|
236
|
-
*
|
|
252
|
+
* never remounted merely because `reCaptchaKey` changed on a LIVE instance:
|
|
253
|
+
* no imperative script injection, no reaching into the DOM, no fork.
|
|
254
|
+
*
|
|
255
|
+
* **This describes script LOADING only, not token MINTING.** REB-793 found
|
|
256
|
+
* the gap: the same swapped prop that safely re-runs this effect is also
|
|
257
|
+
* where `react-google-recaptcha-v3` caches `reCaptchaKey` in a `useRef` — set
|
|
258
|
+
* once, on first mount, and (for invisible v3) never reassigned. The script
|
|
259
|
+
* loads with the swapped-in real key; `executeRecaptcha` keeps sending the
|
|
260
|
+
* key from BEFORE the swap. Wiring this function's return value straight
|
|
261
|
+
* into `<GoogleReCaptchaProvider reCaptchaKey={...}>`, the pattern this
|
|
262
|
+
* whole comment used to recommend, is exactly that bug — see the
|
|
263
|
+
* `@deprecated` note above and `@reblu/site-next/recaptcha-provider`'s
|
|
264
|
+
* `DeferredRecaptchaProvider`, which fixes it by forcing a real remount
|
|
265
|
+
* instead of relying on this same prop swap.
|
|
237
266
|
*
|
|
238
267
|
* Both facts are pinned by `tests/recaptcha-deferred-oracle.test.tsx`, which
|
|
239
268
|
* drives the REAL library and counts script tags in the DOM. They are claims
|
package/dist/recaptcha.d.ts
CHANGED
|
@@ -196,6 +196,25 @@ declare function isContactFormAvailable(availability: ContactFormAvailability):
|
|
|
196
196
|
/**
|
|
197
197
|
* The key to hand `GoogleReCaptchaProvider` on this render — `''` until `armed`.
|
|
198
198
|
*
|
|
199
|
+
* @deprecated **Wiring this return value directly into
|
|
200
|
+
* `<GoogleReCaptchaProvider reCaptchaKey={deferredRecaptchaKey(siteKey, armed)}>`
|
|
201
|
+
* is the exact REB-793 bug**: `react-google-recaptcha-v3@1.11.0` captures
|
|
202
|
+
* `reCaptchaKey` in a `useRef` on FIRST MOUNT and never re-reads the prop for
|
|
203
|
+
* invisible v3 (no visible `container`), so `executeRecaptcha` keeps sending
|
|
204
|
+
* the STALE `''` from before arming to `grecaptcha.execute` forever — the
|
|
205
|
+
* script loads with the right key, but every token mint throws, and every
|
|
206
|
+
* contact-form submission is silently dead on arrival. Verified on
|
|
207
|
+
* dermamedicin preprod 29-Sep: zero requests ever reached
|
|
208
|
+
* `/api/site/contact-form`. Use `DeferredRecaptchaProvider` from
|
|
209
|
+
* `@reblu/site-next/recaptcha-provider` instead — it applies this exact same
|
|
210
|
+
* value as BOTH the `key` and the `reCaptchaKey` prop, which forces a full
|
|
211
|
+
* remount on arm instead of a prop swap, so the mounted instance's `useRef`
|
|
212
|
+
* never sees any key but the real one. This function stays exported,
|
|
213
|
+
* unchanged, because `DeferredRecaptchaProvider` calls it internally and
|
|
214
|
+
* external SITEs may already depend on its signature for other purposes
|
|
215
|
+
* (e.g. rendering their own diagnostics) — this is a documentation-only
|
|
216
|
+
* deprecation, not a behavior or breaking change.
|
|
217
|
+
*
|
|
199
218
|
* ─────────────────────────────────────────────────────────────────────────────
|
|
200
219
|
* WHAT THIS BUYS
|
|
201
220
|
* ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -230,10 +249,20 @@ declare function isContactFormAvailable(availability: ContactFormAvailability):
|
|
|
230
249
|
* the effect and injects the script then.
|
|
231
250
|
*
|
|
232
251
|
* Crucially the provider element never leaves the tree, so its children are
|
|
233
|
-
* never remounted
|
|
234
|
-
*
|
|
235
|
-
*
|
|
236
|
-
*
|
|
252
|
+
* never remounted merely because `reCaptchaKey` changed on a LIVE instance:
|
|
253
|
+
* no imperative script injection, no reaching into the DOM, no fork.
|
|
254
|
+
*
|
|
255
|
+
* **This describes script LOADING only, not token MINTING.** REB-793 found
|
|
256
|
+
* the gap: the same swapped prop that safely re-runs this effect is also
|
|
257
|
+
* where `react-google-recaptcha-v3` caches `reCaptchaKey` in a `useRef` — set
|
|
258
|
+
* once, on first mount, and (for invisible v3) never reassigned. The script
|
|
259
|
+
* loads with the swapped-in real key; `executeRecaptcha` keeps sending the
|
|
260
|
+
* key from BEFORE the swap. Wiring this function's return value straight
|
|
261
|
+
* into `<GoogleReCaptchaProvider reCaptchaKey={...}>`, the pattern this
|
|
262
|
+
* whole comment used to recommend, is exactly that bug — see the
|
|
263
|
+
* `@deprecated` note above and `@reblu/site-next/recaptcha-provider`'s
|
|
264
|
+
* `DeferredRecaptchaProvider`, which fixes it by forcing a real remount
|
|
265
|
+
* instead of relying on this same prop swap.
|
|
237
266
|
*
|
|
238
267
|
* Both facts are pinned by `tests/recaptcha-deferred-oracle.test.tsx`, which
|
|
239
268
|
* drives the REAL library and counts script tags in the DOM. They are claims
|
package/dist/recaptcha.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/recaptcha.ts"],"sourcesContent":["/**\n * reCAPTCHA v3 — the SITE's half of the contract (REB-588).\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHICH HALF LIVES WHERE, AND WHY\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * reCAPTCHA is two secrets and two steps, and they are deliberately split across\n * a trust boundary:\n *\n * SITE KEY — public by design. It ships to the browser inside the script URL,\n * so the tenant serves it from `/api/site/analytics`. This module\n * handles it.\n * SECRET — never leaves base-api. It is stored per tenant in\n * `site_integration_config.recaptchaSecretKey` and read only by\n * `serverCaptchaVerify` when `POST /api/site/contact-form` runs.\n *\n * **Nothing in this module, in this package, or anywhere in the `@reblu/site-*`\n * SDK ever sees the secret, and nothing here calls Google's `siteverify`.** A\n * SITE holding the secret would be a SITE that could be tricked into approving\n * its own tokens, and a distributable SDK is the worst possible place to put a\n * credential. Verification is base-api's job and already works: the SITE mints a\n * token, posts it as `ContactFormInput.captcha`, and base-api decides.\n *\n * That is also why this module is NOT \"reCAPTCHA support\" in the round. It is\n * the three decisions every SITE was otherwise making alone and differently:\n * which action to name, whether a form may be shown at all, and when Google's\n * script is allowed to load.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHY IT IS IN THE SDK AT ALL\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * Because it was already being written four times. `apps/base-api`,\n * `apps/demo-site` and the external `reblu-site-dermamedicin` each grew their\n * own copy of this flow, and they had already drifted — different action\n * strings, different mount timing, a retry loop in one of them. A score that\n * reCAPTCHA reports per action is not comparable across SITEs that name the\n * action differently, and a defect fixed in one copy stays live in the other\n * two. The SDK is where a decision gets made once.\n *\n * This module has ZERO runtime dependencies and imports nothing — not React, not\n * `next`, not `react-google-recaptcha-v3`, not `@reblu/site-ui`. It is pure\n * functions over plain data, callable from a Server Component deciding whether\n * to render a form and from the Client Component that renders it. The subpath is\n * kept dependency-free by `tests/recaptcha-subpath-isolation.test.ts`.\n */\n\nimport type { Analytics, ContactFormMode } from '@reblu/site-contracts'\n\n/**\n * The action name every Reblu SITE mints its contact-form token under.\n *\n * reCAPTCHA v3 scores PER ACTION, and a score is only interpretable against a\n * stable one: Google's own admin console charts each action separately, and a\n * threshold tuned on one action says nothing about another. Two SITEs calling\n * `executeRecaptcha('submit_form')` and `executeRecaptcha('contact_form')` are\n * building two unrelated score histories for the same feature — which is exactly\n * the state the repo was in before this constant existed.\n *\n * `contact_form` over `submit_form` because it names the form, not the verb;\n * a second protected form would need its own action, and `submit_form` would\n * have nothing left to call it.\n *\n * ── WHAT THIS CONSTANT DOES **NOT** BUY, STATED PLAINLY ──\n *\n * It buys comparable scores. It does NOT bind a token to this form, because\n * `serverCaptchaVerify` in base-api checks only `success` and `score`, and never\n * reads the `action` field Google returns. A token minted for any other action\n * on the same site verifies here exactly as well. Making the action load-bearing\n * requires base-api to assert `action === RECAPTCHA_ACTION` on verify; until it\n * does, do not read this constant as a security control.\n */\nexport const RECAPTCHA_ACTION = 'contact_form'\n\n/**\n * The shape a site key must have before this SDK will hand it to Google.\n *\n * ── WHAT THIS IS, AND EMPHATICALLY WHAT IT IS NOT ──\n *\n * It is a SINK-SAFETY guard, not a guess at Google's key format. The key is\n * interpolated into the loader's script URL as a query parameter, so what\n * matters here is that it cannot carry a space, a quote, a newline, an `&`, or a\n * `#` — characters that make a URL mean something other than what was intended.\n * The base64url alphabet Google actually issues from (`A-Z a-z 0-9 - _`) is a\n * strict subset of \"safe\", so a real key passes by construction.\n *\n * The length bounds are deliberately far wider than any key Google issues\n * (theirs are 40 characters). A bound tight enough to be a real format check\n * would be a bound tight enough to take a WORKING tenant's contact form offline\n * the day Google changes its key length — which is strictly worse than the\n * malformed key it was meant to catch. If you are tempted to tighten this,\n * the thing to tighten is the nexus write path, where an owner can still see\n * and fix the error, not this read path where they cannot.\n *\n * ── WHY THE SDK RE-VALIDATES AT ALL ──\n *\n * Same reason `@reblu/site-next/analytics` re-checks `gaId` and `clarityId`\n * (REB-617): base-api is not the only thing a SITE ever talks to, and the layer\n * that owns the value is not the layer that suffers from it being wrong. As of\n * REB-588 this column has NO validation anywhere — not in the nexus form, not on\n * the way out of `/api/site/analytics`, not in the response contract, which is\n * the one asymmetry `gaId`/`clarityId` do not share. Until that is fixed\n * upstream, this is the only guard between a mistyped key and a contact form\n * that renders, looks live, and silently eats every enquiry.\n */\nexport const RECAPTCHA_SITE_KEY_PATTERN = /^[A-Za-z0-9_-]{16,128}$/\n\n/**\n * Whether `value` is a site key safe to put in the loader's script URL.\n *\n * Takes `unknown` on purpose: the value arrives over HTTP, so the contract's\n * `string | null` is a promise about the shape, not a guarantee about the bytes.\n */\nexport function isSafeRecaptchaSiteKey(value: unknown): value is string {\n return typeof value === 'string' && RECAPTCHA_SITE_KEY_PATTERN.test(value)\n}\n\n/**\n * The modes in which base-api will actually accept a submission.\n *\n * An ALLOW-LIST, never `mode !== 'DISABLED'`. The three differ only in what\n * base-api DOES with the payload — a row, a webhook, an email — and the SITE\n * must not care and must never learn the destination: a webhook URL or a Resend\n * key is a tenant secret with no business in a public site.\n *\n * The deny-list version of this is a real incident, not a hypothetical: a page\n * that hid the form on `DISABLED` and rendered it otherwise rendered it for\n * `NOT_CONFIGURED` too — which is what EVERY freshly provisioned tenant carries\n * until someone finishes the wizard (REB-586). A visitor typed out a medical\n * enquiry, pressed send, and got `503 Contact form is disabled`. They learned\n * the clinic could not be reached only after writing to it.\n */\nexport const CONTACT_FORM_OPERATIONAL_MODES = ['DB_ONLY', 'WEBHOOK', 'RESEND'] as const\n\n/** A mode in which the form may be shown. */\nexport type ContactFormOperationalMode = (typeof CONTACT_FORM_OPERATIONAL_MODES)[number]\n\n/**\n * The modes deliberately declined. A TYPE, never a value: the runtime must never\n * read it, because an allow-list must not be expressible as \"everything except\n * this list\", and this subpath's defining property is that it ships nothing it\n * does not need. It exists only to feed {@link ContactFormModeExhaustiveCheck}.\n */\ntype DeclinedMode = 'NOT_CONFIGURED' | 'DISABLED'\n\n/**\n * Compile-time exhaustiveness guard over `ContactFormMode`.\n *\n * `Missing` is constrained to `never` and DEFAULTS to the contract modes that\n * are neither accepted nor explicitly declined, so a default violating its own\n * constraint breaks the build the moment `@reblu/site-contracts` gains a mode.\n *\n * At runtime a new mode already fails closed, which is correct but SILENT — and\n * silence is how a tenant switches their form on in nexus and watches nothing\n * appear. This forces a human to make the call in a diff instead.\n *\n * Exported so it is never reported as an unused symbol.\n */\nexport type ContactFormModeExhaustiveCheck<\n Missing extends never = Exclude<ContactFormMode, ContactFormOperationalMode | DeclinedMode>,\n> = Missing\n\n/** Why the form is not being shown. Drives diagnostics, never visitor-facing copy. */\nexport type ContactFormUnavailableReason =\n /** The analytics read failed or was never made — no answer at all. */\n | 'unreadable'\n /** The tenant's mode is not one base-api accepts submissions in. */\n | 'mode-not-operational'\n /** Accepting mode, but no site key: the browser cannot mint a token. */\n | 'missing-recaptcha-key'\n /** A site key is present but cannot be a key — see {@link RECAPTCHA_SITE_KEY_PATTERN}. */\n | 'malformed-recaptcha-key'\n\nexport type ContactFormAvailability =\n /**\n * Confirmed: base-api accepts submissions AND a usable site key exists. The\n * key travels inside the `available` case on purpose — a component that has\n * proven the form may render should not have to re-read (and re-null-check)\n * the payload to find out what to render it WITH.\n */\n | { state: 'available'; mode: ContactFormOperationalMode; recaptchaSiteKey: string }\n | { state: 'unavailable'; reason: ContactFormUnavailableReason }\n\n/** Whitespace-only is absent — a key someone saved blank is not a key. */\nfunction trimmed(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const text = value.trim()\n return text.length > 0 ? text : null\n}\n\nfunction isOperationalMode(mode: unknown): mode is ContactFormOperationalMode {\n // Widened to `unknown` deliberately: see isSafeRecaptchaSiteKey. A base-api\n // newer than this SDK sends a string TypeScript has never heard of, and it\n // must fail closed rather than be assumed accepting.\n return (CONTACT_FORM_OPERATIONAL_MODES as readonly string[]).includes(mode as string)\n}\n\n/**\n * Resolve whether a contact form may be rendered for this tenant.\n *\n * We offer what we can CONFIRM, never what we have merely failed to disprove: an\n * unknown mode, a mode from a runtime newer than this build, and a config read\n * that threw all resolve to the same answer — no form. The page still shows the\n * phone, the email and the address, so a hidden form costs a visitor one extra\n * glance; a form that eats their message costs them the message.\n *\n * Order matters. The mode is checked BEFORE the key, because \"the tenant has not\n * switched the form on\" is the actionable half of a double failure — a site key\n * for a form nobody enabled is not the problem to fix first.\n */\nexport function resolveContactFormAvailability(\n analytics: Analytics | null | undefined,\n): ContactFormAvailability {\n if (!analytics) return { state: 'unavailable', reason: 'unreadable' }\n\n const mode = analytics.contactFormMode\n if (!isOperationalMode(mode)) return { state: 'unavailable', reason: 'mode-not-operational' }\n\n // `ContactFormInput.captcha` is REQUIRED and base-api verifies it, so an\n // accepting mode with no usable key is still a form whose every submission is\n // dead on arrival. \"Missing\" and \"malformed\" are separated because they call\n // for different fixes by different people: one owner never filled the field,\n // the other filled it with the wrong thing.\n const recaptchaSiteKey = trimmed(analytics.recaptchaSiteKey)\n if (!recaptchaSiteKey) return { state: 'unavailable', reason: 'missing-recaptcha-key' }\n if (!isSafeRecaptchaSiteKey(recaptchaSiteKey)) {\n return { state: 'unavailable', reason: 'malformed-recaptcha-key' }\n }\n\n return { state: 'available', mode, recaptchaSiteKey }\n}\n\n/** Narrowing helper — the single question a renderer should ask. */\nexport function isContactFormAvailable(\n availability: ContactFormAvailability,\n): availability is Extract<ContactFormAvailability, { state: 'available' }> {\n return availability.state === 'available'\n}\n\n/**\n * The key to hand `GoogleReCaptchaProvider` on this render — `''` until `armed`.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHAT THIS BUYS\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `GoogleReCaptchaProvider` loads Google's `api.js` the moment it MOUNTS. Mount\n * it with the form and every visitor who merely lands on the page to read the\n * phone number has contacted Google — on a clinic's contact page, a third-party\n * request nobody asked for, on a route whose whole subject is personal data.\n *\n * Arming on first interaction with the form (focus, first keystroke) means\n * Google is contacted only for a visitor who is actually about to submit, which\n * is the only visitor whose token is worth anything. It is a smaller page, a\n * faster one, and a materially smaller consent surface.\n *\n * **This is NOT a cookie-consent implementation.** Deferring the script narrows\n * the exposure; it does not gate it on a lawful basis. Full consent gating for\n * third parties is REB-642 and has its own owner.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * HOW, WITHOUT A HACK — MEASURED, NOT ASSUMED\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `react-google-recaptcha-v3` injects the script from an effect shaped\n *\n * useEffect(() => { if (reCaptchaKey) { …inject…; return cleanup } … },\n * [ …, reCaptchaKey, … ])\n *\n * Two facts fall out, and together they are the whole mechanism:\n *\n * 1. An EMPTY key mounts the provider and injects NOTHING.\n * 2. `reCaptchaKey` is a dependency, so swapping the real key in later re-runs\n * the effect and injects the script then.\n *\n * Crucially the provider element never leaves the tree, so its children are\n * never remounted: the visitor does not lose focus, a half-typed word, or the\n * caret position at the instant the script arrives. This is the library's own\n * documented prop doing its documented job — no imperative script injection, no\n * reaching into the DOM, no fork.\n *\n * Both facts are pinned by `tests/recaptcha-deferred-oracle.test.tsx`, which\n * drives the REAL library and counts script tags in the DOM. They are claims\n * about someone else's code, so prose asserting them is not enough — if a future\n * version of the library injects eagerly, that test goes red and this whole\n * optimisation is known to be void.\n *\n * ── THE ONE COST, MEASURED ──\n *\n * On the empty-key render the library calls its own warn helper, which is\n * written inverted, so the warning fires in PRODUCTION and stays silent in\n * development. A visitor who opens devtools before touching a field sees one\n * `\"<GoogleReCaptchaProvider /> recaptcha key not provided\"`. Cosmetic console\n * noise, traded against a third-party request on every view of the page. Worth\n * it, and recorded here so the next reader knows it is expected.\n *\n * ── AND NO FALLBACK KEY, EVER ──\n *\n * `''` for a blank OR malformed key however armed. There is no hardcoded\n * fallback anywhere in this module, because a captcha key that is not the\n * tenant's fails Google's verification while LOOKING configured — converting a\n * visible gap an owner can fix in nexus into a silent one nobody can.\n * {@link resolveContactFormAvailability} hides the form in that case; this is\n * the second lock on the same door.\n */\nexport function deferredRecaptchaKey(siteKey: string, armed: boolean): string {\n if (!armed) return ''\n const key = trimmed(siteKey)\n return key && isSafeRecaptchaSiteKey(key) ? key : ''\n}\n"],"mappings":";AAyEO,IAAM,mBAAmB;AAiCzB,IAAM,6BAA6B;AAQnC,SAAS,uBAAuB,OAAiC;AACtE,SAAO,OAAO,UAAU,YAAY,2BAA2B,KAAK,KAAK;AAC3E;AAiBO,IAAM,iCAAiC,CAAC,WAAW,WAAW,QAAQ;AAoD7E,SAAS,QAAQ,OAA+B;AAC9C,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,OAAO,MAAM,KAAK;AACxB,SAAO,KAAK,SAAS,IAAI,OAAO;AAClC;AAEA,SAAS,kBAAkB,MAAmD;AAI5E,SAAQ,+BAAqD,SAAS,IAAc;AACtF;AAeO,SAAS,+BACd,WACyB;AACzB,MAAI,CAAC,UAAW,QAAO,EAAE,OAAO,eAAe,QAAQ,aAAa;AAEpE,QAAM,OAAO,UAAU;AACvB,MAAI,CAAC,kBAAkB,IAAI,EAAG,QAAO,EAAE,OAAO,eAAe,QAAQ,uBAAuB;AAO5F,QAAM,mBAAmB,QAAQ,UAAU,gBAAgB;AAC3D,MAAI,CAAC,iBAAkB,QAAO,EAAE,OAAO,eAAe,QAAQ,wBAAwB;AACtF,MAAI,CAAC,uBAAuB,gBAAgB,GAAG;AAC7C,WAAO,EAAE,OAAO,eAAe,QAAQ,0BAA0B;AAAA,EACnE;AAEA,SAAO,EAAE,OAAO,aAAa,MAAM,iBAAiB;AACtD;AAGO,SAAS,uBACd,cAC0E;AAC1E,SAAO,aAAa,UAAU;AAChC;AAoEO,SAAS,qBAAqB,SAAiB,OAAwB;AAC5E,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,MAAM,QAAQ,OAAO;AAC3B,SAAO,OAAO,uBAAuB,GAAG,IAAI,MAAM;AACpD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/recaptcha.ts"],"sourcesContent":["/**\n * reCAPTCHA v3 — the SITE's half of the contract (REB-588).\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHICH HALF LIVES WHERE, AND WHY\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * reCAPTCHA is two secrets and two steps, and they are deliberately split across\n * a trust boundary:\n *\n * SITE KEY — public by design. It ships to the browser inside the script URL,\n * so the tenant serves it from `/api/site/analytics`. This module\n * handles it.\n * SECRET — never leaves base-api. It is stored per tenant in\n * `site_integration_config.recaptchaSecretKey` and read only by\n * `serverCaptchaVerify` when `POST /api/site/contact-form` runs.\n *\n * **Nothing in this module, in this package, or anywhere in the `@reblu/site-*`\n * SDK ever sees the secret, and nothing here calls Google's `siteverify`.** A\n * SITE holding the secret would be a SITE that could be tricked into approving\n * its own tokens, and a distributable SDK is the worst possible place to put a\n * credential. Verification is base-api's job and already works: the SITE mints a\n * token, posts it as `ContactFormInput.captcha`, and base-api decides.\n *\n * That is also why this module is NOT \"reCAPTCHA support\" in the round. It is\n * the three decisions every SITE was otherwise making alone and differently:\n * which action to name, whether a form may be shown at all, and when Google's\n * script is allowed to load.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHY IT IS IN THE SDK AT ALL\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * Because it was already being written four times. `apps/base-api`,\n * `apps/demo-site` and the external `reblu-site-dermamedicin` each grew their\n * own copy of this flow, and they had already drifted — different action\n * strings, different mount timing, a retry loop in one of them. A score that\n * reCAPTCHA reports per action is not comparable across SITEs that name the\n * action differently, and a defect fixed in one copy stays live in the other\n * two. The SDK is where a decision gets made once.\n *\n * This module has ZERO runtime dependencies and imports nothing — not React, not\n * `next`, not `react-google-recaptcha-v3`, not `@reblu/site-ui`. It is pure\n * functions over plain data, callable from a Server Component deciding whether\n * to render a form and from the Client Component that renders it. The subpath is\n * kept dependency-free by `tests/recaptcha-subpath-isolation.test.ts`.\n */\n\nimport type { Analytics, ContactFormMode } from '@reblu/site-contracts'\n\n/**\n * The action name every Reblu SITE mints its contact-form token under.\n *\n * reCAPTCHA v3 scores PER ACTION, and a score is only interpretable against a\n * stable one: Google's own admin console charts each action separately, and a\n * threshold tuned on one action says nothing about another. Two SITEs calling\n * `executeRecaptcha('submit_form')` and `executeRecaptcha('contact_form')` are\n * building two unrelated score histories for the same feature — which is exactly\n * the state the repo was in before this constant existed.\n *\n * `contact_form` over `submit_form` because it names the form, not the verb;\n * a second protected form would need its own action, and `submit_form` would\n * have nothing left to call it.\n *\n * ── WHAT THIS CONSTANT DOES **NOT** BUY, STATED PLAINLY ──\n *\n * It buys comparable scores. It does NOT bind a token to this form, because\n * `serverCaptchaVerify` in base-api checks only `success` and `score`, and never\n * reads the `action` field Google returns. A token minted for any other action\n * on the same site verifies here exactly as well. Making the action load-bearing\n * requires base-api to assert `action === RECAPTCHA_ACTION` on verify; until it\n * does, do not read this constant as a security control.\n */\nexport const RECAPTCHA_ACTION = 'contact_form'\n\n/**\n * The shape a site key must have before this SDK will hand it to Google.\n *\n * ── WHAT THIS IS, AND EMPHATICALLY WHAT IT IS NOT ──\n *\n * It is a SINK-SAFETY guard, not a guess at Google's key format. The key is\n * interpolated into the loader's script URL as a query parameter, so what\n * matters here is that it cannot carry a space, a quote, a newline, an `&`, or a\n * `#` — characters that make a URL mean something other than what was intended.\n * The base64url alphabet Google actually issues from (`A-Z a-z 0-9 - _`) is a\n * strict subset of \"safe\", so a real key passes by construction.\n *\n * The length bounds are deliberately far wider than any key Google issues\n * (theirs are 40 characters). A bound tight enough to be a real format check\n * would be a bound tight enough to take a WORKING tenant's contact form offline\n * the day Google changes its key length — which is strictly worse than the\n * malformed key it was meant to catch. If you are tempted to tighten this,\n * the thing to tighten is the nexus write path, where an owner can still see\n * and fix the error, not this read path where they cannot.\n *\n * ── WHY THE SDK RE-VALIDATES AT ALL ──\n *\n * Same reason `@reblu/site-next/analytics` re-checks `gaId` and `clarityId`\n * (REB-617): base-api is not the only thing a SITE ever talks to, and the layer\n * that owns the value is not the layer that suffers from it being wrong. As of\n * REB-588 this column has NO validation anywhere — not in the nexus form, not on\n * the way out of `/api/site/analytics`, not in the response contract, which is\n * the one asymmetry `gaId`/`clarityId` do not share. Until that is fixed\n * upstream, this is the only guard between a mistyped key and a contact form\n * that renders, looks live, and silently eats every enquiry.\n */\nexport const RECAPTCHA_SITE_KEY_PATTERN = /^[A-Za-z0-9_-]{16,128}$/\n\n/**\n * Whether `value` is a site key safe to put in the loader's script URL.\n *\n * Takes `unknown` on purpose: the value arrives over HTTP, so the contract's\n * `string | null` is a promise about the shape, not a guarantee about the bytes.\n */\nexport function isSafeRecaptchaSiteKey(value: unknown): value is string {\n return typeof value === 'string' && RECAPTCHA_SITE_KEY_PATTERN.test(value)\n}\n\n/**\n * The modes in which base-api will actually accept a submission.\n *\n * An ALLOW-LIST, never `mode !== 'DISABLED'`. The three differ only in what\n * base-api DOES with the payload — a row, a webhook, an email — and the SITE\n * must not care and must never learn the destination: a webhook URL or a Resend\n * key is a tenant secret with no business in a public site.\n *\n * The deny-list version of this is a real incident, not a hypothetical: a page\n * that hid the form on `DISABLED` and rendered it otherwise rendered it for\n * `NOT_CONFIGURED` too — which is what EVERY freshly provisioned tenant carries\n * until someone finishes the wizard (REB-586). A visitor typed out a medical\n * enquiry, pressed send, and got `503 Contact form is disabled`. They learned\n * the clinic could not be reached only after writing to it.\n */\nexport const CONTACT_FORM_OPERATIONAL_MODES = ['DB_ONLY', 'WEBHOOK', 'RESEND'] as const\n\n/** A mode in which the form may be shown. */\nexport type ContactFormOperationalMode = (typeof CONTACT_FORM_OPERATIONAL_MODES)[number]\n\n/**\n * The modes deliberately declined. A TYPE, never a value: the runtime must never\n * read it, because an allow-list must not be expressible as \"everything except\n * this list\", and this subpath's defining property is that it ships nothing it\n * does not need. It exists only to feed {@link ContactFormModeExhaustiveCheck}.\n */\ntype DeclinedMode = 'NOT_CONFIGURED' | 'DISABLED'\n\n/**\n * Compile-time exhaustiveness guard over `ContactFormMode`.\n *\n * `Missing` is constrained to `never` and DEFAULTS to the contract modes that\n * are neither accepted nor explicitly declined, so a default violating its own\n * constraint breaks the build the moment `@reblu/site-contracts` gains a mode.\n *\n * At runtime a new mode already fails closed, which is correct but SILENT — and\n * silence is how a tenant switches their form on in nexus and watches nothing\n * appear. This forces a human to make the call in a diff instead.\n *\n * Exported so it is never reported as an unused symbol.\n */\nexport type ContactFormModeExhaustiveCheck<\n Missing extends never = Exclude<ContactFormMode, ContactFormOperationalMode | DeclinedMode>,\n> = Missing\n\n/** Why the form is not being shown. Drives diagnostics, never visitor-facing copy. */\nexport type ContactFormUnavailableReason =\n /** The analytics read failed or was never made — no answer at all. */\n | 'unreadable'\n /** The tenant's mode is not one base-api accepts submissions in. */\n | 'mode-not-operational'\n /** Accepting mode, but no site key: the browser cannot mint a token. */\n | 'missing-recaptcha-key'\n /** A site key is present but cannot be a key — see {@link RECAPTCHA_SITE_KEY_PATTERN}. */\n | 'malformed-recaptcha-key'\n\nexport type ContactFormAvailability =\n /**\n * Confirmed: base-api accepts submissions AND a usable site key exists. The\n * key travels inside the `available` case on purpose — a component that has\n * proven the form may render should not have to re-read (and re-null-check)\n * the payload to find out what to render it WITH.\n */\n | { state: 'available'; mode: ContactFormOperationalMode; recaptchaSiteKey: string }\n | { state: 'unavailable'; reason: ContactFormUnavailableReason }\n\n/** Whitespace-only is absent — a key someone saved blank is not a key. */\nfunction trimmed(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const text = value.trim()\n return text.length > 0 ? text : null\n}\n\nfunction isOperationalMode(mode: unknown): mode is ContactFormOperationalMode {\n // Widened to `unknown` deliberately: see isSafeRecaptchaSiteKey. A base-api\n // newer than this SDK sends a string TypeScript has never heard of, and it\n // must fail closed rather than be assumed accepting.\n return (CONTACT_FORM_OPERATIONAL_MODES as readonly string[]).includes(mode as string)\n}\n\n/**\n * Resolve whether a contact form may be rendered for this tenant.\n *\n * We offer what we can CONFIRM, never what we have merely failed to disprove: an\n * unknown mode, a mode from a runtime newer than this build, and a config read\n * that threw all resolve to the same answer — no form. The page still shows the\n * phone, the email and the address, so a hidden form costs a visitor one extra\n * glance; a form that eats their message costs them the message.\n *\n * Order matters. The mode is checked BEFORE the key, because \"the tenant has not\n * switched the form on\" is the actionable half of a double failure — a site key\n * for a form nobody enabled is not the problem to fix first.\n */\nexport function resolveContactFormAvailability(\n analytics: Analytics | null | undefined,\n): ContactFormAvailability {\n if (!analytics) return { state: 'unavailable', reason: 'unreadable' }\n\n const mode = analytics.contactFormMode\n if (!isOperationalMode(mode)) return { state: 'unavailable', reason: 'mode-not-operational' }\n\n // `ContactFormInput.captcha` is REQUIRED and base-api verifies it, so an\n // accepting mode with no usable key is still a form whose every submission is\n // dead on arrival. \"Missing\" and \"malformed\" are separated because they call\n // for different fixes by different people: one owner never filled the field,\n // the other filled it with the wrong thing.\n const recaptchaSiteKey = trimmed(analytics.recaptchaSiteKey)\n if (!recaptchaSiteKey) return { state: 'unavailable', reason: 'missing-recaptcha-key' }\n if (!isSafeRecaptchaSiteKey(recaptchaSiteKey)) {\n return { state: 'unavailable', reason: 'malformed-recaptcha-key' }\n }\n\n return { state: 'available', mode, recaptchaSiteKey }\n}\n\n/** Narrowing helper — the single question a renderer should ask. */\nexport function isContactFormAvailable(\n availability: ContactFormAvailability,\n): availability is Extract<ContactFormAvailability, { state: 'available' }> {\n return availability.state === 'available'\n}\n\n/**\n * The key to hand `GoogleReCaptchaProvider` on this render — `''` until `armed`.\n *\n * @deprecated **Wiring this return value directly into\n * `<GoogleReCaptchaProvider reCaptchaKey={deferredRecaptchaKey(siteKey, armed)}>`\n * is the exact REB-793 bug**: `react-google-recaptcha-v3@1.11.0` captures\n * `reCaptchaKey` in a `useRef` on FIRST MOUNT and never re-reads the prop for\n * invisible v3 (no visible `container`), so `executeRecaptcha` keeps sending\n * the STALE `''` from before arming to `grecaptcha.execute` forever — the\n * script loads with the right key, but every token mint throws, and every\n * contact-form submission is silently dead on arrival. Verified on\n * dermamedicin preprod 29-Sep: zero requests ever reached\n * `/api/site/contact-form`. Use `DeferredRecaptchaProvider` from\n * `@reblu/site-next/recaptcha-provider` instead — it applies this exact same\n * value as BOTH the `key` and the `reCaptchaKey` prop, which forces a full\n * remount on arm instead of a prop swap, so the mounted instance's `useRef`\n * never sees any key but the real one. This function stays exported,\n * unchanged, because `DeferredRecaptchaProvider` calls it internally and\n * external SITEs may already depend on its signature for other purposes\n * (e.g. rendering their own diagnostics) — this is a documentation-only\n * deprecation, not a behavior or breaking change.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * WHAT THIS BUYS\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `GoogleReCaptchaProvider` loads Google's `api.js` the moment it MOUNTS. Mount\n * it with the form and every visitor who merely lands on the page to read the\n * phone number has contacted Google — on a clinic's contact page, a third-party\n * request nobody asked for, on a route whose whole subject is personal data.\n *\n * Arming on first interaction with the form (focus, first keystroke) means\n * Google is contacted only for a visitor who is actually about to submit, which\n * is the only visitor whose token is worth anything. It is a smaller page, a\n * faster one, and a materially smaller consent surface.\n *\n * **This is NOT a cookie-consent implementation.** Deferring the script narrows\n * the exposure; it does not gate it on a lawful basis. Full consent gating for\n * third parties is REB-642 and has its own owner.\n *\n * ─────────────────────────────────────────────────────────────────────────────\n * HOW, WITHOUT A HACK — MEASURED, NOT ASSUMED\n * ─────────────────────────────────────────────────────────────────────────────\n *\n * `react-google-recaptcha-v3` injects the script from an effect shaped\n *\n * useEffect(() => { if (reCaptchaKey) { …inject…; return cleanup } … },\n * [ …, reCaptchaKey, … ])\n *\n * Two facts fall out, and together they are the whole mechanism:\n *\n * 1. An EMPTY key mounts the provider and injects NOTHING.\n * 2. `reCaptchaKey` is a dependency, so swapping the real key in later re-runs\n * the effect and injects the script then.\n *\n * Crucially the provider element never leaves the tree, so its children are\n * never remounted merely because `reCaptchaKey` changed on a LIVE instance:\n * no imperative script injection, no reaching into the DOM, no fork.\n *\n * **This describes script LOADING only, not token MINTING.** REB-793 found\n * the gap: the same swapped prop that safely re-runs this effect is also\n * where `react-google-recaptcha-v3` caches `reCaptchaKey` in a `useRef` — set\n * once, on first mount, and (for invisible v3) never reassigned. The script\n * loads with the swapped-in real key; `executeRecaptcha` keeps sending the\n * key from BEFORE the swap. Wiring this function's return value straight\n * into `<GoogleReCaptchaProvider reCaptchaKey={...}>`, the pattern this\n * whole comment used to recommend, is exactly that bug — see the\n * `@deprecated` note above and `@reblu/site-next/recaptcha-provider`'s\n * `DeferredRecaptchaProvider`, which fixes it by forcing a real remount\n * instead of relying on this same prop swap.\n *\n * Both facts are pinned by `tests/recaptcha-deferred-oracle.test.tsx`, which\n * drives the REAL library and counts script tags in the DOM. They are claims\n * about someone else's code, so prose asserting them is not enough — if a future\n * version of the library injects eagerly, that test goes red and this whole\n * optimisation is known to be void.\n *\n * ── THE ONE COST, MEASURED ──\n *\n * On the empty-key render the library calls its own warn helper, which is\n * written inverted, so the warning fires in PRODUCTION and stays silent in\n * development. A visitor who opens devtools before touching a field sees one\n * `\"<GoogleReCaptchaProvider /> recaptcha key not provided\"`. Cosmetic console\n * noise, traded against a third-party request on every view of the page. Worth\n * it, and recorded here so the next reader knows it is expected.\n *\n * ── AND NO FALLBACK KEY, EVER ──\n *\n * `''` for a blank OR malformed key however armed. There is no hardcoded\n * fallback anywhere in this module, because a captcha key that is not the\n * tenant's fails Google's verification while LOOKING configured — converting a\n * visible gap an owner can fix in nexus into a silent one nobody can.\n * {@link resolveContactFormAvailability} hides the form in that case; this is\n * the second lock on the same door.\n */\nexport function deferredRecaptchaKey(siteKey: string, armed: boolean): string {\n if (!armed) return ''\n const key = trimmed(siteKey)\n return key && isSafeRecaptchaSiteKey(key) ? key : ''\n}\n"],"mappings":";AAyEO,IAAM,mBAAmB;AAiCzB,IAAM,6BAA6B;AAQnC,SAAS,uBAAuB,OAAiC;AACtE,SAAO,OAAO,UAAU,YAAY,2BAA2B,KAAK,KAAK;AAC3E;AAiBO,IAAM,iCAAiC,CAAC,WAAW,WAAW,QAAQ;AAoD7E,SAAS,QAAQ,OAA+B;AAC9C,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,OAAO,MAAM,KAAK;AACxB,SAAO,KAAK,SAAS,IAAI,OAAO;AAClC;AAEA,SAAS,kBAAkB,MAAmD;AAI5E,SAAQ,+BAAqD,SAAS,IAAc;AACtF;AAeO,SAAS,+BACd,WACyB;AACzB,MAAI,CAAC,UAAW,QAAO,EAAE,OAAO,eAAe,QAAQ,aAAa;AAEpE,QAAM,OAAO,UAAU;AACvB,MAAI,CAAC,kBAAkB,IAAI,EAAG,QAAO,EAAE,OAAO,eAAe,QAAQ,uBAAuB;AAO5F,QAAM,mBAAmB,QAAQ,UAAU,gBAAgB;AAC3D,MAAI,CAAC,iBAAkB,QAAO,EAAE,OAAO,eAAe,QAAQ,wBAAwB;AACtF,MAAI,CAAC,uBAAuB,gBAAgB,GAAG;AAC7C,WAAO,EAAE,OAAO,eAAe,QAAQ,0BAA0B;AAAA,EACnE;AAEA,SAAO,EAAE,OAAO,aAAa,MAAM,iBAAiB;AACtD;AAGO,SAAS,uBACd,cAC0E;AAC1E,SAAO,aAAa,UAAU;AAChC;AAiGO,SAAS,qBAAqB,SAAiB,OAAwB;AAC5E,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,MAAM,QAAQ,OAAO;AAC3B,SAAO,OAAO,uBAAuB,GAAG,IAAI,MAAM;AACpD;","names":[]}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/shop/server.ts
|
|
21
|
+
var server_exports = {};
|
|
22
|
+
__export(server_exports, {
|
|
23
|
+
buildShopFilterHrefs: () => buildShopFilterHrefs,
|
|
24
|
+
getShopCollection: () => getShopCollection,
|
|
25
|
+
parseShopSearchParams: () => parseShopSearchParams,
|
|
26
|
+
serializeShopParams: () => serializeShopParams,
|
|
27
|
+
toURLSearchParams: () => toURLSearchParams
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(server_exports);
|
|
30
|
+
|
|
31
|
+
// src/shop/params.ts
|
|
32
|
+
var MAX_Q_LEN = 200;
|
|
33
|
+
var MAX_FILTER_KEYS = 30;
|
|
34
|
+
var MAX_VALUE_LEN = 120;
|
|
35
|
+
var MAX_VALUES_PER_KEY = 30;
|
|
36
|
+
var MAX_LIMIT = 50;
|
|
37
|
+
var SHOP_SORTS = ["price_asc", "price_desc", "newest", "on_sale"];
|
|
38
|
+
function isShopSort(value) {
|
|
39
|
+
return SHOP_SORTS.includes(value);
|
|
40
|
+
}
|
|
41
|
+
function nonNegativeInt(raw) {
|
|
42
|
+
if (raw === null || !/^\d+$/.test(raw)) return void 0;
|
|
43
|
+
const n = Number.parseInt(raw, 10);
|
|
44
|
+
return Number.isNaN(n) ? void 0 : n;
|
|
45
|
+
}
|
|
46
|
+
function toPlainObject(source) {
|
|
47
|
+
return { ...source };
|
|
48
|
+
}
|
|
49
|
+
function parseBracketParams(searchParams, prefix) {
|
|
50
|
+
const out = /* @__PURE__ */ Object.create(null);
|
|
51
|
+
const re = new RegExp(`^${prefix}\\[(.+)\\]$`);
|
|
52
|
+
for (const [rawKey, rawValue] of searchParams.entries()) {
|
|
53
|
+
const match = rawKey.match(re);
|
|
54
|
+
if (!match) continue;
|
|
55
|
+
const key = match[1];
|
|
56
|
+
const value = rawValue.slice(0, MAX_VALUE_LEN);
|
|
57
|
+
if (!(key in out) && Object.keys(out).length >= MAX_FILTER_KEYS) continue;
|
|
58
|
+
const existing = out[key];
|
|
59
|
+
if (existing === void 0) out[key] = value;
|
|
60
|
+
else if (Array.isArray(existing)) {
|
|
61
|
+
if (existing.length < MAX_VALUES_PER_KEY) existing.push(value);
|
|
62
|
+
} else out[key] = [existing, value];
|
|
63
|
+
}
|
|
64
|
+
return Object.keys(out).length > 0 ? toPlainObject(out) : void 0;
|
|
65
|
+
}
|
|
66
|
+
function parseShopSearchParams(searchParams) {
|
|
67
|
+
const params = {};
|
|
68
|
+
const page = nonNegativeInt(searchParams.get("page"));
|
|
69
|
+
if (page !== void 0 && page >= 1) params.page = page;
|
|
70
|
+
const limit = nonNegativeInt(searchParams.get("limit"));
|
|
71
|
+
if (limit !== void 0 && limit >= 1 && limit <= MAX_LIMIT) params.limit = limit;
|
|
72
|
+
const q = searchParams.get("q")?.trim().slice(0, MAX_Q_LEN);
|
|
73
|
+
if (q) params.q = q;
|
|
74
|
+
const sort = searchParams.get("sort");
|
|
75
|
+
if (sort !== null && isShopSort(sort)) params.sort = sort;
|
|
76
|
+
const category = searchParams.get("category")?.trim();
|
|
77
|
+
if (category) params.category = category;
|
|
78
|
+
let priceMin = nonNegativeInt(searchParams.get("priceMin"));
|
|
79
|
+
let priceMax = nonNegativeInt(searchParams.get("priceMax"));
|
|
80
|
+
if (priceMin !== void 0 && priceMax !== void 0 && priceMin > priceMax) {
|
|
81
|
+
;
|
|
82
|
+
[priceMin, priceMax] = [priceMax, priceMin];
|
|
83
|
+
}
|
|
84
|
+
if (priceMin !== void 0) params.priceMin = priceMin;
|
|
85
|
+
if (priceMax !== void 0) params.priceMax = priceMax;
|
|
86
|
+
const onSale = searchParams.get("onSale");
|
|
87
|
+
if (onSale === "true" || onSale === "1") params.onSale = true;
|
|
88
|
+
const taxonomyRaw = parseBracketParams(searchParams, "taxonomy");
|
|
89
|
+
if (taxonomyRaw) {
|
|
90
|
+
const taxonomy = /* @__PURE__ */ Object.create(null);
|
|
91
|
+
for (const [key, value] of Object.entries(taxonomyRaw)) {
|
|
92
|
+
taxonomy[key] = Array.isArray(value) ? value[0] : value;
|
|
93
|
+
}
|
|
94
|
+
params.taxonomy = toPlainObject(taxonomy);
|
|
95
|
+
}
|
|
96
|
+
const attr = parseBracketParams(searchParams, "attr");
|
|
97
|
+
if (attr) params.attr = attr;
|
|
98
|
+
return params;
|
|
99
|
+
}
|
|
100
|
+
function serializeShopParams(params) {
|
|
101
|
+
const sp = new URLSearchParams();
|
|
102
|
+
if (params.page !== void 0) sp.set("page", String(params.page));
|
|
103
|
+
if (params.limit !== void 0) sp.set("limit", String(params.limit));
|
|
104
|
+
if (params.q) sp.set("q", params.q);
|
|
105
|
+
if (params.sort) sp.set("sort", params.sort);
|
|
106
|
+
if (params.category) sp.set("category", params.category);
|
|
107
|
+
if (params.priceMin !== void 0) sp.set("priceMin", String(params.priceMin));
|
|
108
|
+
if (params.priceMax !== void 0) sp.set("priceMax", String(params.priceMax));
|
|
109
|
+
if (params.onSale) sp.set("onSale", "true");
|
|
110
|
+
if (params.taxonomy) {
|
|
111
|
+
for (const [key, value] of Object.entries(params.taxonomy)) {
|
|
112
|
+
if (value) sp.set(`taxonomy[${key}]`, value);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (params.attr) {
|
|
116
|
+
for (const [key, value] of Object.entries(params.attr)) {
|
|
117
|
+
if (Array.isArray(value)) {
|
|
118
|
+
for (const v of value) if (v) sp.append(`attr[${key}]`, v);
|
|
119
|
+
} else if (value) {
|
|
120
|
+
sp.set(`attr[${key}]`, value);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return sp;
|
|
125
|
+
}
|
|
126
|
+
function toURLSearchParams(searchParams) {
|
|
127
|
+
const usp = new URLSearchParams();
|
|
128
|
+
for (const [key, value] of Object.entries(searchParams)) {
|
|
129
|
+
if (value === void 0) continue;
|
|
130
|
+
if (Array.isArray(value)) {
|
|
131
|
+
for (const v of value) usp.append(key, v);
|
|
132
|
+
} else {
|
|
133
|
+
usp.append(key, value);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
return usp;
|
|
137
|
+
}
|
|
138
|
+
function buildShopFilterHrefs(current, pathname) {
|
|
139
|
+
function hrefFor(patch) {
|
|
140
|
+
const next = { ...current, ...patch, page: void 0 };
|
|
141
|
+
const qs = serializeShopParams(next).toString();
|
|
142
|
+
return qs ? `${pathname}?${qs}` : pathname;
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
taxonomy: (axisKey, value) => {
|
|
146
|
+
const taxonomy = { ...current.taxonomy };
|
|
147
|
+
if (value === void 0) delete taxonomy[axisKey];
|
|
148
|
+
else taxonomy[axisKey] = value;
|
|
149
|
+
return hrefFor({ taxonomy });
|
|
150
|
+
},
|
|
151
|
+
attr: (fieldKey, value) => {
|
|
152
|
+
const existing = current.attr?.[fieldKey];
|
|
153
|
+
const values = existing === void 0 ? [] : Array.isArray(existing) ? existing : [existing];
|
|
154
|
+
const next = values.includes(value) ? values.filter((v) => v !== value) : [...values, value];
|
|
155
|
+
const attr = { ...current.attr };
|
|
156
|
+
if (next.length === 0) delete attr[fieldKey];
|
|
157
|
+
else attr[fieldKey] = next;
|
|
158
|
+
return hrefFor({ attr });
|
|
159
|
+
},
|
|
160
|
+
price: (min, max) => hrefFor({ priceMin: min, priceMax: max }),
|
|
161
|
+
onSale: (nextActive) => hrefFor({ onSale: nextActive || void 0 }),
|
|
162
|
+
// Clears every FACET dimension only — q/category/sort (the non-facet part
|
|
163
|
+
// of the query) are deliberately preserved, mirroring ShopFilters' own
|
|
164
|
+
// onChange clear-all patch.
|
|
165
|
+
clearAll: () => hrefFor({ taxonomy: void 0, attr: void 0, priceMin: void 0, priceMax: void 0, onSale: void 0 })
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// src/shop/collection.ts
|
|
170
|
+
var EMPTY_FACETS = {
|
|
171
|
+
taxonomies: [],
|
|
172
|
+
attributes: [],
|
|
173
|
+
price: { min: 0, max: 0 },
|
|
174
|
+
onSale: { count: 0 }
|
|
175
|
+
};
|
|
176
|
+
async function getShopCollection(client, params) {
|
|
177
|
+
const [productsResult, facetsResult] = await Promise.allSettled([
|
|
178
|
+
client.shop.products(params),
|
|
179
|
+
client.shop.facets(params)
|
|
180
|
+
]);
|
|
181
|
+
if (productsResult.status === "rejected") {
|
|
182
|
+
throw productsResult.reason;
|
|
183
|
+
}
|
|
184
|
+
if (facetsResult.status === "rejected") {
|
|
185
|
+
console.warn("[getShopCollection] facets fetch failed, degrading to empty ShopFacets:", facetsResult.reason);
|
|
186
|
+
return { products: productsResult.value, facets: EMPTY_FACETS, facetsStatus: "unavailable" };
|
|
187
|
+
}
|
|
188
|
+
return { products: productsResult.value, facets: facetsResult.value, facetsStatus: "ok" };
|
|
189
|
+
}
|
|
190
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
191
|
+
0 && (module.exports = {
|
|
192
|
+
buildShopFilterHrefs,
|
|
193
|
+
getShopCollection,
|
|
194
|
+
parseShopSearchParams,
|
|
195
|
+
serializeShopParams,
|
|
196
|
+
toURLSearchParams
|
|
197
|
+
});
|
|
198
|
+
//# sourceMappingURL=shop-server.cjs.map
|