Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/captcha/Captcha.tsx
T
2026-07-08 16:15:37 +02:00

99 lines
3.3 KiB
TypeScript

import { createElement, useEffect, useRef } from "react";
interface Props {
/** Render the captcha widget. When false (or unconfigured) nothing is rendered. */
enabled: boolean;
/** Active self-hosted provider. Defaults to mCaptcha for compatibility. */
provider?: "mcaptcha" | "cap";
/** Public base URL of the self-hosted captcha instance. */
instanceUrl?: string;
/** Public sitekey for this surface. */
sitekey?: string;
}
// mCaptcha's vanilla glue mounts the widget into an element with this id and
// injects a hidden <input name="mcaptcha__token"> into the enclosing <form>
// on solve. Keep in sync with @mcaptcha/vanilla-glue (exported `ID`).
const MOUNT_ID = "mcaptcha__widget-container";
/**
* Self-hosted captcha widget — replaces the former no-op RecaptchaWrapper.
*
* Render this **inside** the <form> it should protect: the provider injects a
* hidden token field (`cap-token` or `mcaptcha__token`), so it is submitted
* with the form and verified server-side by `@hivegrid/captcha`.
*
* Client load failures are non-fatal. The server verifier applies
* CAPTCHA_FAIL_OPEN for provider outages, while a missing token remains a hard
* failure when captcha is required.
*/
export default function Captcha({ enabled, provider = "mcaptcha", instanceUrl, sitekey }: Props) {
const active = enabled && Boolean(instanceUrl && sitekey);
const initialized = useRef(false);
useEffect(() => {
if (!active || initialized.current) return;
initialized.current = true;
let cancelled = false;
void (async () => {
try {
if (provider === "cap") {
loadCapAssets(instanceUrl!);
return;
}
const { default: Widget } = await import("@mcaptcha/vanilla-glue");
if (cancelled) return;
// Widget self-mounts into #MOUNT_ID and injects the hidden mcaptcha__token field.
void new Widget({ siteKey: { instanceUrl: new URL(instanceUrl!), key: sitekey! } });
} catch (err) {
console.error("mCaptcha widget failed to initialise", err);
}
})();
return () => {
cancelled = true;
};
}, [active, instanceUrl, provider, sitekey]);
if (!active) return null;
if (provider === "cap") {
return (
<>
{/*
Cap's custom element injects <input name="cap-token"> into the
enclosing form when solved.
*/}
{createCapWidget(instanceUrl!, sitekey!)}
</>
);
}
return <div id={MOUNT_ID} className="m-captcha" data-ui-id="ui.captcha.mount" />;
}
function createCapWidget(instanceUrl: string, sitekey: string) {
return createElement("cap-widget", {
required: true,
"data-cap-api-endpoint": `${instanceUrl.replace(/\/+$/, "")}/${sitekey}/`,
"data-ui-id": "ui.captcha.mount",
});
}
function loadCapAssets(instanceUrl: string): void {
const base = instanceUrl.replace(/\/+$/, "");
const scriptSrc = `${base}/assets/widget.js`;
window.CAP_CUSTOM_WASM_URL = `${base}/assets/cap_wasm_bg.wasm`;
if (document.querySelector(`script[data-cap-widget-loader="true"][src="${scriptSrc}"]`)) return;
const script = document.createElement("script");
script.type = "module";
script.async = true;
script.defer = true;
script.src = scriptSrc;
script.dataset.capWidgetLoader = "true";
document.head.appendChild(script);
}
declare global {
interface Window {
CAP_CUSTOM_WASM_URL?: string;
}
}