Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/components/captcha/Captcha.tsx
T

126 lines
4.5 KiB
TypeScript

import { createElement, useEffect, useRef } from "react";
import type { Ref } from "react";
import { getCurrentDocumentCspNonce } from "~/utils/security/documentCspNonce";
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;
/** Reports whether a reusable form may submit a fresh proof. */
onStatusChange?: (status: "pending" | "solved" | "error") => void;
}
// 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 leave the form unsolved. The server verifier fails
* closed in deployed runtimes; a local development/test process may explicitly
* opt into fail-open behavior.
*/
export default function Captcha({ enabled, provider = "mcaptcha", instanceUrl, sitekey, onStatusChange }: Props) {
const active = enabled && Boolean(instanceUrl && sitekey);
const initialized = useRef(false);
const capWidgetRef = useRef<HTMLElement | null>(null);
useEffect(() => {
if (!active) return;
onStatusChange?.("pending");
if (provider !== "cap") return;
const widget = capWidgetRef.current;
if (!widget) return;
const solved = () => onStatusChange?.("solved");
const reset = () => onStatusChange?.("pending");
const failed = () => onStatusChange?.("error");
widget.addEventListener("solve", solved);
widget.addEventListener("reset", reset);
widget.addEventListener("error", failed);
return () => {
widget.removeEventListener("solve", solved);
widget.removeEventListener("reset", reset);
widget.removeEventListener("error", failed);
};
}, [active, onStatusChange, provider]);
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!, capWidgetRef)}
</>
);
}
return <div id={MOUNT_ID} className="m-captcha" data-ui-id="ui.captcha.mount" />;
}
function createCapWidget(instanceUrl: string, sitekey: string, ref: Ref<HTMLElement>) {
return createElement("cap-widget", {
ref,
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";
const nonce = getCurrentDocumentCspNonce(document);
if (nonce) script.nonce = nonce;
document.head.appendChild(script);
}
declare global {
interface Window {
CAP_CUSTOM_WASM_URL?: string;
}
}