@nice2dev/ui-security 1.2.1 → 1.3.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 CHANGED
@@ -1,5 +1,48 @@
1
1
  # @nice2dev/ui-security — Changelog
2
2
 
3
+ ## 1.3.0
4
+
5
+ No changes in this release.
6
+
7
+ ## 1.2.2
8
+
9
+ ### Patch Changes
10
+
11
+ - 06eb0d2: 1.2.2 — library texts through the translator, a translator in the packages that had none, and the
12
+ end of the hook-dependency warnings. Nothing removed or renamed. Upgrade notes:
13
+ `documentation/omniverk/OMNIVERK_UPGRADE_1.2.2.md`.
14
+
15
+ **Translations.** 2,825 new keys in the global dictionary (en, pl, de, fr, es, uk), 80 in the local
16
+ dictionaries of ui-math, ui-diagrams and ui-presentations: column headers, option labels, texts in
17
+ conditions and templates, messages given to setters, labels returned by helpers, Polish texts that
18
+ were the English default. Relative dates through `Intl.RelativeTimeFormat`, plural forms through
19
+ `…One` / `…Many` keys. ui-science, ui-platform, ui-mobile, auth, licensing, templates, social and
20
+ the icon tools translate through `useNiceTranslation` (new peer `@nice2dev/ui-core ^1.2.0`);
21
+ ui-security reads the global translator when its own provider is absent.
22
+
23
+ **Additions.** `labelKey` on ui-mobile `TabItem` and `SwipeAction` (the presets set it);
24
+ `registerWebAuthn` / `authenticateWebAuthn` take the WebAuthn options `NiceWebAuthnButton` used to
25
+ drop (defaults unchanged); `NiceKeyboardHint` shows `descriptionKey`. Eight icons in
26
+ `@nice2dev/icons` — `NtdPoint`, `NtdSegment`, `NtdPerpendicular`, `NtdParallel`, `NtdMidpoint`,
27
+ `NtdAngleBisector`, `NtdGroup`, `NtdUngroup` — and the same names as `NiceIcon` built-ins.
28
+
29
+ **Behaviour changes, agreed.** ui-math, ui-diagrams and ui-presentations follow the app's global
30
+ `NiceI18nProvider` language when their own provider is absent (they stayed English);
31
+ `NicePresentationEditor` without `lang` takes the surrounding language. Icons drawn as glyphs are
32
+ Nice icons: the `NiceGeometry` tools, Align / Group / Ungroup / Layout of the diagram toolbar, the
33
+ presentation grid toggle, zoom and "Add Track" of `NiceDMXTimeline`. icons-gaming and
34
+ icons-filetypes name an icon by its `title` and are decorative without one, like `createIcon`
35
+ (screen readers read "GiHeart" or "DOCX file icon"); new optional `title` on the gaming icon props.
36
+
37
+ **Hook dependencies (161 → 0).** Fixed along the way: `NiceLowPowerMode` re-rendered forever from
38
+ mount and overflowed the stack on wake; `GenericPlayer` / `NiceGenericPlayerStage` restarted the
39
+ track on a volume change; `NiceDMXTimeline` called `onPlay` on every frame and missed cues added
40
+ during playback; `NiceConflictResolution` `autoResolve` never resolved; `NiceMAM` selected by the
41
+ previous filter; `NiceRulesEngine` "Run All" kept only the last result; `NiceCodeEditor` saved with
42
+ the first render's `onSave`; a consumer's cursor handler switched off `NiceCodeEditorAI`
43
+ completion; `useRadioStream` lost a volume set before the first play; `NiceGameEditor` shortcuts,
44
+ `useVoiceControl` continuous sessions, `NiceDeviceTrust` with a host storing the score.
45
+
3
46
  ## 1.2.1
4
47
 
5
48
  ### Patch Changes
@@ -92,12 +92,22 @@ export declare function registerWebAuthn(options: {
92
92
  userDisplayName: string;
93
93
  challenge: BufferSource;
94
94
  timeout?: number;
95
+ /** Default: 'none' */
96
+ attestation?: AttestationConveyancePreference;
97
+ /** Default: 'platform' */
98
+ authenticatorAttachment?: AuthenticatorAttachment;
99
+ /** Default: 'preferred' */
100
+ residentKey?: ResidentKeyRequirement;
101
+ /** Default: 'required' */
102
+ userVerification?: UserVerificationRequirement;
95
103
  }): Promise<PublicKeyCredential | null>;
96
104
  export declare function authenticateWebAuthn(options: {
97
105
  rpId: string;
98
106
  challenge: BufferSource;
99
107
  allowCredentials?: PublicKeyCredentialDescriptor[];
100
108
  timeout?: number;
109
+ /** Default: 'required' */
110
+ userVerification?: UserVerificationRequirement;
101
111
  }): Promise<PublicKeyCredential | null>;
102
112
  export declare function verifyWithBackend(endpoint: string, payload: {
103
113
  method: BiometricMethod;
@@ -5,6 +5,7 @@ export interface NiceI18nProviderProps {
5
5
  t: NiceTranslateFn;
6
6
  children: React.ReactNode;
7
7
  }
8
+ /** Overrides the app's global translator for the security controls below it. */
8
9
  export declare const NiceI18nProvider: React.FC<NiceI18nProviderProps>;
9
10
  export declare function useNiceTranslation(): {
10
11
  t: NiceTranslateFn;
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),h=require("react"),de=require("@nice2dev/icons"),qe={low:.7,medium:.8,high:.85,critical:.95},Ke={matchThreshold:.85,timeout:3e4,maxRetries:3,livenessDetection:!0,verifyEndpoint:"",authToken:"",showFeedback:!0,hapticFeedback:!0,locale:"en",securityLevel:"high",antiSpoofing:!0};function oe(e){const t={...Ke,...e};return e!=null&&e.matchThreshold||(t.matchThreshold=qe[t.securityLevel]),t}async function ce(e){const t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}function he(e=8){const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t).map(r=>r.toString(36).padStart(2,"0")).join("").slice(0,e)}function Ge(e){const t=new Uint32Array(1);return crypto.getRandomValues(t),t[0]%e}function Ye(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}async function le(e="user"){return navigator.mediaDevices.getUserMedia({video:{facingMode:e,width:{ideal:1280},height:{ideal:720}},audio:!1})}function se(e,t,r){const n=t??e.videoWidth,a=r??e.videoHeight,i=document.createElement("canvas");i.width=n,i.height=a;const o=i.getContext("2d");o.drawImage(e,0,0,n,a);const c=o.getImageData(0,0,n,a);return{canvas:i,ctx:o,imageData:c}}function ne(e){const t=new Uint8Array(e.width*e.height),r=e.data;for(let n=0;n<t.length;n++){const a=n*4;t[n]=Math.round(.299*r[a]+.587*r[a+1]+.114*r[a+2])}return t}function je(e,t,r){const n=new Uint8Array(t*r),a=[1,2,1,2,4,2,1,2,1],i=16;for(let o=1;o<r-1;o++)for(let c=1;c<t-1;c++){let m=0,x=0;for(let y=-1;y<=1;y++)for(let v=-1;v<=1;v++)m+=e[(o+y)*t+(c+v)]*a[x++];n[o*t+c]=Math.round(m/i)}return n}function Je(e,t,r){const n=new Uint8Array(t*r);for(let a=1;a<r-1;a++)for(let i=1;i<t-1;i++){const o=-e[(a-1)*t+(i-1)]+e[(a-1)*t+(i+1)]+-2*e[a*t+(i-1)]+2*e[a*t+(i+1)]+-e[(a+1)*t+(i-1)]+e[(a+1)*t+(i+1)],c=-e[(a-1)*t+(i-1)]-2*e[(a-1)*t+i]-e[(a-1)*t+(i+1)]+e[(a+1)*t+(i-1)]+2*e[(a+1)*t+i]+e[(a+1)*t+(i+1)];n[a*t+i]=Math.min(255,Math.round(Math.sqrt(o*o+c*c)))}return n}function Ze(e){const t=new Array(256).fill(0);for(const x of e)t[x]++;const r=e.length;let n=0;for(let x=0;x<256;x++)n+=x*t[x];let a=0,i=0,o=0,c=0;for(let x=0;x<256;x++){if(i+=t[x],i===0)continue;const y=r-i;if(y===0)break;a+=x*t[x];const v=a/i,A=(n-a)/y,p=i*y*(v-A)**2;p>o&&(o=p,c=x)}const m=new Uint8Array(e.length);for(let x=0;x<e.length;x++)m[x]=e[x]>c?255:0;return{threshold:c,binary:m}}function Te(e,t=.3){var g;const r=e.width,n=e.height,a=ne(e),i=je(a,r,n),o=Je(i,r,n),{binary:c}=Ze(o),m=[],x=[],y=[];for(let k=2;k<n-2;k++)for(let u=2;u<r-2;u++){if(c[k*r+u]===0)continue;const S=[c[(k-1)*r+u],c[(k-1)*r+(u+1)],c[k*r+(u+1)],c[(k+1)*r+(u+1)],c[(k+1)*r+u],c[(k+1)*r+(u-1)],c[k*r+(u-1)],c[(k-1)*r+(u-1)]];let l=0;for(let _=0;_<8;_++){const H=S[_]>0?1:0,K=S[(_+1)%8]>0?1:0;l+=Math.abs(H-K)}l/=2;let f=0,z=0;for(let _=-2;_<=2;_++)for(let H=-2;H<=2;H++)f+=o[(k+_)*r+(u+H)],z++;const U=f/z/255;if(U<t)continue;const G=Math.atan2(a[(k+1)*r+u]-a[(k-1)*r+u],a[k*r+(u+1)]-a[k*r+(u-1)]);l===1?m.push({x:u/r,y:k/n,angle:G,type:"ending",quality:U}):l===3&&m.push({x:u/r,y:k/n,angle:G,type:"bifurcation",quality:U})}m.sort((k,u)=>u.quality-k.quality);const v=m.slice(0,120);if(v.length>5){const k=v.reduce((S,l)=>S+l.x,0)/v.length,u=v.reduce((S,l)=>S+l.y,0)/v.length;x.push({x:k,y:u})}const A=v.length,p=v.filter(k=>k.type==="ending").length,D=v.filter(k=>k.type==="bifurcation").length/(p+1);let b="loop-right";D>1.5?b="whorl":D<.5?b="arch":((g=x[0])==null?void 0:g.x)<.45&&(b="loop-left");const T=v.length>20?v.reduce((k,u)=>k+u.quality,0)/v.length:0;return{minutiae:v,corePoints:x,deltaPoints:y,ridgeCount:A,patternType:b,quality:T}}function Ce(e,t){if(e.minutiae.length<5||t.minutiae.length<5)return 0;let r=0;const n=.05,a=.5,i=new Set;for(const c of e.minutiae){let m=1/0,x=-1;for(let y=0;y<t.minutiae.length;y++){if(i.has(y))continue;const v=t.minutiae[y];if(c.type!==v.type)continue;const A=Ye(c,v),p=Math.abs(c.angle-v.angle);A<n&&p<a&&A<m&&(m=A,x=y)}x>=0&&(r++,i.add(x))}const o=Math.min(e.minutiae.length,t.minutiae.length);return o>0?r/o:0}async function Ie(e,t){const r=JSON.stringify(e),n=await ce(r);return{id:`fp_${Date.now()}_${he()}`,method:"fingerprint",templateData:btoa(r),enrolled:Date.now(),label:t,hash:n}}function Re(e){return JSON.parse(atob(e.templateData))}function De(e,t="left"){const r=e.width,n=e.height,a=ne(e),i=je(a,r,n);let o={cx:r/2,cy:n/2,r:Math.min(r,n)*.08,score:1/0};for(let I=Math.round(n*.3);I<Math.round(n*.7);I+=2)for(let D=Math.round(r*.3);D<Math.round(r*.7);D+=2)for(let b=Math.round(Math.min(r,n)*.04);b<Math.round(Math.min(r,n)*.15);b+=2){let T=0,g=0;for(let l=0;l<Math.PI*2;l+=.3){const f=Math.round(D+b*Math.cos(l)),z=Math.round(I+b*Math.sin(l));f>=0&&f<r&&z>=0&&z<n&&(T+=i[z*r+f],g++)}const k=g>0?T/g:255,u=i[I*r+D],S=k*.5+u*.5;S<o.score&&(o={cx:D,cy:I,r:b,score:S})}const c=o.r*3,m={cx:o.cx,cy:o.cy,r:Math.min(c,Math.min(r,n)*.4)},x=256,y=[];for(let I=0;I<x;I++){const D=I/x*Math.PI*2,b=o.r+(m.r-o.r)*.5,T=Math.round(o.cx+b*Math.cos(D)),g=Math.round(o.cy+b*Math.sin(D));if(T>=0&&T<r&&g>=0&&g<n){const k=Math.round(o.cx+b*Math.cos(D+.1)),u=Math.round(o.cy+b*Math.sin(D+.1)),S=i[g*r+T],l=k>=0&&k<r&&u>=0&&u<n?i[u*r+k]:S;y.push(S>l?1:0)}else y.push(0)}const v=y.join(""),A=Math.PI*o.r**2,p=Math.min(1,Math.max(0,A/(r*n)*100));return{irisCode:v,pupil:o,iris:m,quality:p,eye:t}}function Pe(e,t){if(!e.irisCode||!t.irisCode)return 0;const r=Math.min(e.irisCode.length,t.irisCode.length);if(r===0)return 0;let n=0,a=r;for(let o=-8;o<=8;o++){let c=0;for(let m=0;m<r;m++){const x=(m+o+r)%r;e.irisCode[m]!==t.irisCode[x]&&c++}c<a&&(a=c)}n=a;const i=n/r;return Math.max(0,1-i*2.5)}async function Me(e,t){const r=JSON.stringify(e),n=await ce(r);return{id:`iris_${Date.now()}_${he()}`,method:"iris",templateData:btoa(r),enrolled:Date.now(),label:t,hash:n}}function Ee(e){return JSON.parse(atob(e.templateData))}function ae(e){const t=e.width,r=e.height,n=e.data,a=new Uint8Array(t*r);for(let u=0;u<t*r;u++){const S=u*4,l=n[S],f=n[S+1],z=n[S+2],U=.299*l+.587*f+.114*z,G=128-.169*l-.331*f+.5*z,_=128+.5*l-.419*f-.081*z;G>=77&&G<=127&&_>=133&&_<=173&&U>80&&(a[u]=1)}let i=t,o=r,c=0,m=0,x=0;for(let u=0;u<r;u++)for(let S=0;S<t;S++)a[u*t+S]&&(x++,S<i&&(i=S),S>c&&(c=S),u<o&&(o=u),u>m&&(m=u));const y=c-i,v=m-o;if(y<t*.1||v<r*.1)return null;const A={x:i,y:o,width:y,height:v},p=[],I=ne(e),D=Math.max(1,Math.floor(y/8)),b=Math.max(1,Math.floor(v/16));for(let u=0;u<16;u++)for(let S=0;S<8;S++){const l=i+S*D+Math.floor(D/2),f=o+u*b+Math.floor(b/2);l<t&&f<r?p.push(I[f*t+l]/255):p.push(0)}const T=[],g={x:i+y/2,y:o+v/2};for(let u=0;u<68;u++){const S=u/68*Math.PI*2,l=y*.4*Math.cos(S),f=v*.45*Math.sin(S);T.push({x:(g.x+l)/t,y:(g.y+f)/r})}const k=Math.min(1,x/(y*v)*2);return{embedding:p,boundingBox:A,landmarks:T,headPose:{yaw:0,pitch:0,roll:0},quality:k}}function fe(e,t){if(e.embedding.length!==t.embedding.length)return 0;let r=0,n=0,a=0;for(let o=0;o<e.embedding.length;o++)r+=e.embedding[o]*t.embedding[o],n+=e.embedding[o]**2,a+=t.embedding[o]**2;const i=Math.sqrt(n)*Math.sqrt(a);return i>0?(r/i+1)/2:0}function Fe(e,t){const r=ae(e),n=ae(t);return!r||!n?{similarity:0,cameraFeatures:r,refFeatures:n}:{similarity:fe(r,n),cameraFeatures:r,refFeatures:n}}async function Ne(e,t){const r=JSON.stringify(e),n=await ce(r);return{id:`face_${Date.now()}_${he()}`,method:"face",templateData:btoa(r),enrolled:Date.now(),label:t,hash:n}}function ze(e){return JSON.parse(atob(e.templateData))}function Xe(){const e=["blink","smile","turn-left","turn-right","nod","raise-eyebrows"],t=e[Ge(e.length)];return{type:t,instruction:{blink:"Please blink your eyes",smile:"Please smile","turn-left":"Please turn your head left","turn-right":"Please turn your head right",nod:"Please nod your head","raise-eyebrows":"Please raise your eyebrows"}[t],completed:!1,confidence:0}}function ye(e,t=.02){if(e.length<2)return{isLive:!1,confidence:0,motionScore:0};let r=0;for(let o=1;o<e.length;o++){const c=ne(e[o-1]),m=ne(e[o]);let x=0;for(let y=0;y<c.length;y++)x+=Math.abs(c[y]-m[y]);r+=x/(c.length*255)}const n=r/(e.length-1),a=n>t,i=Math.min(1,n/(t*3));return{isLive:a,confidence:i,motionScore:n}}function pe(){return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,screenResolution:[screen.width,screen.height],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,hardwareConcurrency:navigator.hardwareConcurrency??0}}async function ie(){const e=pe(),t=JSON.stringify(e);return ce(t)}function ge(){return typeof window<"u"&&!!window.PublicKeyCredential}async function Le(){if(!ge())return!1;try{return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function $e(e){const t={rp:{name:e.rpName,id:e.rpId},user:{id:new TextEncoder().encode(e.userId),name:e.userName,displayName:e.userDisplayName},challenge:e.challenge,pubKeyCredParams:[{alg:-7,type:"public-key"},{alg:-257,type:"public-key"}],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"required",residentKey:"preferred"},timeout:e.timeout??6e4,attestation:"none"};return await navigator.credentials.create({publicKey:t})}async function _e(e){const t={rpId:e.rpId,challenge:e.challenge,allowCredentials:e.allowCredentials,userVerification:"required",timeout:e.timeout??6e4};return await navigator.credentials.get({publicKey:t})}async function ue(e,t,r){const n={"Content-Type":"application/json"};r&&(n.Authorization=`Bearer ${r}`);const a=await fetch(e,{method:"POST",headers:n,body:JSON.stringify(t)});return a.ok?a.json():{verified:!1,message:`Server error: ${a.status}`}}function V(e,t){var o;const r=e.trim().match(/^var\(\s*([^,\s)]+)\s*(?:,\s*(.+))?\)$/);if(!r)return e;const n=(o=r[2])==null?void 0:o.trim();if(typeof document>"u"||typeof getComputedStyle>"u")return n?V(n):e;const a=typeof Element<"u"&&t instanceof Element&&t.isConnected?t:document.documentElement,i=getComputedStyle(a).getPropertyValue(r[1]).trim();return i||(n?V(n,t):e)}const Qe=(e,t)=>t,Be=h.createContext(Qe),Ve=({t:e,children:t})=>s.jsx(Be.Provider,{value:e,children:t});function Q(){return{t:h.useContext(Be)}}const et={sm:200,md:280,lg:380},tt=e=>{const{mode:t,enrolledTemplates:r=[],fingerPosition:n="right-index",onEnroll:a,onVerify:i,onStatusChange:o,onError:c,className:m,size:x="md",label:y,showQuality:v=!0,showMinutiae:A=!1,instructionText:p,cameraFacing:I="environment",...D}=e,{t:b}=Q(),T=oe(D),g=et[x],k=h.useRef(null),u=h.useRef(null),S=h.useRef(null),[l,f]=h.useState("idle"),[z,U]=h.useState(0),[G,_]=h.useState(null),[H,K]=h.useState(0),[B,L]=h.useState(""),$=h.useCallback(M=>{f(M),o==null||o(M)},[o]),E=h.useCallback(async()=>{try{const M=await le(I);S.current=M,k.current&&(k.current.srcObject=M,await k.current.play()),$("idle"),L(b("security.fingerprint.placeFingerPrompt","Place your finger on the scanner"))}catch(M){c==null||c(M instanceof Error?M:new Error(String(M))),L(b("security.fingerprint.cameraError","Camera access denied")),$("error")}},[I,b,$,c]),q=h.useCallback(()=>{var M;(M=S.current)==null||M.getTracks().forEach(R=>R.stop()),S.current=null},[]);h.useEffect(()=>(E(),q),[E,q]);const W=h.useCallback(async()=>{if(!(!k.current||l==="processing"||l==="success")){$("scanning"),L(b("security.fingerprint.scanning","Scanning…"));try{const{imageData:M}=se(k.current);$("processing"),L(b("security.fingerprint.processing","Processing fingerprint…"));const R=Te(M);if(_(R),U(R.quality),R.quality<.2){L(b("security.fingerprint.lowQuality","Low quality — try again")),$("idle");return}if(t==="enroll"){const F=await Ie(R,y??n);a==null||a(F,R),L(b("security.fingerprint.enrolled","Fingerprint enrolled successfully")),$("success")}else{let F=0;for(const d of r){const j=Re(d),N=Ce(R,j);N>F&&(F=N)}const C=F>=T.matchThreshold,w={success:C,confidence:F,method:"fingerprint",timestamp:Date.now(),duration:0,payload:btoa(JSON.stringify(R))};if(C&&T.verifyEndpoint){const d=await ie(),j=await ue(T.verifyEndpoint,{method:"fingerprint",templateData:w.payload,matchScore:F,deviceFingerprint:d},T.authToken);w.success=j.verified}w.success?(L(b("security.fingerprint.verified","Fingerprint verified")),$("success")):(K(d=>d+1),H+1>=T.maxRetries?(L(b("security.fingerprint.maxAttempts","Maximum attempts reached")),$("failure")):(L(b("security.fingerprint.noMatch","No match — try again")),$("idle"))),i==null||i(w)}}catch(M){c==null||c(M instanceof Error?M:new Error(String(M))),L(b("security.fingerprint.error","Scan error — try again")),$("error")}}},[l,t,r,T,b,$,a,i,c,y,n,H]);h.useEffect(()=>{if(!A||!G||!u.current)return;const M=u.current.getContext("2d");if(!M)return;M.clearRect(0,0,g,g);const R=V("var(--nice-success, #10b981)",M.canvas),F=V("var(--nice-warning, #f59e0b)",M.canvas);G.minutiae.forEach(C=>{M.beginPath(),M.arc(C.x*g,C.y*g,2,0,Math.PI*2),M.fillStyle=C.type==="ending"?R:F,M.fill(),M.beginPath(),M.moveTo(C.x*g,C.y*g),M.lineTo(C.x*g+Math.cos(C.angle)*8,C.y*g+Math.sin(C.angle)*8),M.strokeStyle=M.fillStyle,M.lineWidth=1,M.stroke()})},[G,A,g]);const Z=l==="success"?"var(--security-success)":l==="failure"||l==="error"?"var(--security-error)":l==="scanning"||l==="processing"?"var(--security-biometric)":"var(--security-border)";return s.jsxs("div",{className:m,style:{display:"inline-flex",flexDirection:"column",alignItems:"center",gap:12},children:[y&&s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"var(--security-text)"},children:y}),s.jsxs("div",{style:{width:g,height:g,position:"relative",borderRadius:"var(--security-radius-lg)",overflow:"hidden",border:`3px solid ${Z}`,boxShadow:l==="scanning"?`0 0 20px ${Z}`:"var(--security-shadow)",transition:"border-color 0.3s, box-shadow 0.3s"},children:[s.jsx("video",{ref:k,style:{width:"100%",height:"100%",objectFit:"cover"},playsInline:!0,muted:!0}),A&&s.jsx("canvas",{ref:u,width:g,height:g,style:{position:"absolute",inset:0,pointerEvents:"none"}}),s.jsxs("svg",{viewBox:"0 0 100 100",style:{position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none",opacity:.3},children:[s.jsx("ellipse",{cx:"50",cy:"50",rx:"28",ry:"38",fill:"none",stroke:"white",strokeWidth:"1",strokeDasharray:"4 3"}),s.jsx("ellipse",{cx:"50",cy:"50",rx:"20",ry:"28",fill:"none",stroke:"white",strokeWidth:"0.5",strokeDasharray:"2 3"})]}),(l==="scanning"||l==="processing")&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-30, rgba(0, 0, 0, 0.3))"},children:s.jsx("div",{style:{width:60,height:60,borderRadius:"50%",border:"3px solid transparent",borderTopColor:Z,animation:"spin 0.8s linear infinite"}})})]}),v&&z>0&&s.jsx("div",{style:{width:g,height:4,background:"var(--security-bg-panel)",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{width:`${z*100}%`,height:"100%",background:z>.6?"var(--security-success)":z>.3?"var(--security-warning)":"var(--security-error)",transition:"width 0.3s"}})}),s.jsx("div",{style:{fontSize:13,color:"var(--security-text-secondary)",textAlign:"center",minHeight:20},children:p??B}),l!=="success"&&l!=="failure"&&s.jsx("button",{onClick:W,disabled:l==="scanning"||l==="processing",style:{padding:"10px 24px",fontSize:14,fontWeight:600,background:"var(--security-biometric)",color:"var(--nice-color-white, #fff)",border:"none",borderRadius:"var(--security-radius)",cursor:"pointer",opacity:l==="scanning"||l==="processing"?.6:1},children:t==="enroll"?b("security.fingerprint.captureBtn","Capture Fingerprint"):b("security.fingerprint.verifyBtn","Verify Fingerprint")}),(l==="failure"||l==="error")&&s.jsx("button",{onClick:()=>{K(0),$("idle"),L("")},style:{padding:"8px 20px",fontSize:13,background:"var(--security-bg-panel)",color:"var(--security-text)",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",cursor:"pointer"},children:b("security.common.retry","Try Again")}),s.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]})},rt={sm:220,md:300,lg:400},st=e=>{const{mode:t,enrolledTemplates:r=[],eye:n="right",onEnroll:a,onVerify:i,onStatusChange:o,onError:c,className:m,size:x="md",label:y,showQuality:v=!0,showSegmentation:A=!0,showGuide:p=!0,instructionText:I,...D}=e,{t:b}=Q(),T=oe(D),g=rt[x],k=h.useRef(null),u=h.useRef(null),S=h.useRef(null),l=h.useRef([]),[f,z]=h.useState("idle"),[U,G]=h.useState(0),[_,H]=h.useState(null),[K,B]=h.useState(0),[L,$]=h.useState(""),E=h.useCallback(R=>{z(R),o==null||o(R)},[o]),q=h.useCallback(async()=>{try{const R=await le("user");S.current=R,k.current&&(k.current.srcObject=R,await k.current.play()),E("idle"),$(b("security.iris.alignEyePrompt","Align your eye with the circle"))}catch(R){c==null||c(R instanceof Error?R:new Error(String(R))),$(b("security.iris.cameraError","Camera access denied")),E("error")}},[b,E,c]),W=h.useCallback(()=>{var R;(R=S.current)==null||R.getTracks().forEach(F=>F.stop()),S.current=null},[]);h.useEffect(()=>(q(),W),[q,W]);const Z=h.useCallback(async()=>{if(!(!k.current||f==="processing"||f==="success")){E("scanning"),$(b("security.iris.scanning","Scanning iris…"));try{const R=[];for(let w=0;w<5;w++){const{imageData:d}=se(k.current);R.push(d),await new Promise(j=>setTimeout(j,200))}if(l.current=R,T.livenessDetection&&!ye(R).isLive){$(b("security.iris.notLive","Liveness check failed — please blink or move slightly")),E("idle");return}E("processing"),$(b("security.iris.processing","Processing iris pattern…"));const F=R[R.length-1],C=De(F,n==="both"?"left":n);if(!C){$(b("security.iris.noIrisDetected","No iris detected — adjust position")),E("idle");return}if(H(C),G(C.quality),C.quality<.1){$(b("security.iris.lowQuality","Low quality — move closer")),E("idle");return}if(A&&u.current){const w=u.current.getContext("2d");if(w){w.clearRect(0,0,g,g);const d=g/F.width,j=g/F.height;w.beginPath(),w.arc(C.pupil.cx*d,C.pupil.cy*j,C.pupil.r*d,0,Math.PI*2),w.strokeStyle=V("var(--nice-danger, #ef4444)",w.canvas),w.lineWidth=2,w.stroke(),w.beginPath(),w.arc(C.iris.cx*d,C.iris.cy*j,C.iris.r*d,0,Math.PI*2),w.strokeStyle=V("var(--nice-primary, #3b82f6)",w.canvas),w.lineWidth=2,w.stroke()}}if(t==="enroll"){const w=await Me(C,y??`${n} eye`);a==null||a(w,C),$(b("security.iris.enrolled","Iris enrolled successfully")),E("success")}else{let w=0;for(const N of r){const P=Ee(N),O=Pe(C,P);O>w&&(w=O)}const d=w>=T.matchThreshold,j={success:d,confidence:w,method:"iris",timestamp:Date.now(),duration:0,livenessPassed:T.livenessDetection?!0:void 0,payload:btoa(JSON.stringify(C))};if(d&&T.verifyEndpoint){const N=await ie(),P=await ue(T.verifyEndpoint,{method:"iris",templateData:j.payload,matchScore:w,deviceFingerprint:N},T.authToken);j.success=P.verified}j.success?($(b("security.iris.verified","Iris verified")),E("success")):(B(N=>N+1),K+1>=T.maxRetries?($(b("security.iris.maxAttempts","Maximum attempts reached")),E("failure")):($(b("security.iris.noMatch","No match — try again")),E("idle"))),i==null||i(j)}}catch(R){c==null||c(R instanceof Error?R:new Error(String(R))),$(b("security.iris.error","Scan error")),E("error")}}},[f,t,r,T,b,E,a,i,c,y,n,K,A,g]),M=f==="success"?"var(--security-success)":f==="failure"||f==="error"?"var(--security-error)":f==="scanning"||f==="processing"?"var(--security-biometric)":"var(--security-border)";return s.jsxs("div",{className:m,style:{display:"inline-flex",flexDirection:"column",alignItems:"center",gap:12},children:[y&&s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"var(--security-text)"},children:y}),s.jsxs("div",{style:{width:g,height:g,position:"relative",borderRadius:"50%",overflow:"hidden",border:`3px solid ${M}`,boxShadow:f==="scanning"?`0 0 30px ${M}`:"var(--security-shadow)",transition:"border-color 0.3s, box-shadow 0.3s"},children:[s.jsx("video",{ref:k,style:{width:"100%",height:"100%",objectFit:"cover"},playsInline:!0,muted:!0}),A&&s.jsx("canvas",{ref:u,width:g,height:g,style:{position:"absolute",inset:0,pointerEvents:"none"}}),p&&f==="idle"&&s.jsxs("svg",{viewBox:"0 0 100 100",style:{position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none",opacity:.4},children:[s.jsx("circle",{cx:"50",cy:"50",r:"35",fill:"none",stroke:"white",strokeWidth:"1",strokeDasharray:"5 3"}),s.jsx("circle",{cx:"50",cy:"50",r:"15",fill:"none",stroke:"white",strokeWidth:"0.5",strokeDasharray:"3 3"}),s.jsx("line",{x1:"50",y1:"10",x2:"50",y2:"25",stroke:"white",strokeWidth:"0.5",opacity:"0.5"}),s.jsx("line",{x1:"50",y1:"75",x2:"50",y2:"90",stroke:"white",strokeWidth:"0.5",opacity:"0.5"}),s.jsx("line",{x1:"10",y1:"50",x2:"25",y2:"50",stroke:"white",strokeWidth:"0.5",opacity:"0.5"}),s.jsx("line",{x1:"75",y1:"50",x2:"90",y2:"50",stroke:"white",strokeWidth:"0.5",opacity:"0.5"})]}),(f==="scanning"||f==="processing")&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-20, rgba(0, 0, 0, 0.2))"},children:s.jsx("div",{style:{width:g*.7,height:3,background:M,animation:"irisLineAnim 1.5s ease-in-out infinite",position:"absolute",opacity:.7}})})]}),s.jsx("div",{style:{fontSize:11,color:"var(--security-text-muted)",textTransform:"uppercase",letterSpacing:1},children:n==="both"?b("security.iris.bothEyes","Both eyes"):n==="left"?b("security.iris.leftEye","Left eye"):b("security.iris.rightEye","Right eye")}),v&&U>0&&s.jsx("div",{style:{width:g*.6,height:4,background:"var(--security-bg-panel)",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{width:`${Math.min(100,U*300)}%`,height:"100%",background:U>.3?"var(--security-success)":U>.1?"var(--security-warning)":"var(--security-error)",transition:"width 0.3s"}})}),s.jsx("div",{style:{fontSize:13,color:"var(--security-text-secondary)",textAlign:"center",minHeight:20},children:I??L}),f!=="success"&&f!=="failure"&&s.jsx("button",{onClick:Z,disabled:f==="scanning"||f==="processing",style:{padding:"10px 24px",fontSize:14,fontWeight:600,background:"var(--security-biometric)",color:"var(--nice-color-white, #fff)",border:"none",borderRadius:"var(--security-radius)",cursor:"pointer",opacity:f==="scanning"||f==="processing"?.6:1},children:t==="enroll"?b("security.iris.captureBtn","Capture Iris"):b("security.iris.verifyBtn","Verify Iris")}),(f==="failure"||f==="error")&&s.jsx("button",{onClick:()=>{B(0),E("idle"),$("")},style:{padding:"8px 20px",fontSize:13,background:"var(--security-bg-panel)",color:"var(--security-text)",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",cursor:"pointer"},children:b("security.common.retry","Try Again")}),s.jsx("style",{children:`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("react/jsx-runtime"),h=require("react"),qe=require("@nice2dev/ui-core"),de=require("@nice2dev/icons"),Ke={low:.7,medium:.8,high:.85,critical:.95},Ge={matchThreshold:.85,timeout:3e4,maxRetries:3,livenessDetection:!0,verifyEndpoint:"",authToken:"",showFeedback:!0,hapticFeedback:!0,locale:"en",securityLevel:"high",antiSpoofing:!0};function oe(e){const t={...Ge,...e};return e!=null&&e.matchThreshold||(t.matchThreshold=Ke[t.securityLevel]),t}async function ce(e){const t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(n=>n.toString(16).padStart(2,"0")).join("")}function he(e=8){const t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t).map(r=>r.toString(36).padStart(2,"0")).join("").slice(0,e)}function Ye(e){const t=new Uint32Array(1);return crypto.getRandomValues(t),t[0]%e}function Je(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}async function le(e="user"){return navigator.mediaDevices.getUserMedia({video:{facingMode:e,width:{ideal:1280},height:{ideal:720}},audio:!1})}function se(e,t,r){const n=t??e.videoWidth,o=r??e.videoHeight,a=document.createElement("canvas");a.width=n,a.height=o;const c=a.getContext("2d");c.drawImage(e,0,0,n,o);const i=c.getImageData(0,0,n,o);return{canvas:a,ctx:c,imageData:i}}function ne(e){const t=new Uint8Array(e.width*e.height),r=e.data;for(let n=0;n<t.length;n++){const o=n*4;t[n]=Math.round(.299*r[o]+.587*r[o+1]+.114*r[o+2])}return t}function je(e,t,r){const n=new Uint8Array(t*r),o=[1,2,1,2,4,2,1,2,1],a=16;for(let c=1;c<r-1;c++)for(let i=1;i<t-1;i++){let p=0,b=0;for(let y=-1;y<=1;y++)for(let w=-1;w<=1;w++)p+=e[(c+y)*t+(i+w)]*o[b++];n[c*t+i]=Math.round(p/a)}return n}function Ze(e,t,r){const n=new Uint8Array(t*r);for(let o=1;o<r-1;o++)for(let a=1;a<t-1;a++){const c=-e[(o-1)*t+(a-1)]+e[(o-1)*t+(a+1)]+-2*e[o*t+(a-1)]+2*e[o*t+(a+1)]+-e[(o+1)*t+(a-1)]+e[(o+1)*t+(a+1)],i=-e[(o-1)*t+(a-1)]-2*e[(o-1)*t+a]-e[(o-1)*t+(a+1)]+e[(o+1)*t+(a-1)]+2*e[(o+1)*t+a]+e[(o+1)*t+(a+1)];n[o*t+a]=Math.min(255,Math.round(Math.sqrt(c*c+i*i)))}return n}function Ve(e){const t=new Array(256).fill(0);for(const b of e)t[b]++;const r=e.length;let n=0;for(let b=0;b<256;b++)n+=b*t[b];let o=0,a=0,c=0,i=0;for(let b=0;b<256;b++){if(a+=t[b],a===0)continue;const y=r-a;if(y===0)break;o+=b*t[b];const w=o/a,j=(n-o)/y,m=a*y*(w-j)**2;m>c&&(c=m,i=b)}const p=new Uint8Array(e.length);for(let b=0;b<e.length;b++)p[b]=e[b]>i?255:0;return{threshold:i,binary:p}}function Te(e,t=.3){var k;const r=e.width,n=e.height,o=ne(e),a=je(o,r,n),c=Ze(a,r,n),{binary:i}=Ve(c),p=[],b=[],y=[];for(let x=2;x<n-2;x++)for(let l=2;l<r-2;l++){if(i[x*r+l]===0)continue;const S=[i[(x-1)*r+l],i[(x-1)*r+(l+1)],i[x*r+(l+1)],i[(x+1)*r+(l+1)],i[(x+1)*r+l],i[(x+1)*r+(l-1)],i[x*r+(l-1)],i[(x-1)*r+(l-1)]];let u=0;for(let B=0;B<8;B++){const H=S[B]>0?1:0,G=S[(B+1)%8]>0?1:0;u+=Math.abs(H-G)}u/=2;let f=0,D=0;for(let B=-2;B<=2;B++)for(let H=-2;H<=2;H++)f+=c[(x+B)*r+(l+H)],D++;const q=f/D/255;if(q<t)continue;const K=Math.atan2(o[(x+1)*r+l]-o[(x-1)*r+l],o[x*r+(l+1)]-o[x*r+(l-1)]);u===1?p.push({x:l/r,y:x/n,angle:K,type:"ending",quality:q}):u===3&&p.push({x:l/r,y:x/n,angle:K,type:"bifurcation",quality:q})}p.sort((x,l)=>l.quality-x.quality);const w=p.slice(0,120);if(w.length>5){const x=w.reduce((S,u)=>S+u.x,0)/w.length,l=w.reduce((S,u)=>S+u.y,0)/w.length;b.push({x,y:l})}const j=w.length,m=w.filter(x=>x.type==="ending").length,z=w.filter(x=>x.type==="bifurcation").length/(m+1);let g="loop-right";z>1.5?g="whorl":z<.5?g="arch":((k=b[0])==null?void 0:k.x)<.45&&(g="loop-left");const I=w.length>20?w.reduce((x,l)=>x+l.quality,0)/w.length:0;return{minutiae:w,corePoints:b,deltaPoints:y,ridgeCount:j,patternType:g,quality:I}}function Ce(e,t){if(e.minutiae.length<5||t.minutiae.length<5)return 0;let r=0;const n=.05,o=.5,a=new Set;for(const i of e.minutiae){let p=1/0,b=-1;for(let y=0;y<t.minutiae.length;y++){if(a.has(y))continue;const w=t.minutiae[y];if(i.type!==w.type)continue;const j=Je(i,w),m=Math.abs(i.angle-w.angle);j<n&&m<o&&j<p&&(p=j,b=y)}b>=0&&(r++,a.add(b))}const c=Math.min(e.minutiae.length,t.minutiae.length);return c>0?r/c:0}async function Ie(e,t){const r=JSON.stringify(e),n=await ce(r);return{id:`fp_${Date.now()}_${he()}`,method:"fingerprint",templateData:btoa(r),enrolled:Date.now(),label:t,hash:n}}function Re(e){return JSON.parse(atob(e.templateData))}function De(e,t="left"){const r=e.width,n=e.height,o=ne(e),a=je(o,r,n);let c={cx:r/2,cy:n/2,r:Math.min(r,n)*.08,score:1/0};for(let C=Math.round(n*.3);C<Math.round(n*.7);C+=2)for(let z=Math.round(r*.3);z<Math.round(r*.7);z+=2)for(let g=Math.round(Math.min(r,n)*.04);g<Math.round(Math.min(r,n)*.15);g+=2){let I=0,k=0;for(let u=0;u<Math.PI*2;u+=.3){const f=Math.round(z+g*Math.cos(u)),D=Math.round(C+g*Math.sin(u));f>=0&&f<r&&D>=0&&D<n&&(I+=a[D*r+f],k++)}const x=k>0?I/k:255,l=a[C*r+z],S=x*.5+l*.5;S<c.score&&(c={cx:z,cy:C,r:g,score:S})}const i=c.r*3,p={cx:c.cx,cy:c.cy,r:Math.min(i,Math.min(r,n)*.4)},b=256,y=[];for(let C=0;C<b;C++){const z=C/b*Math.PI*2,g=c.r+(p.r-c.r)*.5,I=Math.round(c.cx+g*Math.cos(z)),k=Math.round(c.cy+g*Math.sin(z));if(I>=0&&I<r&&k>=0&&k<n){const x=Math.round(c.cx+g*Math.cos(z+.1)),l=Math.round(c.cy+g*Math.sin(z+.1)),S=a[k*r+I],u=x>=0&&x<r&&l>=0&&l<n?a[l*r+x]:S;y.push(S>u?1:0)}else y.push(0)}const w=y.join(""),j=Math.PI*c.r**2,m=Math.min(1,Math.max(0,j/(r*n)*100));return{irisCode:w,pupil:c,iris:p,quality:m,eye:t}}function Pe(e,t){if(!e.irisCode||!t.irisCode)return 0;const r=Math.min(e.irisCode.length,t.irisCode.length);if(r===0)return 0;let n=0,o=r;for(let c=-8;c<=8;c++){let i=0;for(let p=0;p<r;p++){const b=(p+c+r)%r;e.irisCode[p]!==t.irisCode[b]&&i++}i<o&&(o=i)}n=o;const a=n/r;return Math.max(0,1-a*2.5)}async function Me(e,t){const r=JSON.stringify(e),n=await ce(r);return{id:`iris_${Date.now()}_${he()}`,method:"iris",templateData:btoa(r),enrolled:Date.now(),label:t,hash:n}}function Ee(e){return JSON.parse(atob(e.templateData))}function ae(e){const t=e.width,r=e.height,n=e.data,o=new Uint8Array(t*r);for(let l=0;l<t*r;l++){const S=l*4,u=n[S],f=n[S+1],D=n[S+2],q=.299*u+.587*f+.114*D,K=128-.169*u-.331*f+.5*D,B=128+.5*u-.419*f-.081*D;K>=77&&K<=127&&B>=133&&B<=173&&q>80&&(o[l]=1)}let a=t,c=r,i=0,p=0,b=0;for(let l=0;l<r;l++)for(let S=0;S<t;S++)o[l*t+S]&&(b++,S<a&&(a=S),S>i&&(i=S),l<c&&(c=l),l>p&&(p=l));const y=i-a,w=p-c;if(y<t*.1||w<r*.1)return null;const j={x:a,y:c,width:y,height:w},m=[],C=ne(e),z=Math.max(1,Math.floor(y/8)),g=Math.max(1,Math.floor(w/16));for(let l=0;l<16;l++)for(let S=0;S<8;S++){const u=a+S*z+Math.floor(z/2),f=c+l*g+Math.floor(g/2);u<t&&f<r?m.push(C[f*t+u]/255):m.push(0)}const I=[],k={x:a+y/2,y:c+w/2};for(let l=0;l<68;l++){const S=l/68*Math.PI*2,u=y*.4*Math.cos(S),f=w*.45*Math.sin(S);I.push({x:(k.x+u)/t,y:(k.y+f)/r})}const x=Math.min(1,b/(y*w)*2);return{embedding:m,boundingBox:j,landmarks:I,headPose:{yaw:0,pitch:0,roll:0},quality:x}}function fe(e,t){if(e.embedding.length!==t.embedding.length)return 0;let r=0,n=0,o=0;for(let c=0;c<e.embedding.length;c++)r+=e.embedding[c]*t.embedding[c],n+=e.embedding[c]**2,o+=t.embedding[c]**2;const a=Math.sqrt(n)*Math.sqrt(o);return a>0?(r/a+1)/2:0}function Fe(e,t){const r=ae(e),n=ae(t);return!r||!n?{similarity:0,cameraFeatures:r,refFeatures:n}:{similarity:fe(r,n),cameraFeatures:r,refFeatures:n}}async function Ne(e,t){const r=JSON.stringify(e),n=await ce(r);return{id:`face_${Date.now()}_${he()}`,method:"face",templateData:btoa(r),enrolled:Date.now(),label:t,hash:n}}function ze(e){return JSON.parse(atob(e.templateData))}function Xe(){const e=["blink","smile","turn-left","turn-right","nod","raise-eyebrows"],t=e[Ye(e.length)];return{type:t,instruction:{blink:"Please blink your eyes",smile:"Please smile","turn-left":"Please turn your head left","turn-right":"Please turn your head right",nod:"Please nod your head","raise-eyebrows":"Please raise your eyebrows"}[t],completed:!1,confidence:0}}function ye(e,t=.02){if(e.length<2)return{isLive:!1,confidence:0,motionScore:0};let r=0;for(let c=1;c<e.length;c++){const i=ne(e[c-1]),p=ne(e[c]);let b=0;for(let y=0;y<i.length;y++)b+=Math.abs(i[y]-p[y]);r+=b/(i.length*255)}const n=r/(e.length-1),o=n>t,a=Math.min(1,n/(t*3));return{isLive:o,confidence:a,motionScore:n}}function pe(){return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,screenResolution:[screen.width,screen.height],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,touchSupport:"ontouchstart"in window||navigator.maxTouchPoints>0,hardwareConcurrency:navigator.hardwareConcurrency??0}}async function ie(){const e=pe(),t=JSON.stringify(e);return ce(t)}function ge(){return typeof window<"u"&&!!window.PublicKeyCredential}async function Le(){if(!ge())return!1;try{return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}async function $e(e){const t={rp:{name:e.rpName,id:e.rpId},user:{id:new TextEncoder().encode(e.userId),name:e.userName,displayName:e.userDisplayName},challenge:e.challenge,pubKeyCredParams:[{alg:-7,type:"public-key"},{alg:-257,type:"public-key"}],authenticatorSelection:{authenticatorAttachment:e.authenticatorAttachment??"platform",userVerification:e.userVerification??"required",residentKey:e.residentKey??"preferred"},timeout:e.timeout??6e4,attestation:e.attestation??"none"};return await navigator.credentials.create({publicKey:t})}async function _e(e){const t={rpId:e.rpId,challenge:e.challenge,allowCredentials:e.allowCredentials,userVerification:e.userVerification??"required",timeout:e.timeout??6e4};return await navigator.credentials.get({publicKey:t})}async function ue(e,t,r){const n={"Content-Type":"application/json"};r&&(n.Authorization=`Bearer ${r}`);const o=await fetch(e,{method:"POST",headers:n,body:JSON.stringify(t)});return o.ok?o.json():{verified:!1,message:`Server error: ${o.status}`}}function Q(e,t){var c;const r=e.trim().match(/^var\(\s*([^,\s)]+)\s*(?:,\s*(.+))?\)$/);if(!r)return e;const n=(c=r[2])==null?void 0:c.trim();if(typeof document>"u"||typeof getComputedStyle>"u")return n?Q(n):e;const o=typeof Element<"u"&&t instanceof Element&&t.isConnected?t:document.documentElement,a=getComputedStyle(o).getPropertyValue(r[1]).trim();return a||(n?Q(n,t):e)}const Be=h.createContext(null),Qe=({t:e,children:t})=>s.jsx(Be.Provider,{value:e,children:t});function X(){const e=h.useContext(Be),{t}=qe.useNiceTranslation();return{t:e??t}}const et={sm:200,md:280,lg:380},tt=e=>{const{mode:t,enrolledTemplates:r=[],fingerPosition:n="right-index",onEnroll:o,onVerify:a,onStatusChange:c,onError:i,className:p,size:b="md",label:y,showQuality:w=!0,showMinutiae:j=!1,instructionText:m,cameraFacing:C="environment",...z}=e,{t:g}=X(),I=oe(z),k=et[b],x=h.useRef(null),l=h.useRef(null),S=h.useRef(null),[u,f]=h.useState("idle"),[D,q]=h.useState(0),[K,B]=h.useState(null),[H,G]=h.useState(0),[$,L]=h.useState(""),_=h.useCallback(M=>{f(M),c==null||c(M)},[c]),E=h.useCallback(async()=>{try{const M=await le(C);S.current=M,x.current&&(x.current.srcObject=M,await x.current.play()),_("idle"),L(g("security.fingerprint.placeFingerPrompt","Place your finger on the scanner"))}catch(M){i==null||i(M instanceof Error?M:new Error(String(M))),L(g("security.fingerprint.cameraError","Camera access denied")),_("error")}},[C,g,_,i]),U=h.useCallback(()=>{var M;(M=S.current)==null||M.getTracks().forEach(F=>F.stop()),S.current=null},[]);h.useEffect(()=>(E(),U),[E,U]);const W=h.useCallback(async()=>{if(!(!x.current||u==="processing"||u==="success")){_("scanning"),L(g("security.fingerprint.scanning","Scanning…"));try{const{imageData:M}=se(x.current);_("processing"),L(g("security.fingerprint.processing","Processing fingerprint…"));const F=Te(M);if(B(F),q(F.quality),F.quality<.2){L(g("security.fingerprint.lowQuality","Low quality — try again")),_("idle");return}if(t==="enroll"){const R=await Ie(F,y??n);o==null||o(R,F),L(g("security.fingerprint.enrolled","Fingerprint enrolled successfully")),_("success")}else{let R=0;for(const d of r){const A=Re(d),N=Ce(F,A);N>R&&(R=N)}const T=R>=I.matchThreshold,v={success:T,confidence:R,method:"fingerprint",timestamp:Date.now(),duration:0,payload:btoa(JSON.stringify(F))};if(T&&I.verifyEndpoint){const d=await ie(),A=await ue(I.verifyEndpoint,{method:"fingerprint",templateData:v.payload,matchScore:R,deviceFingerprint:d},I.authToken);v.success=A.verified}v.success?(L(g("security.fingerprint.verified","Fingerprint verified")),_("success")):(G(d=>d+1),H+1>=I.maxRetries?(L(g("security.fingerprint.maxAttempts","Maximum attempts reached")),_("failure")):(L(g("security.fingerprint.noMatch","No match — try again")),_("idle"))),a==null||a(v)}}catch(M){i==null||i(M instanceof Error?M:new Error(String(M))),L(g("security.fingerprint.error","Scan error — try again")),_("error")}}},[u,t,r,I,g,_,o,a,i,y,n,H]);h.useEffect(()=>{if(!j||!K||!l.current)return;const M=l.current.getContext("2d");if(!M)return;M.clearRect(0,0,k,k);const F=Q("var(--nice-success, #10b981)",M.canvas),R=Q("var(--nice-warning, #f59e0b)",M.canvas);K.minutiae.forEach(T=>{M.beginPath(),M.arc(T.x*k,T.y*k,2,0,Math.PI*2),M.fillStyle=T.type==="ending"?F:R,M.fill(),M.beginPath(),M.moveTo(T.x*k,T.y*k),M.lineTo(T.x*k+Math.cos(T.angle)*8,T.y*k+Math.sin(T.angle)*8),M.strokeStyle=M.fillStyle,M.lineWidth=1,M.stroke()})},[K,j,k]);const Z=u==="success"?"var(--security-success)":u==="failure"||u==="error"?"var(--security-error)":u==="scanning"||u==="processing"?"var(--security-biometric)":"var(--security-border)";return s.jsxs("div",{className:p,style:{display:"inline-flex",flexDirection:"column",alignItems:"center",gap:12},children:[y&&s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"var(--security-text)"},children:y}),s.jsxs("div",{style:{width:k,height:k,position:"relative",borderRadius:"var(--security-radius-lg)",overflow:"hidden",border:`3px solid ${Z}`,boxShadow:u==="scanning"?`0 0 20px ${Z}`:"var(--security-shadow)",transition:"border-color 0.3s, box-shadow 0.3s"},children:[s.jsx("video",{ref:x,style:{width:"100%",height:"100%",objectFit:"cover"},playsInline:!0,muted:!0}),j&&s.jsx("canvas",{ref:l,width:k,height:k,style:{position:"absolute",inset:0,pointerEvents:"none"}}),s.jsxs("svg",{viewBox:"0 0 100 100",style:{position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none",opacity:.3},children:[s.jsx("ellipse",{cx:"50",cy:"50",rx:"28",ry:"38",fill:"none",stroke:"white",strokeWidth:"1",strokeDasharray:"4 3"}),s.jsx("ellipse",{cx:"50",cy:"50",rx:"20",ry:"28",fill:"none",stroke:"white",strokeWidth:"0.5",strokeDasharray:"2 3"})]}),(u==="scanning"||u==="processing")&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-30, rgba(0, 0, 0, 0.3))"},children:s.jsx("div",{style:{width:60,height:60,borderRadius:"50%",border:"3px solid transparent",borderTopColor:Z,animation:"spin 0.8s linear infinite"}})})]}),w&&D>0&&s.jsx("div",{style:{width:k,height:4,background:"var(--security-bg-panel)",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{width:`${D*100}%`,height:"100%",background:D>.6?"var(--security-success)":D>.3?"var(--security-warning)":"var(--security-error)",transition:"width 0.3s"}})}),s.jsx("div",{style:{fontSize:13,color:"var(--security-text-secondary)",textAlign:"center",minHeight:20},children:m??$}),u!=="success"&&u!=="failure"&&s.jsx("button",{onClick:W,disabled:u==="scanning"||u==="processing",style:{padding:"10px 24px",fontSize:14,fontWeight:600,background:"var(--security-biometric)",color:"var(--nice-color-white, #fff)",border:"none",borderRadius:"var(--security-radius)",cursor:"pointer",opacity:u==="scanning"||u==="processing"?.6:1},children:t==="enroll"?g("security.fingerprint.captureBtn","Capture Fingerprint"):g("security.fingerprint.verifyBtn","Verify Fingerprint")}),(u==="failure"||u==="error")&&s.jsx("button",{onClick:()=>{G(0),_("idle"),L("")},style:{padding:"8px 20px",fontSize:13,background:"var(--security-bg-panel)",color:"var(--security-text)",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",cursor:"pointer"},children:g("security.common.retry","Try Again")}),s.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]})},rt={sm:220,md:300,lg:400},st=e=>{const{mode:t,enrolledTemplates:r=[],eye:n="right",onEnroll:o,onVerify:a,onStatusChange:c,onError:i,className:p,size:b="md",label:y,showQuality:w=!0,showSegmentation:j=!0,showGuide:m=!0,instructionText:C,...z}=e,{t:g}=X(),I=oe(z),k=rt[b],x=h.useRef(null),l=h.useRef(null),S=h.useRef(null),u=h.useRef([]),[f,D]=h.useState("idle"),[q,K]=h.useState(0),[B,H]=h.useState(null),[G,$]=h.useState(0),[L,_]=h.useState(""),E=h.useCallback(F=>{D(F),c==null||c(F)},[c]),U=h.useCallback(async()=>{try{const F=await le("user");S.current=F,x.current&&(x.current.srcObject=F,await x.current.play()),E("idle"),_(g("security.iris.alignEyePrompt","Align your eye with the circle"))}catch(F){i==null||i(F instanceof Error?F:new Error(String(F))),_(g("security.iris.cameraError","Camera access denied")),E("error")}},[g,E,i]),W=h.useCallback(()=>{var F;(F=S.current)==null||F.getTracks().forEach(R=>R.stop()),S.current=null},[]);h.useEffect(()=>(U(),W),[U,W]);const Z=h.useCallback(async()=>{if(!(!x.current||f==="processing"||f==="success")){E("scanning"),_(g("security.iris.scanning","Scanning iris…"));try{const F=[];for(let v=0;v<5;v++){const{imageData:d}=se(x.current);F.push(d),await new Promise(A=>setTimeout(A,200))}if(u.current=F,I.livenessDetection&&!ye(F).isLive){_(g("security.iris.notLive","Liveness check failed — please blink or move slightly")),E("idle");return}E("processing"),_(g("security.iris.processing","Processing iris pattern…"));const R=F[F.length-1],T=De(R,n==="both"?"left":n);if(!T){_(g("security.iris.noIrisDetected","No iris detected — adjust position")),E("idle");return}if(H(T),K(T.quality),T.quality<.1){_(g("security.iris.lowQuality","Low quality — move closer")),E("idle");return}if(j&&l.current){const v=l.current.getContext("2d");if(v){v.clearRect(0,0,k,k);const d=k/R.width,A=k/R.height;v.beginPath(),v.arc(T.pupil.cx*d,T.pupil.cy*A,T.pupil.r*d,0,Math.PI*2),v.strokeStyle=Q("var(--nice-danger, #ef4444)",v.canvas),v.lineWidth=2,v.stroke(),v.beginPath(),v.arc(T.iris.cx*d,T.iris.cy*A,T.iris.r*d,0,Math.PI*2),v.strokeStyle=Q("var(--nice-primary, #3b82f6)",v.canvas),v.lineWidth=2,v.stroke()}}if(t==="enroll"){const v=await Me(T,y??`${n} eye`);o==null||o(v,T),_(g("security.iris.enrolled","Iris enrolled successfully")),E("success")}else{let v=0;for(const N of r){const P=Ee(N),O=Pe(T,P);O>v&&(v=O)}const d=v>=I.matchThreshold,A={success:d,confidence:v,method:"iris",timestamp:Date.now(),duration:0,livenessPassed:I.livenessDetection?!0:void 0,payload:btoa(JSON.stringify(T))};if(d&&I.verifyEndpoint){const N=await ie(),P=await ue(I.verifyEndpoint,{method:"iris",templateData:A.payload,matchScore:v,deviceFingerprint:N},I.authToken);A.success=P.verified}A.success?(_(g("security.iris.verified","Iris verified")),E("success")):($(N=>N+1),G+1>=I.maxRetries?(_(g("security.iris.maxAttempts","Maximum attempts reached")),E("failure")):(_(g("security.iris.noMatch","No match — try again")),E("idle"))),a==null||a(A)}}catch(F){i==null||i(F instanceof Error?F:new Error(String(F))),_(g("security.iris.error","Scan error")),E("error")}}},[f,t,r,I,g,E,o,a,i,y,n,G,j,k]),M=f==="success"?"var(--security-success)":f==="failure"||f==="error"?"var(--security-error)":f==="scanning"||f==="processing"?"var(--security-biometric)":"var(--security-border)";return s.jsxs("div",{className:p,style:{display:"inline-flex",flexDirection:"column",alignItems:"center",gap:12},children:[y&&s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"var(--security-text)"},children:y}),s.jsxs("div",{style:{width:k,height:k,position:"relative",borderRadius:"50%",overflow:"hidden",border:`3px solid ${M}`,boxShadow:f==="scanning"?`0 0 30px ${M}`:"var(--security-shadow)",transition:"border-color 0.3s, box-shadow 0.3s"},children:[s.jsx("video",{ref:x,style:{width:"100%",height:"100%",objectFit:"cover"},playsInline:!0,muted:!0}),j&&s.jsx("canvas",{ref:l,width:k,height:k,style:{position:"absolute",inset:0,pointerEvents:"none"}}),m&&f==="idle"&&s.jsxs("svg",{viewBox:"0 0 100 100",style:{position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none",opacity:.4},children:[s.jsx("circle",{cx:"50",cy:"50",r:"35",fill:"none",stroke:"white",strokeWidth:"1",strokeDasharray:"5 3"}),s.jsx("circle",{cx:"50",cy:"50",r:"15",fill:"none",stroke:"white",strokeWidth:"0.5",strokeDasharray:"3 3"}),s.jsx("line",{x1:"50",y1:"10",x2:"50",y2:"25",stroke:"white",strokeWidth:"0.5",opacity:"0.5"}),s.jsx("line",{x1:"50",y1:"75",x2:"50",y2:"90",stroke:"white",strokeWidth:"0.5",opacity:"0.5"}),s.jsx("line",{x1:"10",y1:"50",x2:"25",y2:"50",stroke:"white",strokeWidth:"0.5",opacity:"0.5"}),s.jsx("line",{x1:"75",y1:"50",x2:"90",y2:"50",stroke:"white",strokeWidth:"0.5",opacity:"0.5"})]}),(f==="scanning"||f==="processing")&&s.jsx("div",{style:{position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--nice-overlay-20, rgba(0, 0, 0, 0.2))"},children:s.jsx("div",{style:{width:k*.7,height:3,background:M,animation:"irisLineAnim 1.5s ease-in-out infinite",position:"absolute",opacity:.7}})})]}),s.jsx("div",{style:{fontSize:11,color:"var(--security-text-muted)",textTransform:"uppercase",letterSpacing:1},children:n==="both"?g("security.iris.bothEyes","Both eyes"):n==="left"?g("security.iris.leftEye","Left eye"):g("security.iris.rightEye","Right eye")}),w&&q>0&&s.jsx("div",{style:{width:k*.6,height:4,background:"var(--security-bg-panel)",borderRadius:2,overflow:"hidden"},children:s.jsx("div",{style:{width:`${Math.min(100,q*300)}%`,height:"100%",background:q>.3?"var(--security-success)":q>.1?"var(--security-warning)":"var(--security-error)",transition:"width 0.3s"}})}),s.jsx("div",{style:{fontSize:13,color:"var(--security-text-secondary)",textAlign:"center",minHeight:20},children:C??L}),f!=="success"&&f!=="failure"&&s.jsx("button",{onClick:Z,disabled:f==="scanning"||f==="processing",style:{padding:"10px 24px",fontSize:14,fontWeight:600,background:"var(--security-biometric)",color:"var(--nice-color-white, #fff)",border:"none",borderRadius:"var(--security-radius)",cursor:"pointer",opacity:f==="scanning"||f==="processing"?.6:1},children:t==="enroll"?g("security.iris.captureBtn","Capture Iris"):g("security.iris.verifyBtn","Verify Iris")}),(f==="failure"||f==="error")&&s.jsx("button",{onClick:()=>{$(0),E("idle"),_("")},style:{padding:"8px 20px",fontSize:13,background:"var(--security-bg-panel)",color:"var(--security-text)",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",cursor:"pointer"},children:g("security.common.retry","Try Again")}),s.jsx("style",{children:`
2
2
  @keyframes irisLineAnim {
3
- 0%, 100% { transform: translateY(-${g*.3}px); opacity: 0.3; }
4
- 50% { transform: translateY(${g*.3}px); opacity: 0.8; }
3
+ 0%, 100% { transform: translateY(-${k*.3}px); opacity: 0.3; }
4
+ 50% { transform: translateY(${k*.3}px); opacity: 0.8; }
5
5
  }
6
- `})]})},nt={sm:240,md:320,lg:440},it=e=>{const{mode:t,enrolledTemplates:r=[],referencePhoto:n,onEnroll:a,onVerify:i,onStatusChange:o,onError:c,className:m,size:x="md",label:y,showQuality:v=!0,showBoundingBox:A=!0,livenessSteps:p=1,showReference:I=!0,instructionText:D,...b}=e,{t:T}=Q(),g=oe(b),k=nt[x],u=h.useRef(null),S=h.useRef(null),l=h.useRef(null),[f,z]=h.useState("idle"),[U,G]=h.useState(0),[_,H]=h.useState(0),[K,B]=h.useState(""),[L,$]=h.useState(null),[E,q]=h.useState(0),W=h.useCallback(w=>{z(w),o==null||o(w)},[o]),Z=h.useCallback(async()=>{try{const w=await le("user");l.current=w,u.current&&(u.current.srcObject=w,await u.current.play()),W("idle"),B(T("security.face.lookAtCamera","Look at the camera"))}catch(w){c==null||c(w instanceof Error?w:new Error(String(w))),B(T("security.face.cameraError","Camera access denied")),W("error")}},[T,W,c]),M=h.useCallback(()=>{var w;(w=l.current)==null||w.getTracks().forEach(d=>d.stop()),l.current=null},[]);h.useEffect(()=>(Z(),M),[Z,M]);const R=h.useCallback(w=>{var ee,xe,be;const d=(ee=S.current)==null?void 0:ee.getContext("2d");if(!d)return;const j=S.current.width,N=S.current.height;if(d.clearRect(0,0,j,N),!w||!A)return;const P=w.boundingBox,O=j/(((xe=u.current)==null?void 0:xe.videoWidth)??j),Y=N/(((be=u.current)==null?void 0:be.videoHeight)??N);d.strokeStyle=V(f==="success"?"var(--nice-success, #10b981)":"var(--nice-primary, #3b82f6)",d.canvas),d.lineWidth=2,d.setLineDash([6,4]),d.strokeRect(P.x*O,P.y*Y,P.width*O,P.height*Y),d.setLineDash([]);const X=[[P.x*O,P.y*Y],[(P.x+P.width)*O,P.y*Y],[P.x*O,(P.y+P.height)*Y],[(P.x+P.width)*O,(P.y+P.height)*Y]],J=12;d.lineWidth=3;for(const[te,re]of X)d.beginPath(),d.moveTo(te===P.x*O?te:te-J,re),d.lineTo(te,re),d.lineTo(te,re===P.y*Y?re+J:re-J),d.stroke()},[A,f]),F=h.useCallback(async()=>{if(!(!u.current||f==="processing"||f==="success")){W("scanning"),B(T("security.face.scanning","Scanning face…"));try{if(g.livenessDetection){const j=[];for(let P=0;P<8;P++)j.push(se(u.current).imageData),await new Promise(O=>setTimeout(O,200));if(!ye(j).isLive){B(T("security.face.notLive","Liveness check failed — move naturally")),W("idle");return}}W("processing"),B(T("security.face.processing","Analysing face…"));const{imageData:w}=se(u.current);if(t==="compare"&&n){const j=typeof n=="string"?await at(n):ot(n),{similarity:N,cameraFeatures:P,refFeatures:O}=Fe(w,j);q(N),G((P==null?void 0:P.quality)??0),R(P);const X={success:N>=g.matchThreshold,confidence:N,method:"face",timestamp:Date.now(),duration:0,livenessPassed:g.livenessDetection};X.success?(B(T("security.face.matchFound",`Match: ${(N*100).toFixed(0)}%`)),W("success")):(H(J=>J+1),_+1>=g.maxRetries?(B(T("security.face.maxAttempts","Maximum attempts reached")),W("failure")):(B(T("security.face.noMatch","No match — try again")),W("idle"))),i==null||i(X);return}const d=ae(w);if(!d){B(T("security.face.noFaceDetected","No face detected")),W("idle");return}if(G(d.quality),R(d),t==="enroll"){const j=await Ne(d,y??"face");a==null||a(j,d),B(T("security.face.enrolled","Face enrolled successfully")),W("success")}else{let j=0;for(const O of r){const Y=ze(O),X=fe(d,Y);X>j&&(j=X)}q(j);const N=j>=g.matchThreshold,P={success:N,confidence:j,method:"face",timestamp:Date.now(),duration:0,livenessPassed:g.livenessDetection};if(N&&g.verifyEndpoint){const O=await ie(),Y=await ue(g.verifyEndpoint,{method:"face",templateData:btoa(JSON.stringify(d)),matchScore:j,deviceFingerprint:O},g.authToken);P.success=Y.verified}P.success?(B(T("security.face.verified","Face verified")),W("success")):(H(O=>O+1),_+1>=g.maxRetries?(B(T("security.face.maxAttempts","Maximum attempts reached")),W("failure")):(B(T("security.face.noMatch","No match — try again")),W("idle"))),i==null||i(P)}}catch(w){c==null||c(w instanceof Error?w:new Error(String(w))),B(T("security.face.error","Error — try again")),W("error")}}},[f,t,r,n,g,T,W,a,i,c,y,_,R]),C=f==="success"?"var(--security-success)":f==="failure"||f==="error"?"var(--security-error)":f==="scanning"||f==="processing"?"var(--security-biometric)":"var(--security-border)";return s.jsxs("div",{className:m,style:{display:"inline-flex",flexDirection:"column",alignItems:"center",gap:12},children:[y&&s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"var(--security-text)"},children:y}),s.jsxs("div",{style:{display:"flex",gap:16,alignItems:"center"},children:[s.jsxs("div",{style:{width:k,height:k*.75,position:"relative",borderRadius:"var(--security-radius-lg)",overflow:"hidden",border:`3px solid ${C}`,boxShadow:f==="scanning"?`0 0 20px ${C}`:"var(--security-shadow)",transition:"border-color 0.3s, box-shadow 0.3s"},children:[s.jsx("video",{ref:u,style:{width:"100%",height:"100%",objectFit:"cover",transform:"scaleX(-1)"},playsInline:!0,muted:!0}),s.jsx("canvas",{ref:S,width:k,height:k*.75,style:{position:"absolute",inset:0,pointerEvents:"none",transform:"scaleX(-1)"}}),s.jsx("svg",{viewBox:"0 0 100 75",style:{position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none",opacity:.3},children:s.jsx("ellipse",{cx:"50",cy:"37",rx:"22",ry:"30",fill:"none",stroke:"white",strokeWidth:"0.8",strokeDasharray:"4 3"})}),(f==="scanning"||f==="processing")&&s.jsx("div",{style:{position:"absolute",inset:0,background:"var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",display:"flex",alignItems:"center",justifyContent:"center"},children:s.jsx("div",{style:{width:50,height:50,borderRadius:"50%",border:"3px solid transparent",borderTopColor:C,animation:"spin 0.8s linear infinite"}})})]}),t==="compare"&&I&&n&&s.jsxs("div",{style:{width:k*.4,height:k*.5,borderRadius:"var(--security-radius)",overflow:"hidden",border:"2px solid var(--security-border)"},children:[s.jsx("img",{src:typeof n=="string"?n:void 0,alt:T("security.face.referenceAlt","Reference"),style:{width:"100%",height:"100%",objectFit:"cover"}}),s.jsx("div",{style:{textAlign:"center",fontSize:10,padding:4,color:"var(--security-text-muted)",background:"var(--security-bg-panel)"},children:T("security.face.reference","Reference")})]})]}),E>0&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[s.jsxs("span",{style:{color:"var(--security-text-secondary)"},children:[T("security.face.confidence","Confidence"),":"]}),s.jsx("div",{style:{width:100,height:6,background:"var(--security-bg-panel)",borderRadius:3,overflow:"hidden"},children:s.jsx("div",{style:{width:`${E*100}%`,height:"100%",background:E>=g.matchThreshold?"var(--security-success)":"var(--security-warning)"}})}),s.jsxs("span",{style:{fontWeight:600,color:E>=g.matchThreshold?"var(--security-success)":"var(--security-warning)"},children:[(E*100).toFixed(0),"%"]})]}),s.jsx("div",{style:{fontSize:13,color:"var(--security-text-secondary)",textAlign:"center",minHeight:20},children:D??K}),f!=="success"&&f!=="failure"&&s.jsx("button",{onClick:F,disabled:f==="scanning"||f==="processing",style:{padding:"10px 24px",fontSize:14,fontWeight:600,background:"var(--security-biometric)",color:"var(--nice-color-white, #fff)",border:"none",borderRadius:"var(--security-radius)",cursor:"pointer",opacity:f==="scanning"||f==="processing"?.6:1},children:t==="enroll"?T("security.face.captureBtn","Capture Face"):t==="compare"?T("security.face.compareBtn","Compare"):T("security.face.verifyBtn","Verify Face")}),(f==="failure"||f==="error")&&s.jsx("button",{onClick:()=>{H(0),q(0),W("idle"),B("")},style:{padding:"8px 20px",fontSize:13,background:"var(--security-bg-panel)",color:"var(--security-text)",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",cursor:"pointer"},children:T("security.common.retry","Try Again")}),s.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]})};async function at(e){return new Promise((t,r)=>{const n=new Image;n.crossOrigin="anonymous",n.onload=()=>{const a=document.createElement("canvas");a.width=n.naturalWidth,a.height=n.naturalHeight;const i=a.getContext("2d");i.drawImage(n,0,0),t(i.getImageData(0,0,a.width,a.height))},n.onerror=()=>r(new Error("Failed to load reference image")),n.src=e})}function ot(e){const t=document.createElement("canvas");t.width=e.naturalWidth||e.width,t.height=e.naturalHeight||e.height;const r=t.getContext("2d");return r.drawImage(e,0,0),r.getImageData(0,0,t.width,t.height)}const ct=4,lt=5,ut=3e4,dt=e=>{const{length:t=ct,scramble:r=!1,showDigits:n=!1,maxAttempts:a=lt,lockoutDuration:i=ut,keySize:o=64,haptic:c=!0,keyLabels:m,expectedHash:x,expectedPin:y,mode:v="verify",onComplete:A,onVerify:p,onStatusChange:I,onError:D,showBiometricFallback:b=!1,onBiometricFallback:T,label:g,className:k}=e,{t:u}=Q(),[S,l]=h.useState([]),[f,z]=h.useState("idle"),[U,G]=h.useState(0),[_,H]=h.useState(0),[K,B]=h.useState(null),L=h.useRef(void 0),$=h.useMemo(()=>{const F=["1","2","3","4","5","6","7","8","9","","0","back"];if(!r)return F;const C=["0","1","2","3","4","5","6","7","8","9"];for(let w=C.length-1;w>0;w--){const d=new Uint32Array(1);crypto.getRandomValues(d);const j=d[0]%(w+1);[C[w],C[j]]=[C[j],C[w]]}return[C[0],C[1],C[2],C[3],C[4],C[5],C[6],C[7],C[8],"",C[9],"back"]},[r,f]),E=h.useCallback(F=>{z(F),I==null||I(F)},[I]);h.useEffect(()=>{if(!(_<=Date.now()))return L.current=setInterval(()=>{Date.now()>=_&&(clearInterval(L.current),E("idle"),G(0),l([]))},500),()=>clearInterval(L.current)},[_,E]);const q=_>Date.now(),W=h.useCallback(()=>{c&&navigator.vibrate&&navigator.vibrate(20)},[c]),Z=h.useCallback(async F=>{if(q||f==="success")return;if(W(),F==="back"){l(j=>j.slice(0,-1));return}if(F==="")return;const C=[...S,F];if(l(C),C.length<t)return;const w=C.join("");if(E("processing"),v==="set"){if(K===null){B(w),l([]),E("idle");return}if(K!==w){B(null),l([]),E("failure"),setTimeout(()=>E("idle"),1200);return}A==null||A(w),E("success");return}let d=!1;if(x){const j=new TextEncoder,N=await crypto.subtle.digest("SHA-256",j.encode(w));d=Array.from(new Uint8Array(N)).map(O=>O.toString(16).padStart(2,"0")).join("")===x}else if(y)d=w===y;else{A==null||A(w),E("success");return}if(d)E("success"),p==null||p({success:!0,confidence:1,method:"pin",timestamp:Date.now(),duration:0}),A==null||A(w);else{const j=U+1;if(G(j),j>=a){const N=Date.now()+i;H(N),E("failure"),D==null||D(new Error("Too many failed PIN attempts"))}else E("failure"),setTimeout(()=>{E("idle"),l([])},800);p==null||p({success:!1,confidence:0,method:"pin",timestamp:Date.now(),duration:0})}},[S,t,q,f,v,K,x,y,U,a,i,W,E,A,p,D]),M=Math.max(0,Math.ceil((_-Date.now())/1e3)),R=f==="success"?"var(--security-success)":f==="failure"?"var(--security-error)":"var(--security-border)";return s.jsxs("div",{className:k,style:{display:"inline-flex",flexDirection:"column",alignItems:"center",gap:16,fontFamily:"var(--security-font)",color:"var(--security-text)"},children:[g&&s.jsx("div",{style:{fontSize:14,fontWeight:600},children:g}),s.jsx("div",{style:{fontSize:13,color:"var(--security-text-secondary)",minHeight:18,textAlign:"center"},children:q?u("security.pin.locked",`Locked — try again in ${M}s`):v==="set"&&K!==null?u("security.pin.confirm","Confirm your PIN"):v==="set"?u("security.pin.setNew","Enter a new PIN"):u("security.pin.enter","Enter your PIN")}),s.jsx("div",{style:{display:"flex",gap:12},children:Array.from({length:t},(F,C)=>s.jsx("div",{style:{width:16,height:16,borderRadius:"50%",border:`2px solid ${R}`,background:C<S.length?R:"transparent",transition:"background 0.15s, border-color 0.15s"}},C))}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(3, ${o}px)`,gap:10,opacity:q?.4:1,pointerEvents:q?"none":"auto"},children:$.map((F,C)=>{if(F==="")return s.jsx("div",{},C);const w=F==="back";return s.jsx("button",{onClick:()=>Z(F),disabled:q||f==="success","aria-label":w?"Backspace":F,style:{width:o,height:o,borderRadius:"var(--security-key-border-radius, 50%)",border:"1px solid var(--security-key-border, var(--security-border))",background:"var(--security-key-bg, var(--security-bg-panel))",color:"var(--security-key-text, var(--security-text))",fontSize:w?20:22,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.1s, transform 0.1s",userSelect:"none"},onMouseDown:d=>{d.currentTarget.style.transform="scale(0.92)"},onMouseUp:d=>{d.currentTarget.style.transform=""},onMouseLeave:d=>{d.currentTarget.style.transform=""},children:w?s.jsx(de.NtdBackspace,{size:22}):(m==null?void 0:m[F])??F},C)})}),S.length>0&&f!=="success"&&s.jsx("button",{onClick:()=>l([]),style:{fontSize:12,background:"none",border:"none",color:"var(--security-text-secondary)",cursor:"pointer",textDecoration:"underline"},children:u("security.pin.clear","Clear")}),b&&s.jsx("button",{onClick:T,style:{fontSize:13,padding:"8px 16px",background:"none",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",color:"var(--security-biometric)",cursor:"pointer"},children:u("security.pin.biometricFallback","Use biometrics instead")}),U>0&&f!=="success"&&!q&&s.jsx("div",{style:{fontSize:11,color:"var(--security-warning)"},children:u("security.pin.attempts",`${U}/${a} attempts`)})]})},ht=3,ft=4,yt=5,pt=14,gt=e=>{const{gridSize:t=ht,minLength:r=ft,showTrail:n=!0,showError:a=!0,maxAttempts:i=yt,dotSize:o=pt,trailColor:c,mode:m="verify",expectedHash:x,expectedPattern:y,onComplete:v,onVerify:A,onStatusChange:p,onError:I,label:D,className:b,canvasSize:T}=e,{t:g}=Q(),k=h.useRef(null),[u,S]=h.useState([]),[l,f]=h.useState(!1),[z,U]=h.useState("idle"),[G,_]=h.useState(0),[H,K]=h.useState(null),[B,L]=h.useState(null),$=T??t*80,E=$/t,q=h.useCallback(d=>{U(d),p==null||p(d)},[p]),W=h.useCallback(()=>{const d=[];for(let j=0;j<t;j++)for(let N=0;N<t;N++)d.push({x:N*E+E/2,y:j*E+E/2});return d},[t,E]),Z=h.useCallback(d=>{const j=k.current.getBoundingClientRect(),N="touches"in d?d.touches[0].clientX:d.clientX,P="touches"in d?d.touches[0].clientY:d.clientY;return{x:N-j.left,y:P-j.top}},[]),M=h.useCallback((d,j)=>{const N=W(),P=E*.38;for(let O=0;O<N.length;O++){const Y=N[O].x-d,X=N[O].y-j;if(Y*Y+X*X<P*P)return O}return-1},[W,E]),R=h.useCallback(()=>{var X;const d=(X=k.current)==null?void 0:X.getContext("2d");if(!d)return;d.clearRect(0,0,$,$);const j=W(),N=z==="failure",P=d.canvas,O=V(N&&a?"var(--security-error)":c??"var(--security-biometric)",P),Y=V("var(--security-border)",P);for(let J=0;J<j.length;J++){const ee=u.includes(J);d.beginPath(),d.arc(j[J].x,j[J].y,ee?o*.75:o*.5,0,Math.PI*2),d.fillStyle=ee?O:Y,d.fill(),ee&&(d.beginPath(),d.arc(j[J].x,j[J].y,o*1.2,0,Math.PI*2),d.strokeStyle=O,d.lineWidth=1.5,d.globalAlpha=.3,d.stroke(),d.globalAlpha=1)}if(n&&u.length>1){d.beginPath(),d.moveTo(j[u[0]].x,j[u[0]].y);for(let J=1;J<u.length;J++)d.lineTo(j[u[J]].x,j[u[J]].y);l&&B&&d.lineTo(B.x,B.y),d.strokeStyle=O,d.lineWidth=3,d.lineCap="round",d.lineJoin="round",d.globalAlpha=.5,d.stroke(),d.globalAlpha=1}else n&&u.length===1&&l&&B&&(d.beginPath(),d.moveTo(j[u[0]].x,j[u[0]].y),d.lineTo(B.x,B.y),d.strokeStyle=V(c??"var(--security-biometric)",P),d.lineWidth=3,d.globalAlpha=.4,d.stroke(),d.globalAlpha=1)},[$,W,o,u,l,B,z,n,a,c]);h.useEffect(()=>{R()},[R]);const F=h.useCallback(d=>{if(z==="success"||z==="failure")return;d.preventDefault();const{x:j,y:N}=Z(d),P=M(j,N);P>=0&&(f(!0),S([P]),L({x:j,y:N}))},[z,Z,M]),C=h.useCallback(d=>{if(!l)return;d.preventDefault();const{x:j,y:N}=Z(d);L({x:j,y:N});const P=M(j,N);P>=0&&!u.includes(P)&&S(O=>[...O,P])},[l,Z,M,u]),w=h.useCallback(async()=>{if(!l)return;if(f(!1),L(null),u.length<r){S([]);return}const d=u.join(",");if(m==="set"){if(H===null){K([...u]),S([]);return}if(H.join(",")!==d){K(null),q("failure"),setTimeout(()=>{q("idle"),S([])},800);return}v==null||v([...u]),q("success");return}q("processing");let j=!1;if(x){const N=new TextEncoder,P=await crypto.subtle.digest("SHA-256",N.encode(d));j=Array.from(new Uint8Array(P)).map(Y=>Y.toString(16).padStart(2,"0")).join("")===x}else if(y)j=d===y;else{v==null||v([...u]),q("success");return}if(j)q("success"),A==null||A({success:!0,confidence:1,method:"pattern",timestamp:Date.now(),duration:0}),v==null||v([...u]);else{const N=G+1;_(N),q("failure"),N>=i&&(I==null||I(new Error("Too many failed pattern attempts"))),setTimeout(()=>{q("idle"),S([])},900),A==null||A({success:!1,confidence:0,method:"pattern",timestamp:Date.now(),duration:0})}},[l,u,r,m,H,x,y,G,i,q,v,A,I]);return s.jsxs("div",{className:b,style:{display:"inline-flex",flexDirection:"column",alignItems:"center",gap:12,fontFamily:"var(--security-font)",color:"var(--security-text)"},children:[D&&s.jsx("div",{style:{fontSize:14,fontWeight:600},children:D}),s.jsx("div",{style:{fontSize:13,color:"var(--security-text-secondary)",minHeight:18,textAlign:"center"},children:z==="success"?g("security.pattern.success","Pattern accepted"):z==="failure"?g("security.pattern.wrong","Wrong pattern"):m==="set"&&H!==null?g("security.pattern.confirm","Draw pattern again to confirm"):m==="set"?g("security.pattern.setNew","Draw a new pattern"):g("security.pattern.draw","Draw your pattern")}),s.jsx("canvas",{ref:k,width:$,height:$,style:{touchAction:"none",borderRadius:"var(--security-radius-lg)",background:"var(--security-bg-panel)",border:`1px solid ${z==="failure"?"var(--security-error)":"var(--security-border)"}`,cursor:"pointer",transition:"border-color 0.3s"},onMouseDown:F,onMouseMove:C,onMouseUp:w,onMouseLeave:w,onTouchStart:F,onTouchMove:C,onTouchEnd:w}),(z==="failure"||z==="success")&&s.jsx("button",{onClick:()=>{S([]),_(0),K(null),q("idle")},style:{fontSize:13,padding:"6px 16px",background:"var(--security-bg-panel)",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",color:"var(--security-text)",cursor:"pointer"},children:g("security.common.retry","Try Again")}),G>0&&z!=="success"&&s.jsx("div",{style:{fontSize:11,color:"var(--security-warning)"},children:g("security.pattern.attempts",`${G}/${i} attempts`)})]})},mt={sm:"8px 16px",md:"12px 24px",lg:"14px 32px"},vt={sm:13,md:14,lg:16},xt=e=>{const{mode:t,credentialIds:r=[],challenge:n,rpName:a=window.location.hostname,rpId:i=window.location.hostname,user:o,attestation:c="none",authenticatorAttachment:m,residentKey:x="preferred",userVerification:y="preferred",onRegister:v,onAuthenticate:A,onVerify:p,onStatusChange:I,onError:D,label:b,className:T,variant:g="primary",size:k="md",fullWidth:u=!1,icon:S}=e,{t:l}=Q(),[f,z]=h.useState("idle"),[U,G]=h.useState(!0),[_,H]=h.useState(!1),K=h.useCallback(R=>{z(R),I==null||I(R)},[I]);h.useEffect(()=>{G(ge()),Le().then(H)},[]);const B=h.useCallback(()=>{if(n){const R=atob(n.replace(/-/g,"+").replace(/_/g,"/")),F=new Uint8Array(R.length);for(let C=0;C<R.length;C++)F[C]=R.charCodeAt(C);return F.buffer}return crypto.getRandomValues(new Uint8Array(32)).buffer},[n]),L=h.useCallback(async()=>{if(!U){D==null||D(new Error("WebAuthn not available"));return}K("processing");try{if(t==="register"){const R=(o==null?void 0:o.id)??crypto.getRandomValues(new Uint8Array(16)),F=(o==null?void 0:o.name)??"user",C=(o==null?void 0:o.displayName)??F,w=B(),d=await $e({rpName:a,rpId:i,userId:typeof R=="string"?R:Array.from(R).join(""),userName:F,userDisplayName:C,challenge:w});K("success"),d&&(v==null||v(d)),p==null||p({success:!0,confidence:1,method:"webauthn",timestamp:Date.now(),duration:0})}else{const R=await _e({rpId:i,challenge:B(),allowCredentials:r==null?void 0:r.map(F=>({id:new TextEncoder().encode(F),type:"public-key"}))});K("success"),R&&(A==null||A(R)),p==null||p({success:!0,confidence:1,method:"webauthn",timestamp:Date.now(),duration:0})}}catch(R){const F=R instanceof Error?R:new Error(String(R));F.name==="NotAllowedError"?K("idle"):(K("error"),D==null||D(F),p==null||p({success:!1,confidence:0,method:"webauthn",timestamp:Date.now(),duration:0}))}},[U,t,r,o,a,i,c,m,x,y,B,K,v,A,p,D]),$=t==="register"?_?l("security.webauthn.registerPasskey","Register Passkey"):l("security.webauthn.register","Register Security Key"):_?l("security.webauthn.signInPasskey","Sign in with Passkey"):l("security.webauthn.signIn","Sign in with Security Key"),E=b??$,q={primary:"var(--security-biometric)",outline:"transparent",ghost:"transparent"},W={primary:"none",outline:"2px solid var(--security-biometric)",ghost:"none"},Z={primary:"var(--nice-color-white, #fff)",outline:"var(--security-biometric)",ghost:"var(--security-biometric)"},M=!U||f==="processing"||f==="success";return s.jsxs("div",{className:T,style:{display:u?"block":"inline-block",textAlign:"center"},children:[s.jsxs("button",{onClick:L,disabled:M,style:{width:u?"100%":"auto",padding:mt[k],fontSize:vt[k],fontWeight:600,fontFamily:"var(--security-font)",background:q[g],color:Z[g],border:W[g],borderRadius:"var(--security-radius)",cursor:M?"not-allowed":"pointer",opacity:M?.6:1,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:8,transition:"opacity 0.2s, transform 0.1s"},children:[f==="processing"&&s.jsx("span",{style:{display:"inline-block",width:16,height:16,borderRadius:"50%",border:"2px solid transparent",borderTopColor:"currentColor",animation:"spin 0.6s linear infinite"}}),f==="success"&&s.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:"0.3em",height:"0.6em",marginBottom:"0.15em",borderRight:"0.12em solid currentColor",borderBottom:"0.12em solid currentColor",transform:"rotate(45deg)"}}),S&&f!=="processing"&&f!=="success"&&S,E]}),!U&&s.jsx("div",{style:{fontSize:11,marginTop:6,color:"var(--security-warning)"},children:l("security.webauthn.notAvailable","WebAuthn is not supported in this browser")}),f==="error"&&s.jsx("div",{style:{fontSize:11,marginTop:6,color:"var(--security-error)"},children:l("security.webauthn.error","Authentication failed — try again")}),s.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]})},bt=[],wt=e=>e>=80?"var(--security-error)":e>=50?"var(--security-warning)":"var(--security-success)",St=({entries:e=bt,pageSize:t=20,showExport:r=!0,filterMethods:n,onEntryClick:a,className:i,label:o})=>{const{t:c}=Q(),[m,x]=h.useState("all"),[y,v]=h.useState("all"),[A,p]=h.useState(0),I=h.useMemo(()=>{let l=[...e];return m!=="all"&&(l=l.filter(f=>f.method===m)),y!=="all"&&(l=l.filter(f=>f.status===y)),l.sort((f,z)=>z.timestamp-f.timestamp),l},[e,m,y]),D=Math.max(1,Math.ceil(I.length/t)),b=I.slice(A*t,(A+1)*t),T=h.useMemo(()=>n||Array.from(new Set(e.map(l=>l.method))),[e,n]),g=h.useMemo(()=>Array.from(new Set(e.map(l=>l.status))),[e]),k=h.useCallback(()=>{const l=new Blob([JSON.stringify(I,null,2)],{type:"application/json"}),f=URL.createObjectURL(l),z=document.createElement("a");z.href=f,z.download=`security-audit-${new Date().toISOString().slice(0,10)}.json`,z.click(),URL.revokeObjectURL(f)},[I]),u=l=>new Date(l).toLocaleString(),S={padding:"8px 12px",borderBottom:"1px solid var(--security-border)",fontSize:13,whiteSpace:"nowrap"};return s.jsxs("div",{className:i,style:{fontFamily:"var(--security-font)",color:"var(--security-text)",background:"var(--security-bg)",borderRadius:"var(--security-radius-lg)",border:"1px solid var(--security-border)",overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",background:"var(--security-bg-panel)",borderBottom:"1px solid var(--security-border)"},children:[s.jsx("div",{style:{fontWeight:600,fontSize:15},children:o??c("security.audit.title","Security Audit Log")}),s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[s.jsxs("select",{value:m,onChange:l=>{x(l.target.value),p(0)},style:we,children:[s.jsx("option",{value:"all",children:c("security.audit.allMethods","All methods")}),T.map(l=>s.jsx("option",{value:l,children:l},l))]}),s.jsxs("select",{value:y,onChange:l=>{v(l.target.value),p(0)},style:we,children:[s.jsx("option",{value:"all",children:c("security.audit.allStatuses","All statuses")}),g.map(l=>s.jsx("option",{value:l,children:l},l))]}),r&&s.jsx("button",{onClick:k,style:kt,title:c("security.audit.exportJson","Export JSON"),children:c("security.json","JSON")})]})]}),s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{background:"var(--security-bg-panel)",fontSize:12,color:"var(--security-text-secondary)",textTransform:"uppercase",letterSpacing:.5},children:[s.jsx("th",{style:{...S,textAlign:"left"},children:c("security.audit.time","Time")}),s.jsx("th",{style:{...S,textAlign:"left"},children:c("security.audit.action","Action")}),s.jsx("th",{style:{...S,textAlign:"center"},children:c("security.audit.method","Method")}),s.jsx("th",{style:{...S,textAlign:"center"},children:c("security.audit.status","Status")}),s.jsx("th",{style:{...S,textAlign:"center"},children:c("security.audit.risk","Risk")}),s.jsx("th",{style:{...S,textAlign:"left"},children:c("security.audit.device","Device")})]})}),s.jsxs("tbody",{children:[b.length===0&&s.jsx("tr",{children:s.jsx("td",{colSpan:6,style:{...S,textAlign:"center",color:"var(--security-text-muted)",padding:24},children:c("security.audit.noEntries","No entries to show")})}),b.map(l=>s.jsxs("tr",{onClick:()=>a==null?void 0:a(l),style:{cursor:a?"pointer":"default"},onMouseEnter:f=>{f.currentTarget.style.background="var(--security-bg-panel)"},onMouseLeave:f=>{f.currentTarget.style.background=""},children:[s.jsx("td",{style:S,children:u(l.timestamp)}),s.jsx("td",{style:S,children:l.action}),s.jsx("td",{style:{...S,textAlign:"center"},children:s.jsx("span",{style:{padding:"2px 8px",borderRadius:12,fontSize:11,fontWeight:600,background:"var(--security-bg-panel)",border:"1px solid var(--security-border)"},children:l.method})}),s.jsx("td",{style:{...S,textAlign:"center"},children:l.status}),s.jsx("td",{style:{...S,textAlign:"center"},children:l.riskScore!=null&&s.jsx("span",{style:{color:wt(l.riskScore),fontWeight:600},children:l.riskScore})}),s.jsx("td",{style:{...S,maxWidth:200,overflow:"hidden",textOverflow:"ellipsis"},children:l.device??"—"})]},l.id))]})]})}),D>1&&s.jsxs("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",gap:12,padding:"10px 16px",fontSize:13,color:"var(--security-text-secondary)",borderTop:"1px solid var(--security-border)"},children:[s.jsxs("button",{disabled:A===0,onClick:()=>p(A-1),style:Se,children:[s.jsx(de.NtdArrowLeft,{size:14,style:{verticalAlign:"-2px"}})," ",c("security.audit.prev","Prev")]}),s.jsxs("span",{children:[A+1," / ",D]}),s.jsxs("button",{disabled:A>=D-1,onClick:()=>p(A+1),style:Se,children:[c("security.audit.next","Next")," ",s.jsx(de.NtdArrowRight,{size:14,style:{verticalAlign:"-2px"}})]})]}),s.jsx("div",{style:{padding:"6px 16px",fontSize:11,color:"var(--security-text-muted)",textAlign:"right"},children:c("security.audit.total",`${I.length} entries`)})]})},we={fontSize:12,padding:"4px 8px",background:"var(--security-bg)",color:"var(--security-text)",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)"},kt={background:"none",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",padding:"4px 8px",cursor:"pointer",fontSize:16},Se={background:"none",border:"none",cursor:"pointer",color:"var(--security-biometric)",fontWeight:600,fontSize:13},At=[],ke={display:"inline-block",width:"0.3em",height:"0.6em",margin:"0 0.35em 0.15em 0.1em",borderRight:"0.12em solid currentColor",borderBottom:"0.12em solid currentColor",transform:"rotate(45deg)"},jt=({options:e=At,requiredCount:t=1,onSelect:r,onComplete:n,className:a,label:i,layout:o="grid"})=>{const{t:c}=Q(),m=e.filter(y=>y.verified).length,x=m>=t;return s.jsxs("div",{className:a,style:{fontFamily:"var(--security-font)",color:"var(--security-text)",display:"flex",flexDirection:"column",gap:16},children:[i&&s.jsx("div",{style:{fontSize:15,fontWeight:600},children:i}),t>1&&s.jsx("div",{style:{fontSize:13,color:"var(--security-text-secondary)"},children:c("security.mfa.progress",`Verified ${m} of ${t} required`)}),s.jsx("div",{style:{display:o==="grid"?"grid":"flex",gridTemplateColumns:o==="grid"?"repeat(auto-fill, minmax(140px, 1fr))":void 0,flexDirection:o==="list"?"column":void 0,gap:12},children:e.map(y=>{const v=y.verified??!1,A=y.disabled||x;return s.jsxs("button",{onClick:()=>!A&&!v&&(r==null?void 0:r(y.method)),disabled:A||v,style:{display:"flex",flexDirection:o==="grid"?"column":"row",alignItems:"center",gap:o==="grid"?8:12,padding:o==="grid"?"20px 16px":"12px 16px",background:v?"color-mix(in srgb, var(--nice-color-success, #10b981) 8%, transparent)":"var(--security-bg-panel)",border:`2px solid ${v?"var(--security-success)":"var(--security-border)"}`,borderRadius:"var(--security-radius-lg)",cursor:A||v?"default":"pointer",opacity:A&&!v?.5:1,transition:"border-color 0.2s, background 0.2s",textAlign:o==="grid"?"center":"left"},children:[s.jsx("span",{style:{fontSize:28},children:v?s.jsx("span",{"aria-label":"verified",style:{...ke,color:"var(--security-success)"}}):y.icon}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"var(--security-text)"},children:y.label??y.method}),y.description&&s.jsx("div",{style:{fontSize:11,color:"var(--security-text-muted)",marginTop:2},children:y.description})]})]},y.method)})}),x&&s.jsxs("div",{style:{textAlign:"center",fontSize:14,fontWeight:600,color:"var(--security-success)",padding:8},children:[s.jsx("span",{"aria-hidden":"true",style:ke}),c("security.mfa.complete","All factors verified")]})]})},Tt=[],Ct=({sessions:e=Tt,onRevoke:t,onRevokeAll:r,onTrust:n,className:a,label:i,showRevokeAll:o=!0})=>{const{t:c}=Q(),[m,x]=h.useState(new Set),y=h.useMemo(()=>[...e].sort((p,I)=>(I.current?1:0)-(p.current?1:0)||I.lastActive-p.lastActive),[e]),v=p=>{const I=new Date(p),b=Date.now()-p;return b<6e4?c("security.session.justNow","Just now"):b<36e5?`${Math.floor(b/6e4)}m ago`:b<864e5?`${Math.floor(b/36e5)}h ago`:I.toLocaleDateString()},A=p=>{x(I=>new Set(I).add(p)),t==null||t(p)};return s.jsxs("div",{className:a,style:{fontFamily:"var(--security-font)",color:"var(--security-text)",background:"var(--security-bg)",borderRadius:"var(--security-radius-lg)",border:"1px solid var(--security-border)",overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",background:"var(--security-bg-panel)",borderBottom:"1px solid var(--security-border)"},children:[s.jsx("div",{style:{fontSize:15,fontWeight:600},children:i??c("security.session.title","Active Sessions")}),o&&e.length>1&&s.jsx("button",{onClick:r,style:{fontSize:12,padding:"4px 12px",background:"none",border:"1px solid var(--security-error)",borderRadius:"var(--security-radius)",color:"var(--security-error)",cursor:"pointer"},children:c("security.session.revokeAll","Revoke all others")})]}),s.jsxs("div",{children:[y.map(p=>s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid var(--security-border)",opacity:m.has(p.id)?.5:1,background:p.current?"color-mix(in srgb, var(--nice-color-primary, #3b82f6) 4%, transparent)":void 0},children:[s.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center"},children:[s.jsx("span",{style:{fontSize:10,fontWeight:600,textTransform:"uppercase",color:"var(--security-text-muted)",minWidth:48},children:p.device.toLowerCase().includes("mobile")?c("security.session.mobile","Mobile"):c("security.session.desktop","Desktop")}),s.jsxs("div",{children:[s.jsxs("div",{style:{fontSize:14,fontWeight:500},children:[p.device,p.current&&s.jsx("span",{style:{marginLeft:8,fontSize:10,padding:"1px 6px",background:"var(--security-biometric)",color:"var(--nice-color-white, #fff)",borderRadius:8},children:c("security.session.current","Current")}),p.trusted&&s.jsx("span",{style:{marginLeft:6,fontSize:10,padding:"1px 6px",background:"var(--nice-success-bg, #ecfdf5)",color:"var(--nice-success-text, #065f46)",borderRadius:8},children:c("security.session.trusted","Trusted")})]}),s.jsx("div",{style:{fontSize:12,color:"var(--security-text-muted)",marginTop:2},children:[p.browser,p.os,p.location].filter(Boolean).join(" · ")}),s.jsxs("div",{style:{fontSize:11,color:"var(--security-text-muted)",marginTop:1},children:[c("security.session.lastActive","Last active"),":"," ",v(p.lastActive)]})]})]}),s.jsxs("div",{style:{display:"flex",gap:6},children:[n&&!p.current&&s.jsx("button",{onClick:()=>n(p.id,!p.trusted),style:{fontSize:11,padding:"4px 8px",background:"none",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",cursor:"pointer",color:"var(--security-text-secondary)"},children:p.trusted?c("security.session.untrust","Untrust"):c("security.session.trust","Trust")}),!p.current&&s.jsx("button",{onClick:()=>A(p.id),disabled:m.has(p.id),style:{fontSize:11,padding:"4px 10px",background:"none",border:"1px solid var(--security-error)",borderRadius:"var(--security-radius)",cursor:"pointer",color:"var(--security-error)"},children:c("security.session.revoke","Revoke")})]})]},p.id)),e.length===0&&s.jsx("div",{style:{padding:24,textAlign:"center",color:"var(--security-text-muted)",fontSize:13},children:c("security.session.noSessions","No active sessions")})]})]})},It=({trustScore:e,onScoreComputed:t,trustThreshold:r=60,showFactors:n=!0,showFingerprint:a=!1,className:i,label:o})=>{const{t:c}=Q(),[m,x]=h.useState(e??null),[y,v]=h.useState(!e),A=h.useCallback(async()=>{var I;v(!0);try{const D=pe(),b=await ie(),T=[];let g=50;D.platform&&!D.platform.includes("Linux")&&(T.push({name:"Known platform",score:5,description:"Running on a recognized platform",weight:.05}),g+=5),navigator.cookieEnabled&&(T.push({name:"Cookies enabled",score:5,description:"Browser cookies are enabled",weight:.05}),g+=5),D.screenResolution[0]>=360&&D.screenResolution[1]>=640&&(T.push({name:"Standard resolution",score:5,description:"Screen resolution within normal range",weight:.05}),g+=5),typeof window<"u"&&window.isSecureContext&&(T.push({name:"Secure context",score:10,description:"Running in HTTPS secure context",weight:.1}),g+=10),((I=navigator.languages)==null?void 0:I.length)>0&&(T.push({name:"Language configured",score:5,description:"Browser language is set",weight:.05}),g+=5),D.touchSupport&&(T.push({name:"Touch device",score:5,description:"Touch input is supported",weight:.05}),g+=5);try{const l=document.createElement("canvas").getContext("webgl");l&&l.getExtension("WEBGL_debug_renderer_info")&&(T.push({name:"Hardware GPU",score:10,description:"Hardware GPU detected",weight:.1}),g+=10)}catch{}navigator.credentials&&(T.push({name:"Credential API",score:5,description:"Credential Management API available",weight:.05}),g+=5),g=Math.min(100,Math.max(0,g));const k=Date.now(),u={score:g,factors:T,trusted:g>=r,firstSeen:k,lastSeen:k,fingerprint:b};x(u),t==null||t(u)}finally{v(!1)}},[r,t]);h.useEffect(()=>{e||A()},[e,A]),h.useEffect(()=>{e&&x(e)},[e]);const p=m?m.score>=80?"var(--security-success)":m.score>=50?"var(--security-warning)":"var(--security-error)":"var(--security-text-muted)";return s.jsxs("div",{className:i,style:{fontFamily:"var(--security-font)",color:"var(--security-text)",background:"var(--security-bg-panel)",borderRadius:"var(--security-radius-lg)",border:"1px solid var(--security-border)",padding:20,display:"flex",flexDirection:"column",gap:14,alignItems:"center"},children:[s.jsx("div",{style:{fontSize:15,fontWeight:600},children:o??c("security.trust.title","Device Trust")}),y?s.jsx("div",{style:{fontSize:13,color:"var(--security-text-muted)"},children:c("security.trust.computing","Analysing device…")}):m?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{position:"relative",width:100,height:100},children:[s.jsxs("svg",{viewBox:"0 0 36 36",style:{width:"100%",height:"100%",transform:"rotate(-90deg)"},children:[s.jsx("circle",{cx:"18",cy:"18",r:"15.9",fill:"none",stroke:"var(--security-border)",strokeWidth:"2.5"}),s.jsx("circle",{cx:"18",cy:"18",r:"15.9",fill:"none",stroke:p,strokeWidth:"2.5",strokeDasharray:`${m.score}, 100`,strokeLinecap:"round"})]}),s.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:[s.jsx("span",{style:{fontSize:24,fontWeight:700,color:p},children:m.score}),s.jsx("span",{style:{fontSize:10,color:"var(--security-text-muted)"},children:"/100"})]})]}),s.jsx("div",{style:{fontSize:14,fontWeight:600,color:m.trusted?"var(--security-success)":"var(--security-warning)"},children:m.trusted?c("security.trust.trusted","Device Trusted"):c("security.trust.untrusted","Low Trust Score")}),n&&m.factors.length>0&&s.jsxs("div",{style:{width:"100%",fontSize:12},children:[s.jsxs("div",{style:{fontWeight:600,marginBottom:6,color:"var(--security-text-secondary)"},children:[c("security.trust.factors","Contributing factors"),":"]}),s.jsx("ul",{style:{margin:0,paddingLeft:18,color:"var(--security-text-muted)"},children:m.factors.map((I,D)=>s.jsx("li",{style:{marginBottom:2},children:I.name},D))})]}),a&&m.fingerprint&&s.jsx("div",{style:{fontSize:10,color:"var(--security-text-muted)",wordBreak:"break-all",textAlign:"center",maxWidth:280,fontFamily:"monospace"},children:m.fingerprint})]}):null]})};function Rt(e){if(!e)return 0;let t=0;return e.length>=8&&t++,e.length>=12&&t++,/[a-z]/.test(e)&&/[A-Z]/.test(e)&&t++,/\d/.test(e)&&t++,/[^a-zA-Z0-9]/.test(e)&&t++,/(.)\1{3,}/.test(e)&&t--,Math.max(0,Math.min(4,t))}const Dt=["Very weak","Weak","Fair","Strong","Very strong"],Ae=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #eab308)","var(--nice-success, #22c55e)","var(--nice-success, #10b981)"],Pt=({mode:e="verify",expectedHash:t,minStrength:r=2,minLength:n=8,onComplete:a,onVerify:i,onStatusChange:o,onError:c,label:m,placeholder:x,className:y,showStrength:v=!0,maxAttempts:A=5})=>{const{t:p}=Q(),[I,D]=h.useState(""),[b,T]=h.useState(""),[g,k]=h.useState(!1),[u,S]=h.useState("idle"),[l,f]=h.useState(0),[z,U]=h.useState(""),G=h.useRef(null),_=Rt(I),H=h.useCallback(L=>{S(L),o==null||o(L)},[o]),K=h.useCallback(async()=>{if(U(""),H("processing"),e==="set"){if(I.length<n){U(p("security.passphrase.tooShort",`Minimum ${n} characters`)),H("idle");return}if(_<r){U(p("security.passphrase.tooWeak","Passphrase is too weak")),H("idle");return}if(I!==b){U(p("security.passphrase.noMatch","Passphrases do not match")),H("failure"),setTimeout(()=>H("idle"),1e3);return}a==null||a(I),H("success");return}if(t){const L=new TextEncoder,$=await crypto.subtle.digest("SHA-256",L.encode(I));if(Array.from(new Uint8Array($)).map(W=>W.toString(16).padStart(2,"0")).join("")===t)H("success"),i==null||i({success:!0,confidence:1,method:"passphrase",timestamp:Date.now(),duration:0}),a==null||a(I);else{const W=l+1;f(W),W>=A?(H("failure"),c==null||c(new Error("Too many failed attempts"))):(U(p("security.passphrase.incorrect","Incorrect passphrase")),H("idle")),i==null||i({success:!1,confidence:0,method:"passphrase",timestamp:Date.now(),duration:0})}}else a==null||a(I),H("success")},[I,b,e,t,_,r,n,l,A,p,H,a,i,c]),B={width:"100%",padding:"10px 14px",fontSize:14,background:"var(--security-bg)",color:"var(--security-text)",border:`1px solid ${u==="failure"?"var(--security-error)":"var(--security-border)"}`,borderRadius:"var(--security-radius)",boxSizing:"border-box",fontFamily:"var(--security-font)"};return s.jsxs("div",{className:y,style:{display:"flex",flexDirection:"column",gap:10,maxWidth:340,fontFamily:"var(--security-font)",color:"var(--security-text)"},children:[m&&s.jsx("label",{style:{fontSize:14,fontWeight:600},children:m}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{ref:G,type:g?"text":"password",value:I,onChange:L=>D(L.target.value),placeholder:x??p("security.passphrase.placeholder","Enter passphrase"),style:B,disabled:u==="success",onKeyDown:L=>L.key==="Enter"&&K()}),s.jsx("button",{type:"button",onClick:()=>k(!g),style:{position:"absolute",right:8,top:"50%",transform:"translateY(-50%)",background:"none",border:"none",cursor:"pointer",fontSize:16,color:"var(--security-text-muted)"},tabIndex:-1,children:g?p("security.passphrase.hide","Hide"):p("security.passphrase.show","Show")})]}),e==="set"&&v&&I.length>0&&s.jsxs("div",{children:[s.jsx("div",{style:{display:"flex",gap:3,height:4},children:[0,1,2,3].map(L=>s.jsx("div",{style:{flex:1,borderRadius:2,background:L<_?Ae[_]:"var(--security-border)",transition:"background 0.2s"}},L))}),s.jsx("div",{style:{fontSize:11,marginTop:4,color:Ae[_]},children:p(`security.passphrase.strength${_}`,Dt[_])})]}),e==="set"&&s.jsx("input",{type:g?"text":"password",value:b,onChange:L=>T(L.target.value),placeholder:p("security.passphrase.confirmPlaceholder","Confirm passphrase"),style:B,disabled:u==="success",onKeyDown:L=>L.key==="Enter"&&K(),onPaste:L=>L.preventDefault()}),z&&s.jsx("div",{style:{fontSize:12,color:"var(--security-error)"},children:z}),s.jsx("button",{onClick:K,disabled:!I||u==="processing"||u==="success",style:{padding:"10px 20px",fontSize:14,fontWeight:600,background:u==="success"?"var(--security-success)":"var(--security-biometric)",color:"var(--nice-color-white, #fff)",border:"none",borderRadius:"var(--security-radius)",cursor:u==="success"?"default":"pointer",opacity:!I||u==="processing"?.6:1},children:u==="success"?p("security.passphrase.accepted","Accepted"):e==="set"?p("security.passphrase.setBtn","Set Passphrase"):p("security.passphrase.verifyBtn","Verify")}),l>0&&u!=="success"&&s.jsx("div",{style:{fontSize:11,color:"var(--security-warning)"},children:p("security.passphrase.attempts",`${l}/${A} attempts`)})]})};function Mt(e){const t=[],r={defaultSrc:"default-src",scriptSrc:"script-src",styleSrc:"style-src",imgSrc:"img-src",fontSrc:"font-src",connectSrc:"connect-src",frameSrc:"frame-src",objectSrc:"object-src",mediaSrc:"media-src",workerSrc:"worker-src",childSrc:"child-src",formAction:"form-action",frameAncestors:"frame-ancestors",baseUri:"base-uri",reportUri:"report-uri",reportTo:"report-to",upgradeInsecureRequests:"upgrade-insecure-requests",blockAllMixedContent:"block-all-mixed-content"};return Object.entries(e.directives).forEach(([n,a])=>{const i=r[n];if(i){if(typeof a=="boolean")a&&t.push(i);else if(typeof a=="string")t.push(`${i} ${a}`);else if(Array.isArray(a)){let o=a;e.nonce&&(n==="scriptSrc"||n==="styleSrc")&&(o=[...o,`'nonce-${e.nonce}'`]),t.push(`${i} ${o.join(" ")}`)}}}),t.join("; ")}function Et(e){const t="'self'";return{defaultSrc:[t],scriptSrc:[t],styleSrc:[t,"'unsafe-inline'"],imgSrc:[t,"data:","blob:",e==null?void 0:e.cdnDomain].filter(Boolean),fontSrc:[t,"data:",e==null?void 0:e.cdnDomain].filter(Boolean),connectSrc:[t,e==null?void 0:e.apiDomain,"wss:"].filter(Boolean),frameSrc:["'none'"],objectSrc:["'none'"],baseUri:[t],formAction:[t],frameAncestors:["'none'"],upgradeInsecureRequests:!0,reportUri:e==null?void 0:e.reportUri}}function Ft(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).substring(2)+Date.now().toString(36)}const Nt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function We(e){return e.replace(/[&<>"'`=/]/g,t=>Nt[t]||t)}function zt(e,t){let r=We(e);return t!=null&&t.maxLength&&r.length>t.maxLength&&(r=r.substring(0,t.maxLength)),r}function Lt(e){if(!e)return null;try{const t=new URL(e);return!["http:","https:","mailto:","tel:"].includes(t.protocol)||e.toLowerCase().includes("javascript:")?null:t.toString()}catch{return null}}function $t(e){const t=["script","iframe","object","embed","form"];let r=e;t.forEach(i=>{const o=new RegExp(`<${i}[^>]*>.*?</${i}>`,"gi");r=r.replace(o,"");const c=new RegExp(`<${i}[^>]*/>`,"gi");r=r.replace(c,"")});const n=/\s+on\w+\s*=/gi;r=r.replace(n," data-removed=");const a=/javascript:/gi;return r=r.replace(a,""),r}function _t(e,t){let r=e;if(t!=null&&t.allowedTags){const n=/<\/?([a-z][a-z0-9]*)[^>]*>/gi;r=r.replace(n,(a,i)=>t.allowedTags.includes(i.toLowerCase())?a:"")}return r=r.replace(/\s+on\w+\s*=/gi," data-removed="),r=r.replace(/javascript:/gi,""),{__html:r}}const me={headerName:"X-CSRF-Token",cookieName:"XSRF-TOKEN",fieldName:"_csrf"};function Bt(){if(typeof crypto<"u"){const e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}return Math.random().toString(36).substring(2)+Date.now().toString(36)}function ve(e=me.cookieName){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]+)`));return t?decodeURIComponent(t[2]):null}function Wt(e=me){return async function(r,n={}){const a=ve(e.cookieName);a||console.warn("CSRF token not found");const i=new Headers(n.headers);return a&&e.headerName&&i.set(e.headerName,a),fetch(r,{...n,headers:i})}}function Ht(e=me){const t=ve(e.cookieName);return{token:t,inputProps:{type:"hidden",name:e.fieldName,value:t||""},headerName:e.headerName}}function He(e){const t=new Map,r=e.keyGenerator||(i=>i.url);function n(i){const o=r(i),c=Date.now();let m=t.get(o);(!m||c>m.resetAt)&&(m={count:0,resetAt:c+e.windowMs}),m.count++,t.set(o,m);const x=m.count<=e.maxRequests,y=Math.max(0,e.maxRequests-m.count);return{allowed:x,remaining:y,resetAt:m.resetAt}}function a(i){i?t.delete(i):t.clear()}return{checkLimit:n,reset:a}}function Ot(e){const t=He(e);return{checkAndFetch:async(n,a)=>{const i=t.checkLimit({url:n,method:a==null?void 0:a.method});if(!i.allowed){const o=Math.ceil((i.resetAt-Date.now())/1e3);throw new Error(`Rate limit exceeded. Retry after ${o} seconds.`)}return fetch(n,a)},checkLimit:t.checkLimit,reset:t.reset}}function Oe(e,t){const r=[];if(t.allowedTypes&&t.allowedTypes.length>0&&(t.allowedTypes.includes(e.type)||r.push(`File type '${e.type}' is not allowed. Allowed types: ${t.allowedTypes.join(", ")}`)),t.maxSize&&e.size>t.maxSize){const i=(t.maxSize/1048576).toFixed(2),o=(e.size/(1024*1024)).toFixed(2);r.push(`File size (${o}MB) exceeds maximum allowed size (${i}MB)`)}const n=[".exe",".bat",".cmd",".sh",".ps1",".vbs",".js",".jar"],a=e.name.toLowerCase();for(const i of n)if(a.includes(i+".")||a.endsWith(i)){r.push(`File extension '${i}' is not allowed`);break}return{valid:r.length===0,errors:r,file:r.length===0?e:void 0}}function Ut(e,t){const r=[],n=[],a=[];t.maxFiles&&e.length>t.maxFiles&&r.push(`Too many files. Maximum allowed: ${t.maxFiles}`);const i=e.reduce((o,c)=>o+c.size,0);if(t.maxTotalSize&&i>t.maxTotalSize){const o=(t.maxTotalSize/1048576).toFixed(2),c=(i/(1024*1024)).toFixed(2);r.push(`Total file size (${c}MB) exceeds maximum (${o}MB)`)}return e.forEach(o=>{const c=Oe(o,t);c.valid?n.push(o):a.push({file:o,errors:c.errors})}),{valid:r.length===0&&a.length===0,errors:[...r,...a.flatMap(o=>o.errors)],validFiles:n,invalidFiles:a}}async function qt(e,t){const r=new FormData;r.append("file",e);try{const n=await fetch(t,{method:"POST",body:r});if(!n.ok)throw new Error("Virus scan failed");return await n.json()}catch(n){return console.error("Virus scan error:",n),{clean:!1,threat:"Scan failed"}}}function Ue(){if(typeof localStorage>"u")return null;const e=localStorage.getItem("nice2dev_consent");if(!e)return null;try{return JSON.parse(e)}catch{return null}}function Kt(e){typeof localStorage>"u"||localStorage.setItem("nice2dev_consent",JSON.stringify({...e,necessary:!0,timestamp:new Date().toISOString()}))}function Gt(e){const t=Ue();return t?t[e]===!0:!1}function Yt(e){if(typeof document>"u")return;document.cookie.split(";").forEach(r=>{const[n]=r.trim().split("=");e.includes(n)||(document.cookie=`${n}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`)})}async function Jt(e,t,r=fetch){const n={exportDate:new Date().toISOString(),userId:e};return await Promise.all(Object.entries(t).map(async([a,i])=>{try{const o=await r(i);o.ok&&(n[a]=await o.json())}catch(o){console.error(`Failed to fetch ${a} data:`,o),n[a]={error:"Failed to retrieve data"}}})),n}async function Zt(e,t,r=fetch){try{const n=await r(t,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:e,timestamp:new Date().toISOString()})});return n.ok?{success:!0,confirmationId:(await n.json()).confirmationId}:{success:!1,error:"Deletion request failed"}}catch(n){return{success:!1,error:String(n)}}}function Xt(e,t){var n;const r={...e,id:((n=crypto.randomUUID)==null?void 0:n.call(crypto))||Math.random().toString(36),timestamp:new Date};return t&&fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}).catch(console.error),process.env.NODE_ENV==="development"&&console.warn("[HIPAA] PHI Access:",r),r}function Qt(e){let t=null,r=null,n=Date.now();const a=e.timeoutMinutes*60*1e3,i=e.warningBeforeMs||6e4;function o(){n=Date.now(),t&&clearTimeout(t),r&&clearTimeout(r),e.onWarning&&(r=setTimeout(()=>{var y;const x=a-(Date.now()-n);(y=e.onWarning)==null||y.call(e,x)},a-i)),t=setTimeout(e.onTimeout,a)}function c(){t&&clearTimeout(t),r&&clearTimeout(r)}function m(){return Math.max(0,a-(Date.now()-n))}return o(),typeof window<"u"&&["mousedown","keypress","touchstart","scroll"].forEach(y=>{window.addEventListener(y,o,{passive:!0})}),{resetTimer:o,destroy:c,getTimeRemaining:m}}function Vt(e,t){const r=o=>{const c=o.replace("#",""),m=parseInt(c.substr(0,2),16)/255,x=parseInt(c.substr(2,2),16)/255,y=parseInt(c.substr(4,2),16)/255,v=A=>A<=.03928?A/12.92:Math.pow((A+.055)/1.055,2.4);return .2126*v(m)+.7152*v(x)+.0722*v(y)},n=r(e),a=r(t),i=(Math.max(n,a)+.05)/(Math.min(n,a)+.05);return{ratio:Math.round(i*100)/100,passesAA:i>=4.5,passesAAA:i>=7,passesAALarge:i>=3,passesAAALarge:i>=4.5}}function er(e){var r,n,a;if(e.getAttribute("aria-label"))return!0;const t=e.getAttribute("aria-labelledby");if(t){const i=document.getElementById(t);if((r=i==null?void 0:i.textContent)!=null&&r.trim())return!0}if(e.id){const i=document.querySelector(`label[for="${e.id}"]`);if((n=i==null?void 0:i.textContent)!=null&&n.trim())return!0}return!!((a=e.textContent)!=null&&a.trim()||e.getAttribute("title")||e.placeholder)}function tr(e){const r=(e||document.body).querySelectorAll("h1, h2, h3, h4, h5, h6"),n=[];let a=0,i=!1;return r.forEach(o=>{const c=parseInt(o.tagName[1]);c===1&&(i&&n.push({level:c,element:o,issue:"Multiple H1 elements found"}),i=!0),c>a+1&&a!==0&&n.push({level:c,element:o,issue:`Skipped heading level: H${a} to H${c}`}),a=c}),!i&&r.length>0&&n.push({level:0,element:r[0],issue:"Missing H1 element"}),{valid:n.length===0,issues:n}}function rr(e){const t=[];let r=null;const n=e.batchSize||10,a=e.flushInterval||5e3;async function i(){if(t.length===0)return;const x=t.splice(0,n);try{await fetch(e.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:x})})}catch(y){console.error("Failed to send audit logs:",y),t.unshift(...x)}}function o(){r||(r=setTimeout(()=>{r=null,i()},a))}function c(x){var v;const y={...x,id:((v=crypto.randomUUID)==null?void 0:v.call(crypto))||Math.random().toString(36),timestamp:new Date,userAgent:e.includeUserAgent&&typeof navigator<"u"?navigator.userAgent:void 0};t.push(y),t.length>=n?i():o()}function m(){r&&clearTimeout(r),i()}return{log:c,flush:i,destroy:m}}function sr(){return[{controlId:"CC6.1",name:"Logical and Physical Access Controls",category:"security",status:"in_progress",lastAssessed:new Date},{controlId:"CC6.2",name:"User Registration and Authorization",category:"security",status:"in_progress",lastAssessed:new Date},{controlId:"CC6.3",name:"Access Control Removal",category:"security",status:"in_progress",lastAssessed:new Date},{controlId:"A1.1",name:"System Capacity",category:"availability",status:"in_progress",lastAssessed:new Date},{controlId:"A1.2",name:"Backup and Recovery",category:"availability",status:"in_progress",lastAssessed:new Date},{controlId:"C1.1",name:"Confidential Information Classification",category:"confidentiality",status:"in_progress",lastAssessed:new Date},{controlId:"C1.2",name:"Confidential Information Disposal",category:"confidentiality",status:"in_progress",lastAssessed:new Date},{controlId:"P1.1",name:"Privacy Notice",category:"privacy",status:"in_progress",lastAssessed:new Date},{controlId:"P2.1",name:"Consent",category:"privacy",status:"in_progress",lastAssessed:new Date},{controlId:"P3.1",name:"Collection",category:"privacy",status:"in_progress",lastAssessed:new Date}]}const nr={hardcodedSecrets:[{pattern:/password\s*[:=]\s*["'][^"']+["']/gi,name:"Hardcoded password"},{pattern:/api[_-]?key\s*[:=]\s*["'][^"']+["']/gi,name:"Hardcoded API key"},{pattern:/secret\s*[:=]\s*["'][^"']+["']/gi,name:"Hardcoded secret"},{pattern:/token\s*[:=]\s*["'][^"']+["']/gi,name:"Hardcoded token"}],sqlInjection:[{pattern:/execute\s*\(\s*["'`].*\$\{/gi,name:"Potential SQL injection (template literal)"},{pattern:/query\s*\(\s*["'`].*\+/gi,name:"Potential SQL injection (string concatenation)"}],xss:[{pattern:/dangerouslySetInnerHTML/g,name:"dangerouslySetInnerHTML usage"},{pattern:/innerHTML\s*=/g,name:"innerHTML assignment"},{pattern:/document\.write\s*\(/g,name:"document.write usage"},{pattern:/eval\s*\(/g,name:"eval usage"}],insecureFunctions:[{pattern:/Math\.random\s*\(\)/g,name:"Insecure random (use crypto)"},{pattern:/new Function\s*\(/g,name:"Function constructor (code injection risk)"},{pattern:/setTimeout\s*\(\s*["']/g,name:"setTimeout with string (code injection)"},{pattern:/setInterval\s*\(\s*["']/g,name:"setInterval with string (code injection)"}],infoExposure:[{pattern:/console\.(log|info|warn|error)\s*\(/g,name:"Console logging (remove in production)"},{pattern:/debugger/g,name:"Debugger statement"},{pattern:/TODO.*password/gi,name:"TODO mentioning password"}]};function ir(){return`# .github/workflows/sast.yml
6
+ `})]})},nt={sm:240,md:320,lg:440},it=e=>{const{mode:t,enrolledTemplates:r=[],referencePhoto:n,onEnroll:o,onVerify:a,onStatusChange:c,onError:i,className:p,size:b="md",label:y,showQuality:w=!0,showBoundingBox:j=!0,livenessSteps:m=1,showReference:C=!0,instructionText:z,...g}=e,{t:I}=X(),k=oe(g),x=nt[b],l=h.useRef(null),S=h.useRef(null),u=h.useRef(null),[f,D]=h.useState("idle"),[q,K]=h.useState(0),[B,H]=h.useState(0),[G,$]=h.useState(""),[L,_]=h.useState(null),[E,U]=h.useState(0),W=h.useCallback(v=>{D(v),c==null||c(v)},[c]),Z=h.useCallback(async()=>{try{const v=await le("user");u.current=v,l.current&&(l.current.srcObject=v,await l.current.play()),W("idle"),$(I("security.face.lookAtCamera","Look at the camera"))}catch(v){i==null||i(v instanceof Error?v:new Error(String(v))),$(I("security.face.cameraError","Camera access denied")),W("error")}},[I,W,i]),M=h.useCallback(()=>{var v;(v=u.current)==null||v.getTracks().forEach(d=>d.stop()),u.current=null},[]);h.useEffect(()=>(Z(),M),[Z,M]);const F=h.useCallback(v=>{var ee,xe,be;const d=(ee=S.current)==null?void 0:ee.getContext("2d");if(!d)return;const A=S.current.width,N=S.current.height;if(d.clearRect(0,0,A,N),!v||!j)return;const P=v.boundingBox,O=A/(((xe=l.current)==null?void 0:xe.videoWidth)??A),Y=N/(((be=l.current)==null?void 0:be.videoHeight)??N);d.strokeStyle=Q(f==="success"?"var(--nice-success, #10b981)":"var(--nice-primary, #3b82f6)",d.canvas),d.lineWidth=2,d.setLineDash([6,4]),d.strokeRect(P.x*O,P.y*Y,P.width*O,P.height*Y),d.setLineDash([]);const V=[[P.x*O,P.y*Y],[(P.x+P.width)*O,P.y*Y],[P.x*O,(P.y+P.height)*Y],[(P.x+P.width)*O,(P.y+P.height)*Y]],J=12;d.lineWidth=3;for(const[te,re]of V)d.beginPath(),d.moveTo(te===P.x*O?te:te-J,re),d.lineTo(te,re),d.lineTo(te,re===P.y*Y?re+J:re-J),d.stroke()},[j,f]),R=h.useCallback(async()=>{if(!(!l.current||f==="processing"||f==="success")){W("scanning"),$(I("security.face.scanning","Scanning face…"));try{if(k.livenessDetection){const A=[];for(let P=0;P<8;P++)A.push(se(l.current).imageData),await new Promise(O=>setTimeout(O,200));if(!ye(A).isLive){$(I("security.face.notLive","Liveness check failed — move naturally")),W("idle");return}}W("processing"),$(I("security.face.processing","Analysing face…"));const{imageData:v}=se(l.current);if(t==="compare"&&n){const A=typeof n=="string"?await at(n):ot(n),{similarity:N,cameraFeatures:P,refFeatures:O}=Fe(v,A);U(N),K((P==null?void 0:P.quality)??0),F(P);const V={success:N>=k.matchThreshold,confidence:N,method:"face",timestamp:Date.now(),duration:0,livenessPassed:k.livenessDetection};V.success?($(I("security.face.matchFound","Match: {percent}%").replace("{percent}",(N*100).toFixed(0))),W("success")):(H(J=>J+1),B+1>=k.maxRetries?($(I("security.face.maxAttempts","Maximum attempts reached")),W("failure")):($(I("security.face.noMatch","No match — try again")),W("idle"))),a==null||a(V);return}const d=ae(v);if(!d){$(I("security.face.noFaceDetected","No face detected")),W("idle");return}if(K(d.quality),F(d),t==="enroll"){const A=await Ne(d,y??"face");o==null||o(A,d),$(I("security.face.enrolled","Face enrolled successfully")),W("success")}else{let A=0;for(const O of r){const Y=ze(O),V=fe(d,Y);V>A&&(A=V)}U(A);const N=A>=k.matchThreshold,P={success:N,confidence:A,method:"face",timestamp:Date.now(),duration:0,livenessPassed:k.livenessDetection};if(N&&k.verifyEndpoint){const O=await ie(),Y=await ue(k.verifyEndpoint,{method:"face",templateData:btoa(JSON.stringify(d)),matchScore:A,deviceFingerprint:O},k.authToken);P.success=Y.verified}P.success?($(I("security.face.verified","Face verified")),W("success")):(H(O=>O+1),B+1>=k.maxRetries?($(I("security.face.maxAttempts","Maximum attempts reached")),W("failure")):($(I("security.face.noMatch","No match — try again")),W("idle"))),a==null||a(P)}}catch(v){i==null||i(v instanceof Error?v:new Error(String(v))),$(I("security.face.error","Error — try again")),W("error")}}},[f,t,r,n,k,I,W,o,a,i,y,B,F]),T=f==="success"?"var(--security-success)":f==="failure"||f==="error"?"var(--security-error)":f==="scanning"||f==="processing"?"var(--security-biometric)":"var(--security-border)";return s.jsxs("div",{className:p,style:{display:"inline-flex",flexDirection:"column",alignItems:"center",gap:12},children:[y&&s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"var(--security-text)"},children:y}),s.jsxs("div",{style:{display:"flex",gap:16,alignItems:"center"},children:[s.jsxs("div",{style:{width:x,height:x*.75,position:"relative",borderRadius:"var(--security-radius-lg)",overflow:"hidden",border:`3px solid ${T}`,boxShadow:f==="scanning"?`0 0 20px ${T}`:"var(--security-shadow)",transition:"border-color 0.3s, box-shadow 0.3s"},children:[s.jsx("video",{ref:l,style:{width:"100%",height:"100%",objectFit:"cover",transform:"scaleX(-1)"},playsInline:!0,muted:!0}),s.jsx("canvas",{ref:S,width:x,height:x*.75,style:{position:"absolute",inset:0,pointerEvents:"none",transform:"scaleX(-1)"}}),s.jsx("svg",{viewBox:"0 0 100 75",style:{position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none",opacity:.3},children:s.jsx("ellipse",{cx:"50",cy:"37",rx:"22",ry:"30",fill:"none",stroke:"white",strokeWidth:"0.8",strokeDasharray:"4 3"})}),(f==="scanning"||f==="processing")&&s.jsx("div",{style:{position:"absolute",inset:0,background:"var(--nice-overlay-15, rgba(0, 0, 0, 0.15))",display:"flex",alignItems:"center",justifyContent:"center"},children:s.jsx("div",{style:{width:50,height:50,borderRadius:"50%",border:"3px solid transparent",borderTopColor:T,animation:"spin 0.8s linear infinite"}})})]}),t==="compare"&&C&&n&&s.jsxs("div",{style:{width:x*.4,height:x*.5,borderRadius:"var(--security-radius)",overflow:"hidden",border:"2px solid var(--security-border)"},children:[s.jsx("img",{src:typeof n=="string"?n:void 0,alt:I("security.face.referenceAlt","Reference"),style:{width:"100%",height:"100%",objectFit:"cover"}}),s.jsx("div",{style:{textAlign:"center",fontSize:10,padding:4,color:"var(--security-text-muted)",background:"var(--security-bg-panel)"},children:I("security.face.reference","Reference")})]})]}),E>0&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13},children:[s.jsxs("span",{style:{color:"var(--security-text-secondary)"},children:[I("security.face.confidence","Confidence"),":"]}),s.jsx("div",{style:{width:100,height:6,background:"var(--security-bg-panel)",borderRadius:3,overflow:"hidden"},children:s.jsx("div",{style:{width:`${E*100}%`,height:"100%",background:E>=k.matchThreshold?"var(--security-success)":"var(--security-warning)"}})}),s.jsxs("span",{style:{fontWeight:600,color:E>=k.matchThreshold?"var(--security-success)":"var(--security-warning)"},children:[(E*100).toFixed(0),"%"]})]}),s.jsx("div",{style:{fontSize:13,color:"var(--security-text-secondary)",textAlign:"center",minHeight:20},children:z??G}),f!=="success"&&f!=="failure"&&s.jsx("button",{onClick:R,disabled:f==="scanning"||f==="processing",style:{padding:"10px 24px",fontSize:14,fontWeight:600,background:"var(--security-biometric)",color:"var(--nice-color-white, #fff)",border:"none",borderRadius:"var(--security-radius)",cursor:"pointer",opacity:f==="scanning"||f==="processing"?.6:1},children:t==="enroll"?I("security.face.captureBtn","Capture Face"):t==="compare"?I("security.face.compareBtn","Compare"):I("security.face.verifyBtn","Verify Face")}),(f==="failure"||f==="error")&&s.jsx("button",{onClick:()=>{H(0),U(0),W("idle"),$("")},style:{padding:"8px 20px",fontSize:13,background:"var(--security-bg-panel)",color:"var(--security-text)",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",cursor:"pointer"},children:I("security.common.retry","Try Again")}),s.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]})};async function at(e){return new Promise((t,r)=>{const n=new Image;n.crossOrigin="anonymous",n.onload=()=>{const o=document.createElement("canvas");o.width=n.naturalWidth,o.height=n.naturalHeight;const a=o.getContext("2d");a.drawImage(n,0,0),t(a.getImageData(0,0,o.width,o.height))},n.onerror=()=>r(new Error("Failed to load reference image")),n.src=e})}function ot(e){const t=document.createElement("canvas");t.width=e.naturalWidth||e.width,t.height=e.naturalHeight||e.height;const r=t.getContext("2d");return r.drawImage(e,0,0),r.getImageData(0,0,t.width,t.height)}const ct=4,lt=5,ut=3e4,dt=e=>{const{length:t=ct,scramble:r=!1,showDigits:n=!1,maxAttempts:o=lt,lockoutDuration:a=ut,keySize:c=64,haptic:i=!0,keyLabels:p,expectedHash:b,expectedPin:y,mode:w="verify",onComplete:j,onVerify:m,onStatusChange:C,onError:z,showBiometricFallback:g=!1,onBiometricFallback:I,label:k,className:x}=e,{t:l}=X(),[S,u]=h.useState([]),[f,D]=h.useState("idle"),[q,K]=h.useState(0),[B,H]=h.useState(0),[G,$]=h.useState(null),L=h.useRef(void 0),_=h.useMemo(()=>{const R=["1","2","3","4","5","6","7","8","9","","0","back"];if(!r)return R;const T=["0","1","2","3","4","5","6","7","8","9"];for(let v=T.length-1;v>0;v--){const d=new Uint32Array(1);crypto.getRandomValues(d);const A=d[0]%(v+1);[T[v],T[A]]=[T[A],T[v]]}return[T[0],T[1],T[2],T[3],T[4],T[5],T[6],T[7],T[8],"",T[9],"back"]},[r,f]),E=h.useCallback(R=>{D(R),C==null||C(R)},[C]);h.useEffect(()=>{if(!(B<=Date.now()))return L.current=setInterval(()=>{Date.now()>=B&&(clearInterval(L.current),E("idle"),K(0),u([]))},500),()=>clearInterval(L.current)},[B,E]);const U=B>Date.now(),W=h.useCallback(()=>{i&&navigator.vibrate&&navigator.vibrate(20)},[i]),Z=h.useCallback(async R=>{if(U||f==="success")return;if(W(),R==="back"){u(A=>A.slice(0,-1));return}if(R==="")return;const T=[...S,R];if(u(T),T.length<t)return;const v=T.join("");if(E("processing"),w==="set"){if(G===null){$(v),u([]),E("idle");return}if(G!==v){$(null),u([]),E("failure"),setTimeout(()=>E("idle"),1200);return}j==null||j(v),E("success");return}let d=!1;if(b){const A=new TextEncoder,N=await crypto.subtle.digest("SHA-256",A.encode(v));d=Array.from(new Uint8Array(N)).map(O=>O.toString(16).padStart(2,"0")).join("")===b}else if(y)d=v===y;else{j==null||j(v),E("success");return}if(d)E("success"),m==null||m({success:!0,confidence:1,method:"pin",timestamp:Date.now(),duration:0}),j==null||j(v);else{const A=q+1;if(K(A),A>=o){const N=Date.now()+a;H(N),E("failure"),z==null||z(new Error("Too many failed PIN attempts"))}else E("failure"),setTimeout(()=>{E("idle"),u([])},800);m==null||m({success:!1,confidence:0,method:"pin",timestamp:Date.now(),duration:0})}},[S,t,U,f,w,G,b,y,q,o,a,W,E,j,m,z]),M=Math.max(0,Math.ceil((B-Date.now())/1e3)),F=f==="success"?"var(--security-success)":f==="failure"?"var(--security-error)":"var(--security-border)";return s.jsxs("div",{className:x,style:{display:"inline-flex",flexDirection:"column",alignItems:"center",gap:16,fontFamily:"var(--security-font)",color:"var(--security-text)"},children:[k&&s.jsx("div",{style:{fontSize:14,fontWeight:600},children:k}),s.jsx("div",{style:{fontSize:13,color:"var(--security-text-secondary)",minHeight:18,textAlign:"center"},children:U?l("security.pin.locked","Locked — try again in {seconds}s").replace("{seconds}",String(M)):w==="set"&&G!==null?l("security.pin.confirm","Confirm your PIN"):w==="set"?l("security.pin.setNew","Enter a new PIN"):l("security.pin.enter","Enter your PIN")}),s.jsx("div",{style:{display:"flex",gap:12},children:Array.from({length:t},(R,T)=>s.jsx("div",{style:{width:16,height:16,borderRadius:"50%",border:`2px solid ${F}`,background:T<S.length?F:"transparent",transition:"background 0.15s, border-color 0.15s"}},T))}),s.jsx("div",{style:{display:"grid",gridTemplateColumns:`repeat(3, ${c}px)`,gap:10,opacity:U?.4:1,pointerEvents:U?"none":"auto"},children:_.map((R,T)=>{if(R==="")return s.jsx("div",{},T);const v=R==="back";return s.jsx("button",{onClick:()=>Z(R),disabled:U||f==="success","aria-label":v?l("security.pin.backspace","Backspace"):R,style:{width:c,height:c,borderRadius:"var(--security-key-border-radius, 50%)",border:"1px solid var(--security-key-border, var(--security-border))",background:"var(--security-key-bg, var(--security-bg-panel))",color:"var(--security-key-text, var(--security-text))",fontSize:v?20:22,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.1s, transform 0.1s",userSelect:"none"},onMouseDown:d=>{d.currentTarget.style.transform="scale(0.92)"},onMouseUp:d=>{d.currentTarget.style.transform=""},onMouseLeave:d=>{d.currentTarget.style.transform=""},children:v?s.jsx(de.NtdBackspace,{size:22}):(p==null?void 0:p[R])??R},T)})}),S.length>0&&f!=="success"&&s.jsx("button",{onClick:()=>u([]),style:{fontSize:12,background:"none",border:"none",color:"var(--security-text-secondary)",cursor:"pointer",textDecoration:"underline"},children:l("security.pin.clear","Clear")}),g&&s.jsx("button",{onClick:I,style:{fontSize:13,padding:"8px 16px",background:"none",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",color:"var(--security-biometric)",cursor:"pointer"},children:l("security.pin.biometricFallback","Use biometrics instead")}),q>0&&f!=="success"&&!U&&s.jsx("div",{style:{fontSize:11,color:"var(--security-warning)"},children:l("security.pin.attempts","{attempts}/{max} attempts").replace("{attempts}",String(q)).replace("{max}",String(o))})]})},ht=3,ft=4,yt=5,pt=14,gt=e=>{const{gridSize:t=ht,minLength:r=ft,showTrail:n=!0,showError:o=!0,maxAttempts:a=yt,dotSize:c=pt,trailColor:i,mode:p="verify",expectedHash:b,expectedPattern:y,onComplete:w,onVerify:j,onStatusChange:m,onError:C,label:z,className:g,canvasSize:I}=e,{t:k}=X(),x=h.useRef(null),[l,S]=h.useState([]),[u,f]=h.useState(!1),[D,q]=h.useState("idle"),[K,B]=h.useState(0),[H,G]=h.useState(null),[$,L]=h.useState(null),_=I??t*80,E=_/t,U=h.useCallback(d=>{q(d),m==null||m(d)},[m]),W=h.useCallback(()=>{const d=[];for(let A=0;A<t;A++)for(let N=0;N<t;N++)d.push({x:N*E+E/2,y:A*E+E/2});return d},[t,E]),Z=h.useCallback(d=>{const A=x.current.getBoundingClientRect(),N="touches"in d?d.touches[0].clientX:d.clientX,P="touches"in d?d.touches[0].clientY:d.clientY;return{x:N-A.left,y:P-A.top}},[]),M=h.useCallback((d,A)=>{const N=W(),P=E*.38;for(let O=0;O<N.length;O++){const Y=N[O].x-d,V=N[O].y-A;if(Y*Y+V*V<P*P)return O}return-1},[W,E]),F=h.useCallback(()=>{var V;const d=(V=x.current)==null?void 0:V.getContext("2d");if(!d)return;d.clearRect(0,0,_,_);const A=W(),N=D==="failure",P=d.canvas,O=Q(N&&o?"var(--security-error)":i??"var(--security-biometric)",P),Y=Q("var(--security-border)",P);for(let J=0;J<A.length;J++){const ee=l.includes(J);d.beginPath(),d.arc(A[J].x,A[J].y,ee?c*.75:c*.5,0,Math.PI*2),d.fillStyle=ee?O:Y,d.fill(),ee&&(d.beginPath(),d.arc(A[J].x,A[J].y,c*1.2,0,Math.PI*2),d.strokeStyle=O,d.lineWidth=1.5,d.globalAlpha=.3,d.stroke(),d.globalAlpha=1)}if(n&&l.length>1){d.beginPath(),d.moveTo(A[l[0]].x,A[l[0]].y);for(let J=1;J<l.length;J++)d.lineTo(A[l[J]].x,A[l[J]].y);u&&$&&d.lineTo($.x,$.y),d.strokeStyle=O,d.lineWidth=3,d.lineCap="round",d.lineJoin="round",d.globalAlpha=.5,d.stroke(),d.globalAlpha=1}else n&&l.length===1&&u&&$&&(d.beginPath(),d.moveTo(A[l[0]].x,A[l[0]].y),d.lineTo($.x,$.y),d.strokeStyle=Q(i??"var(--security-biometric)",P),d.lineWidth=3,d.globalAlpha=.4,d.stroke(),d.globalAlpha=1)},[_,W,c,l,u,$,D,n,o,i]);h.useEffect(()=>{F()},[F]);const R=h.useCallback(d=>{if(D==="success"||D==="failure")return;d.preventDefault();const{x:A,y:N}=Z(d),P=M(A,N);P>=0&&(f(!0),S([P]),L({x:A,y:N}))},[D,Z,M]),T=h.useCallback(d=>{if(!u)return;d.preventDefault();const{x:A,y:N}=Z(d);L({x:A,y:N});const P=M(A,N);P>=0&&!l.includes(P)&&S(O=>[...O,P])},[u,Z,M,l]),v=h.useCallback(async()=>{if(!u)return;if(f(!1),L(null),l.length<r){S([]);return}const d=l.join(",");if(p==="set"){if(H===null){G([...l]),S([]);return}if(H.join(",")!==d){G(null),U("failure"),setTimeout(()=>{U("idle"),S([])},800);return}w==null||w([...l]),U("success");return}U("processing");let A=!1;if(b){const N=new TextEncoder,P=await crypto.subtle.digest("SHA-256",N.encode(d));A=Array.from(new Uint8Array(P)).map(Y=>Y.toString(16).padStart(2,"0")).join("")===b}else if(y)A=d===y;else{w==null||w([...l]),U("success");return}if(A)U("success"),j==null||j({success:!0,confidence:1,method:"pattern",timestamp:Date.now(),duration:0}),w==null||w([...l]);else{const N=K+1;B(N),U("failure"),N>=a&&(C==null||C(new Error("Too many failed pattern attempts"))),setTimeout(()=>{U("idle"),S([])},900),j==null||j({success:!1,confidence:0,method:"pattern",timestamp:Date.now(),duration:0})}},[u,l,r,p,H,b,y,K,a,U,w,j,C]);return s.jsxs("div",{className:g,style:{display:"inline-flex",flexDirection:"column",alignItems:"center",gap:12,fontFamily:"var(--security-font)",color:"var(--security-text)"},children:[z&&s.jsx("div",{style:{fontSize:14,fontWeight:600},children:z}),s.jsx("div",{style:{fontSize:13,color:"var(--security-text-secondary)",minHeight:18,textAlign:"center"},children:D==="success"?k("security.pattern.success","Pattern accepted"):D==="failure"?k("security.pattern.wrong","Wrong pattern"):p==="set"&&H!==null?k("security.pattern.confirm","Draw pattern again to confirm"):p==="set"?k("security.pattern.setNew","Draw a new pattern"):k("security.pattern.draw","Draw your pattern")}),s.jsx("canvas",{ref:x,width:_,height:_,style:{touchAction:"none",borderRadius:"var(--security-radius-lg)",background:"var(--security-bg-panel)",border:`1px solid ${D==="failure"?"var(--security-error)":"var(--security-border)"}`,cursor:"pointer",transition:"border-color 0.3s"},onMouseDown:R,onMouseMove:T,onMouseUp:v,onMouseLeave:v,onTouchStart:R,onTouchMove:T,onTouchEnd:v}),(D==="failure"||D==="success")&&s.jsx("button",{onClick:()=>{S([]),B(0),G(null),U("idle")},style:{fontSize:13,padding:"6px 16px",background:"var(--security-bg-panel)",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",color:"var(--security-text)",cursor:"pointer"},children:k("security.common.retry","Try Again")}),K>0&&D!=="success"&&s.jsx("div",{style:{fontSize:11,color:"var(--security-warning)"},children:k("security.pattern.attempts","{attempts}/{max} attempts").replace("{attempts}",String(K)).replace("{max}",String(a))})]})},mt={sm:"8px 16px",md:"12px 24px",lg:"14px 32px"},vt={sm:13,md:14,lg:16},xt=e=>{const{mode:t,credentialIds:r=[],challenge:n,rpName:o=window.location.hostname,rpId:a=window.location.hostname,user:c,attestation:i,authenticatorAttachment:p,residentKey:b,userVerification:y,timeout:w,onRegister:j,onAuthenticate:m,onVerify:C,onStatusChange:z,onError:g,label:I,className:k,variant:x="primary",size:l="md",fullWidth:S=!1,icon:u}=e,{t:f}=X(),[D,q]=h.useState("idle"),[K,B]=h.useState(!0),[H,G]=h.useState(!1),$=h.useCallback(R=>{q(R),z==null||z(R)},[z]);h.useEffect(()=>{B(ge()),Le().then(G)},[]);const L=h.useCallback(()=>{if(n){const R=atob(n.replace(/-/g,"+").replace(/_/g,"/")),T=new Uint8Array(R.length);for(let v=0;v<R.length;v++)T[v]=R.charCodeAt(v);return T.buffer}return crypto.getRandomValues(new Uint8Array(32)).buffer},[n]),_=h.useCallback(async()=>{if(!K){g==null||g(new Error("WebAuthn not available"));return}$("processing");try{if(t==="register"){const R=(c==null?void 0:c.id)??crypto.getRandomValues(new Uint8Array(16)),T=(c==null?void 0:c.name)??"user",v=(c==null?void 0:c.displayName)??T,d=L(),A=await $e({rpName:o,rpId:a,userId:typeof R=="string"?R:Array.from(R).join(""),userName:T,userDisplayName:v,challenge:d,timeout:w,attestation:i,authenticatorAttachment:p,residentKey:b,userVerification:y});$("success"),A&&(j==null||j(A)),C==null||C({success:!0,confidence:1,method:"webauthn",timestamp:Date.now(),duration:0})}else{const R=await _e({rpId:a,challenge:L(),allowCredentials:r==null?void 0:r.map(T=>({id:new TextEncoder().encode(T),type:"public-key"})),timeout:w,userVerification:y});$("success"),R&&(m==null||m(R)),C==null||C({success:!0,confidence:1,method:"webauthn",timestamp:Date.now(),duration:0})}}catch(R){const T=R instanceof Error?R:new Error(String(R));T.name==="NotAllowedError"?$("idle"):($("error"),g==null||g(T),C==null||C({success:!1,confidence:0,method:"webauthn",timestamp:Date.now(),duration:0}))}},[K,t,r,c,o,a,i,p,b,y,w,L,$,j,m,C,g]),E=t==="register"?H?f("security.webauthn.registerPasskey","Register Passkey"):f("security.webauthn.register","Register Security Key"):H?f("security.webauthn.signInPasskey","Sign in with Passkey"):f("security.webauthn.signIn","Sign in with Security Key"),U=I??E,W={primary:"var(--security-biometric)",outline:"transparent",ghost:"transparent"},Z={primary:"none",outline:"2px solid var(--security-biometric)",ghost:"none"},M={primary:"var(--nice-color-white, #fff)",outline:"var(--security-biometric)",ghost:"var(--security-biometric)"},F=!K||D==="processing"||D==="success";return s.jsxs("div",{className:k,style:{display:S?"block":"inline-block",textAlign:"center"},children:[s.jsxs("button",{onClick:_,disabled:F,style:{width:S?"100%":"auto",padding:mt[l],fontSize:vt[l],fontWeight:600,fontFamily:"var(--security-font)",background:W[x],color:M[x],border:Z[x],borderRadius:"var(--security-radius)",cursor:F?"not-allowed":"pointer",opacity:F?.6:1,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:8,transition:"opacity 0.2s, transform 0.1s"},children:[D==="processing"&&s.jsx("span",{style:{display:"inline-block",width:16,height:16,borderRadius:"50%",border:"2px solid transparent",borderTopColor:"currentColor",animation:"spin 0.6s linear infinite"}}),D==="success"&&s.jsx("span",{"aria-hidden":"true",style:{display:"inline-block",width:"0.3em",height:"0.6em",marginBottom:"0.15em",borderRight:"0.12em solid currentColor",borderBottom:"0.12em solid currentColor",transform:"rotate(45deg)"}}),u&&D!=="processing"&&D!=="success"&&u,U]}),!K&&s.jsx("div",{style:{fontSize:11,marginTop:6,color:"var(--security-warning)"},children:f("security.webauthn.notAvailable","WebAuthn is not supported in this browser")}),D==="error"&&s.jsx("div",{style:{fontSize:11,marginTop:6,color:"var(--security-error)"},children:f("security.webauthn.error","Authentication failed — try again")}),s.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]})},bt=[],wt=e=>e>=80?"var(--security-error)":e>=50?"var(--security-warning)":"var(--security-success)",St=({entries:e=bt,pageSize:t=20,showExport:r=!0,filterMethods:n,onEntryClick:o,className:a,label:c})=>{const{t:i}=X(),[p,b]=h.useState("all"),[y,w]=h.useState("all"),[j,m]=h.useState(0),C=h.useMemo(()=>{let u=[...e];return p!=="all"&&(u=u.filter(f=>f.method===p)),y!=="all"&&(u=u.filter(f=>f.status===y)),u.sort((f,D)=>D.timestamp-f.timestamp),u},[e,p,y]),z=Math.max(1,Math.ceil(C.length/t)),g=C.slice(j*t,(j+1)*t),I=h.useMemo(()=>n||Array.from(new Set(e.map(u=>u.method))),[e,n]),k=h.useMemo(()=>Array.from(new Set(e.map(u=>u.status))),[e]),x=h.useCallback(()=>{const u=new Blob([JSON.stringify(C,null,2)],{type:"application/json"}),f=URL.createObjectURL(u),D=document.createElement("a");D.href=f,D.download=`security-audit-${new Date().toISOString().slice(0,10)}.json`,D.click(),URL.revokeObjectURL(f)},[C]),l=u=>new Date(u).toLocaleString(),S={padding:"8px 12px",borderBottom:"1px solid var(--security-border)",fontSize:13,whiteSpace:"nowrap"};return s.jsxs("div",{className:a,style:{fontFamily:"var(--security-font)",color:"var(--security-text)",background:"var(--security-bg)",borderRadius:"var(--security-radius-lg)",border:"1px solid var(--security-border)",overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",background:"var(--security-bg-panel)",borderBottom:"1px solid var(--security-border)"},children:[s.jsx("div",{style:{fontWeight:600,fontSize:15},children:c??i("security.audit.title","Security Audit Log")}),s.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[s.jsxs("select",{value:p,onChange:u=>{b(u.target.value),m(0)},style:we,children:[s.jsx("option",{value:"all",children:i("security.audit.allMethods","All methods")}),I.map(u=>s.jsx("option",{value:u,children:u},u))]}),s.jsxs("select",{value:y,onChange:u=>{w(u.target.value),m(0)},style:we,children:[s.jsx("option",{value:"all",children:i("security.audit.allStatuses","All statuses")}),k.map(u=>s.jsx("option",{value:u,children:u},u))]}),r&&s.jsx("button",{onClick:x,style:kt,title:i("security.audit.exportJson","Export JSON"),children:i("security.json","JSON")})]})]}),s.jsx("div",{style:{overflowX:"auto"},children:s.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[s.jsx("thead",{children:s.jsxs("tr",{style:{background:"var(--security-bg-panel)",fontSize:12,color:"var(--security-text-secondary)",textTransform:"uppercase",letterSpacing:.5},children:[s.jsx("th",{style:{...S,textAlign:"left"},children:i("security.audit.time","Time")}),s.jsx("th",{style:{...S,textAlign:"left"},children:i("security.audit.action","Action")}),s.jsx("th",{style:{...S,textAlign:"center"},children:i("security.audit.method","Method")}),s.jsx("th",{style:{...S,textAlign:"center"},children:i("security.audit.status","Status")}),s.jsx("th",{style:{...S,textAlign:"center"},children:i("security.audit.risk","Risk")}),s.jsx("th",{style:{...S,textAlign:"left"},children:i("security.audit.device","Device")})]})}),s.jsxs("tbody",{children:[g.length===0&&s.jsx("tr",{children:s.jsx("td",{colSpan:6,style:{...S,textAlign:"center",color:"var(--security-text-muted)",padding:24},children:i("security.audit.noEntries","No entries to show")})}),g.map(u=>s.jsxs("tr",{onClick:()=>o==null?void 0:o(u),style:{cursor:o?"pointer":"default"},onMouseEnter:f=>{f.currentTarget.style.background="var(--security-bg-panel)"},onMouseLeave:f=>{f.currentTarget.style.background=""},children:[s.jsx("td",{style:S,children:l(u.timestamp)}),s.jsx("td",{style:S,children:u.action}),s.jsx("td",{style:{...S,textAlign:"center"},children:s.jsx("span",{style:{padding:"2px 8px",borderRadius:12,fontSize:11,fontWeight:600,background:"var(--security-bg-panel)",border:"1px solid var(--security-border)"},children:u.method})}),s.jsx("td",{style:{...S,textAlign:"center"},children:u.status}),s.jsx("td",{style:{...S,textAlign:"center"},children:u.riskScore!=null&&s.jsx("span",{style:{color:wt(u.riskScore),fontWeight:600},children:u.riskScore})}),s.jsx("td",{style:{...S,maxWidth:200,overflow:"hidden",textOverflow:"ellipsis"},children:u.device??"—"})]},u.id))]})]})}),z>1&&s.jsxs("div",{style:{display:"flex",justifyContent:"center",alignItems:"center",gap:12,padding:"10px 16px",fontSize:13,color:"var(--security-text-secondary)",borderTop:"1px solid var(--security-border)"},children:[s.jsxs("button",{disabled:j===0,onClick:()=>m(j-1),style:Se,children:[s.jsx(de.NtdArrowLeft,{size:14,style:{verticalAlign:"-2px"}})," ",i("security.audit.prev","Prev")]}),s.jsxs("span",{children:[j+1," / ",z]}),s.jsxs("button",{disabled:j>=z-1,onClick:()=>m(j+1),style:Se,children:[i("security.audit.next","Next")," ",s.jsx(de.NtdArrowRight,{size:14,style:{verticalAlign:"-2px"}})]})]}),s.jsx("div",{style:{padding:"6px 16px",fontSize:11,color:"var(--security-text-muted)",textAlign:"right"},children:i("security.audit.total","{count} entries").replace("{count}",String(C.length))})]})},we={fontSize:12,padding:"4px 8px",background:"var(--security-bg)",color:"var(--security-text)",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)"},kt={background:"none",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",padding:"4px 8px",cursor:"pointer",fontSize:16},Se={background:"none",border:"none",cursor:"pointer",color:"var(--security-biometric)",fontWeight:600,fontSize:13},At=[],ke={display:"inline-block",width:"0.3em",height:"0.6em",margin:"0 0.35em 0.15em 0.1em",borderRight:"0.12em solid currentColor",borderBottom:"0.12em solid currentColor",transform:"rotate(45deg)"},jt=({options:e=At,requiredCount:t=1,onSelect:r,onComplete:n,className:o,label:a,layout:c="grid"})=>{const{t:i}=X(),p=e.filter(y=>y.verified).length,b=p>=t;return s.jsxs("div",{className:o,style:{fontFamily:"var(--security-font)",color:"var(--security-text)",display:"flex",flexDirection:"column",gap:16},children:[a&&s.jsx("div",{style:{fontSize:15,fontWeight:600},children:a}),t>1&&s.jsx("div",{style:{fontSize:13,color:"var(--security-text-secondary)"},children:i("security.mfa.progress","Verified {verified} of {required} required").replace("{verified}",String(p)).replace("{required}",String(t))}),s.jsx("div",{style:{display:c==="grid"?"grid":"flex",gridTemplateColumns:c==="grid"?"repeat(auto-fill, minmax(140px, 1fr))":void 0,flexDirection:c==="list"?"column":void 0,gap:12},children:e.map(y=>{const w=y.verified??!1,j=y.disabled||b;return s.jsxs("button",{onClick:()=>!j&&!w&&(r==null?void 0:r(y.method)),disabled:j||w,style:{display:"flex",flexDirection:c==="grid"?"column":"row",alignItems:"center",gap:c==="grid"?8:12,padding:c==="grid"?"20px 16px":"12px 16px",background:w?"color-mix(in srgb, var(--nice-color-success, #10b981) 8%, transparent)":"var(--security-bg-panel)",border:`2px solid ${w?"var(--security-success)":"var(--security-border)"}`,borderRadius:"var(--security-radius-lg)",cursor:j||w?"default":"pointer",opacity:j&&!w?.5:1,transition:"border-color 0.2s, background 0.2s",textAlign:c==="grid"?"center":"left"},children:[s.jsx("span",{style:{fontSize:28},children:w?s.jsx("span",{"aria-label":"verified",style:{...ke,color:"var(--security-success)"}}):y.icon}),s.jsxs("div",{children:[s.jsx("div",{style:{fontSize:14,fontWeight:600,color:"var(--security-text)"},children:y.label??y.method}),y.description&&s.jsx("div",{style:{fontSize:11,color:"var(--security-text-muted)",marginTop:2},children:y.description})]})]},y.method)})}),b&&s.jsxs("div",{style:{textAlign:"center",fontSize:14,fontWeight:600,color:"var(--security-success)",padding:8},children:[s.jsx("span",{"aria-hidden":"true",style:ke}),i("security.mfa.complete","All factors verified")]})]})},Tt=[],Ct=({sessions:e=Tt,onRevoke:t,onRevokeAll:r,onTrust:n,className:o,label:a,showRevokeAll:c=!0})=>{const{t:i}=X(),[p,b]=h.useState(new Set),y=h.useMemo(()=>[...e].sort((m,C)=>(C.current?1:0)-(m.current?1:0)||C.lastActive-m.lastActive),[e]),w=m=>{const C=new Date(m),g=Date.now()-m;return g<6e4?i("security.session.justNow","Just now"):g<36e5?`${Math.floor(g/6e4)}m ago`:g<864e5?`${Math.floor(g/36e5)}h ago`:C.toLocaleDateString()},j=m=>{b(C=>new Set(C).add(m)),t==null||t(m)};return s.jsxs("div",{className:o,style:{fontFamily:"var(--security-font)",color:"var(--security-text)",background:"var(--security-bg)",borderRadius:"var(--security-radius-lg)",border:"1px solid var(--security-border)",overflow:"hidden"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",background:"var(--security-bg-panel)",borderBottom:"1px solid var(--security-border)"},children:[s.jsx("div",{style:{fontSize:15,fontWeight:600},children:a??i("security.session.title","Active Sessions")}),c&&e.length>1&&s.jsx("button",{onClick:r,style:{fontSize:12,padding:"4px 12px",background:"none",border:"1px solid var(--security-error)",borderRadius:"var(--security-radius)",color:"var(--security-error)",cursor:"pointer"},children:i("security.session.revokeAll","Revoke all others")})]}),s.jsxs("div",{children:[y.map(m=>s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid var(--security-border)",opacity:p.has(m.id)?.5:1,background:m.current?"color-mix(in srgb, var(--nice-color-primary, #3b82f6) 4%, transparent)":void 0},children:[s.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center"},children:[s.jsx("span",{style:{fontSize:10,fontWeight:600,textTransform:"uppercase",color:"var(--security-text-muted)",minWidth:48},children:m.device.toLowerCase().includes("mobile")?i("security.session.mobile","Mobile"):i("security.session.desktop","Desktop")}),s.jsxs("div",{children:[s.jsxs("div",{style:{fontSize:14,fontWeight:500},children:[m.device,m.current&&s.jsx("span",{style:{marginLeft:8,fontSize:10,padding:"1px 6px",background:"var(--security-biometric)",color:"var(--nice-color-white, #fff)",borderRadius:8},children:i("security.session.current","Current")}),m.trusted&&s.jsx("span",{style:{marginLeft:6,fontSize:10,padding:"1px 6px",background:"var(--nice-success-bg, #ecfdf5)",color:"var(--nice-success-text, #065f46)",borderRadius:8},children:i("security.session.trusted","Trusted")})]}),s.jsx("div",{style:{fontSize:12,color:"var(--security-text-muted)",marginTop:2},children:[m.browser,m.os,m.location].filter(Boolean).join(" · ")}),s.jsxs("div",{style:{fontSize:11,color:"var(--security-text-muted)",marginTop:1},children:[i("security.session.lastActive","Last active"),":"," ",w(m.lastActive)]})]})]}),s.jsxs("div",{style:{display:"flex",gap:6},children:[n&&!m.current&&s.jsx("button",{onClick:()=>n(m.id,!m.trusted),style:{fontSize:11,padding:"4px 8px",background:"none",border:"1px solid var(--security-border)",borderRadius:"var(--security-radius)",cursor:"pointer",color:"var(--security-text-secondary)"},children:m.trusted?i("security.session.untrust","Untrust"):i("security.session.trust","Trust")}),!m.current&&s.jsx("button",{onClick:()=>j(m.id),disabled:p.has(m.id),style:{fontSize:11,padding:"4px 10px",background:"none",border:"1px solid var(--security-error)",borderRadius:"var(--security-radius)",cursor:"pointer",color:"var(--security-error)"},children:i("security.session.revoke","Revoke")})]})]},m.id)),e.length===0&&s.jsx("div",{style:{padding:24,textAlign:"center",color:"var(--security-text-muted)",fontSize:13},children:i("security.session.noSessions","No active sessions")})]})]})},It=({trustScore:e,onScoreComputed:t,trustThreshold:r=60,showFactors:n=!0,showFingerprint:o=!1,className:a,label:c})=>{const{t:i}=X(),[p,b]=h.useState(e??null),[y,w]=h.useState(!e),j=h.useRef(t);j.current=t;const m=h.useCallback(async()=>{var z,g;w(!0);try{const I=pe(),k=await ie(),x=[];let l=50;I.platform&&!I.platform.includes("Linux")&&(x.push({name:i("security.trust.knownPlatform","Known platform"),score:5,description:i("security.trust.knownPlatformHint","Running on a recognized platform"),weight:.05}),l+=5),navigator.cookieEnabled&&(x.push({name:i("security.trust.cookiesEnabled","Cookies enabled"),score:5,description:i("security.trust.cookiesEnabledHint","Browser cookies are enabled"),weight:.05}),l+=5),I.screenResolution[0]>=360&&I.screenResolution[1]>=640&&(x.push({name:i("security.trust.standardResolution","Standard resolution"),score:5,description:i("security.trust.standardResolutionHint","Screen resolution within normal range"),weight:.05}),l+=5),typeof window<"u"&&window.isSecureContext&&(x.push({name:i("security.trust.secureContext","Secure context"),score:10,description:i("security.trust.secureContextHint","Running in HTTPS secure context"),weight:.1}),l+=10),((z=navigator.languages)==null?void 0:z.length)>0&&(x.push({name:i("security.trust.languageConfigured","Language configured"),score:5,description:i("security.trust.languageConfiguredHint","Browser language is set"),weight:.05}),l+=5),I.touchSupport&&(x.push({name:i("security.trust.touchDevice","Touch device"),score:5,description:i("security.trust.touchDeviceHint","Touch input is supported"),weight:.05}),l+=5);try{const D=document.createElement("canvas").getContext("webgl");D&&D.getExtension("WEBGL_debug_renderer_info")&&(x.push({name:i("security.trust.hardwareGpu","Hardware GPU"),score:10,description:i("security.trust.hardwareGpuHint","Hardware GPU detected"),weight:.1}),l+=10)}catch{}navigator.credentials&&(x.push({name:i("security.trust.credentialApi","Credential API"),score:5,description:i("security.trust.credentialApiHint","Credential Management API available"),weight:.05}),l+=5),l=Math.min(100,Math.max(0,l));const S=Date.now(),u={score:l,factors:x,trusted:l>=r,firstSeen:S,lastSeen:S,fingerprint:k};b(u),(g=j.current)==null||g.call(j,u)}finally{w(!1)}},[r,i]);h.useEffect(()=>{e||m()},[e,m]),h.useEffect(()=>{e&&b(e)},[e]);const C=p?p.score>=80?"var(--security-success)":p.score>=50?"var(--security-warning)":"var(--security-error)":"var(--security-text-muted)";return s.jsxs("div",{className:a,style:{fontFamily:"var(--security-font)",color:"var(--security-text)",background:"var(--security-bg-panel)",borderRadius:"var(--security-radius-lg)",border:"1px solid var(--security-border)",padding:20,display:"flex",flexDirection:"column",gap:14,alignItems:"center"},children:[s.jsx("div",{style:{fontSize:15,fontWeight:600},children:c??i("security.trust.title","Device Trust")}),y?s.jsx("div",{style:{fontSize:13,color:"var(--security-text-muted)"},children:i("security.trust.computing","Analysing device…")}):p?s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{position:"relative",width:100,height:100},children:[s.jsxs("svg",{viewBox:"0 0 36 36",style:{width:"100%",height:"100%",transform:"rotate(-90deg)"},children:[s.jsx("circle",{cx:"18",cy:"18",r:"15.9",fill:"none",stroke:"var(--security-border)",strokeWidth:"2.5"}),s.jsx("circle",{cx:"18",cy:"18",r:"15.9",fill:"none",stroke:C,strokeWidth:"2.5",strokeDasharray:`${p.score}, 100`,strokeLinecap:"round"})]}),s.jsxs("div",{style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:[s.jsx("span",{style:{fontSize:24,fontWeight:700,color:C},children:p.score}),s.jsx("span",{style:{fontSize:10,color:"var(--security-text-muted)"},children:"/100"})]})]}),s.jsx("div",{style:{fontSize:14,fontWeight:600,color:p.trusted?"var(--security-success)":"var(--security-warning)"},children:p.trusted?i("security.trust.trusted","Device Trusted"):i("security.trust.untrusted","Low Trust Score")}),n&&p.factors.length>0&&s.jsxs("div",{style:{width:"100%",fontSize:12},children:[s.jsxs("div",{style:{fontWeight:600,marginBottom:6,color:"var(--security-text-secondary)"},children:[i("security.trust.factors","Contributing factors"),":"]}),s.jsx("ul",{style:{margin:0,paddingLeft:18,color:"var(--security-text-muted)"},children:p.factors.map((z,g)=>s.jsx("li",{style:{marginBottom:2},children:z.name},g))})]}),o&&p.fingerprint&&s.jsx("div",{style:{fontSize:10,color:"var(--security-text-muted)",wordBreak:"break-all",textAlign:"center",maxWidth:280,fontFamily:"monospace"},children:p.fingerprint})]}):null]})};function Rt(e){if(!e)return 0;let t=0;return e.length>=8&&t++,e.length>=12&&t++,/[a-z]/.test(e)&&/[A-Z]/.test(e)&&t++,/\d/.test(e)&&t++,/[^a-zA-Z0-9]/.test(e)&&t++,/(.)\1{3,}/.test(e)&&t--,Math.max(0,Math.min(4,t))}const Dt=["Very weak","Weak","Fair","Strong","Very strong"],Ae=["var(--nice-danger, #ef4444)","var(--nice-warning, #f97316)","var(--nice-warning, #eab308)","var(--nice-success, #22c55e)","var(--nice-success, #10b981)"],Pt=({mode:e="verify",expectedHash:t,minStrength:r=2,minLength:n=8,onComplete:o,onVerify:a,onStatusChange:c,onError:i,label:p,placeholder:b,className:y,showStrength:w=!0,maxAttempts:j=5})=>{const{t:m}=X(),[C,z]=h.useState(""),[g,I]=h.useState(""),[k,x]=h.useState(!1),[l,S]=h.useState("idle"),[u,f]=h.useState(0),[D,q]=h.useState(""),K=h.useRef(null),B=Rt(C),H=h.useCallback(L=>{S(L),c==null||c(L)},[c]),G=h.useCallback(async()=>{if(q(""),H("processing"),e==="set"){if(C.length<n){q(m("security.passphrase.tooShort","Minimum {min} characters").replace("{min}",String(n))),H("idle");return}if(B<r){q(m("security.passphrase.tooWeak","Passphrase is too weak")),H("idle");return}if(C!==g){q(m("security.passphrase.noMatch","Passphrases do not match")),H("failure"),setTimeout(()=>H("idle"),1e3);return}o==null||o(C),H("success");return}if(t){const L=new TextEncoder,_=await crypto.subtle.digest("SHA-256",L.encode(C));if(Array.from(new Uint8Array(_)).map(W=>W.toString(16).padStart(2,"0")).join("")===t)H("success"),a==null||a({success:!0,confidence:1,method:"passphrase",timestamp:Date.now(),duration:0}),o==null||o(C);else{const W=u+1;f(W),W>=j?(H("failure"),i==null||i(new Error("Too many failed attempts"))):(q(m("security.passphrase.incorrect","Incorrect passphrase")),H("idle")),a==null||a({success:!1,confidence:0,method:"passphrase",timestamp:Date.now(),duration:0})}}else o==null||o(C),H("success")},[C,g,e,t,B,r,n,u,j,m,H,o,a,i]),$={width:"100%",padding:"10px 14px",fontSize:14,background:"var(--security-bg)",color:"var(--security-text)",border:`1px solid ${l==="failure"?"var(--security-error)":"var(--security-border)"}`,borderRadius:"var(--security-radius)",boxSizing:"border-box",fontFamily:"var(--security-font)"};return s.jsxs("div",{className:y,style:{display:"flex",flexDirection:"column",gap:10,maxWidth:340,fontFamily:"var(--security-font)",color:"var(--security-text)"},children:[p&&s.jsx("label",{style:{fontSize:14,fontWeight:600},children:p}),s.jsxs("div",{style:{position:"relative"},children:[s.jsx("input",{ref:K,type:k?"text":"password",value:C,onChange:L=>z(L.target.value),placeholder:b??m("security.passphrase.placeholder","Enter passphrase"),style:$,disabled:l==="success",onKeyDown:L=>L.key==="Enter"&&G()}),s.jsx("button",{type:"button",onClick:()=>x(!k),style:{position:"absolute",right:8,top:"50%",transform:"translateY(-50%)",background:"none",border:"none",cursor:"pointer",fontSize:16,color:"var(--security-text-muted)"},tabIndex:-1,children:k?m("security.passphrase.hide","Hide"):m("security.passphrase.show","Show")})]}),e==="set"&&w&&C.length>0&&s.jsxs("div",{children:[s.jsx("div",{style:{display:"flex",gap:3,height:4},children:[0,1,2,3].map(L=>s.jsx("div",{style:{flex:1,borderRadius:2,background:L<B?Ae[B]:"var(--security-border)",transition:"background 0.2s"}},L))}),s.jsx("div",{style:{fontSize:11,marginTop:4,color:Ae[B]},children:m(`security.passphrase.strength${B}`,Dt[B])})]}),e==="set"&&s.jsx("input",{type:k?"text":"password",value:g,onChange:L=>I(L.target.value),placeholder:m("security.passphrase.confirmPlaceholder","Confirm passphrase"),style:$,disabled:l==="success",onKeyDown:L=>L.key==="Enter"&&G(),onPaste:L=>L.preventDefault()}),D&&s.jsx("div",{style:{fontSize:12,color:"var(--security-error)"},children:D}),s.jsx("button",{onClick:G,disabled:!C||l==="processing"||l==="success",style:{padding:"10px 20px",fontSize:14,fontWeight:600,background:l==="success"?"var(--security-success)":"var(--security-biometric)",color:"var(--nice-color-white, #fff)",border:"none",borderRadius:"var(--security-radius)",cursor:l==="success"?"default":"pointer",opacity:!C||l==="processing"?.6:1},children:l==="success"?m("security.passphrase.accepted","Accepted"):e==="set"?m("security.passphrase.setBtn","Set Passphrase"):m("security.passphrase.verifyBtn","Verify")}),u>0&&l!=="success"&&s.jsx("div",{style:{fontSize:11,color:"var(--security-warning)"},children:m("security.passphrase.attempts","{attempts}/{max} attempts").replace("{attempts}",String(u)).replace("{max}",String(j))})]})};function Mt(e){const t=[],r={defaultSrc:"default-src",scriptSrc:"script-src",styleSrc:"style-src",imgSrc:"img-src",fontSrc:"font-src",connectSrc:"connect-src",frameSrc:"frame-src",objectSrc:"object-src",mediaSrc:"media-src",workerSrc:"worker-src",childSrc:"child-src",formAction:"form-action",frameAncestors:"frame-ancestors",baseUri:"base-uri",reportUri:"report-uri",reportTo:"report-to",upgradeInsecureRequests:"upgrade-insecure-requests",blockAllMixedContent:"block-all-mixed-content"};return Object.entries(e.directives).forEach(([n,o])=>{const a=r[n];if(a){if(typeof o=="boolean")o&&t.push(a);else if(typeof o=="string")t.push(`${a} ${o}`);else if(Array.isArray(o)){let c=o;e.nonce&&(n==="scriptSrc"||n==="styleSrc")&&(c=[...c,`'nonce-${e.nonce}'`]),t.push(`${a} ${c.join(" ")}`)}}}),t.join("; ")}function Et(e){const t="'self'";return{defaultSrc:[t],scriptSrc:[t],styleSrc:[t,"'unsafe-inline'"],imgSrc:[t,"data:","blob:",e==null?void 0:e.cdnDomain].filter(Boolean),fontSrc:[t,"data:",e==null?void 0:e.cdnDomain].filter(Boolean),connectSrc:[t,e==null?void 0:e.apiDomain,"wss:"].filter(Boolean),frameSrc:["'none'"],objectSrc:["'none'"],baseUri:[t],formAction:[t],frameAncestors:["'none'"],upgradeInsecureRequests:!0,reportUri:e==null?void 0:e.reportUri}}function Ft(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID().replace(/-/g,""):Math.random().toString(36).substring(2)+Date.now().toString(36)}const Nt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"};function We(e){return e.replace(/[&<>"'`=/]/g,t=>Nt[t]||t)}function zt(e,t){let r=We(e);return t!=null&&t.maxLength&&r.length>t.maxLength&&(r=r.substring(0,t.maxLength)),r}function Lt(e){if(!e)return null;try{const t=new URL(e);return!["http:","https:","mailto:","tel:"].includes(t.protocol)||e.toLowerCase().includes("javascript:")?null:t.toString()}catch{return null}}function $t(e){const t=["script","iframe","object","embed","form"];let r=e;t.forEach(a=>{const c=new RegExp(`<${a}[^>]*>.*?</${a}>`,"gi");r=r.replace(c,"");const i=new RegExp(`<${a}[^>]*/>`,"gi");r=r.replace(i,"")});const n=/\s+on\w+\s*=/gi;r=r.replace(n," data-removed=");const o=/javascript:/gi;return r=r.replace(o,""),r}function _t(e,t){let r=e;if(t!=null&&t.allowedTags){const n=/<\/?([a-z][a-z0-9]*)[^>]*>/gi;r=r.replace(n,(o,a)=>t.allowedTags.includes(a.toLowerCase())?o:"")}return r=r.replace(/\s+on\w+\s*=/gi," data-removed="),r=r.replace(/javascript:/gi,""),{__html:r}}const me={headerName:"X-CSRF-Token",cookieName:"XSRF-TOKEN",fieldName:"_csrf"};function Bt(){if(typeof crypto<"u"){const e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}return Math.random().toString(36).substring(2)+Date.now().toString(36)}function ve(e=me.cookieName){if(typeof document>"u")return null;const t=document.cookie.match(new RegExp(`(^| )${e}=([^;]+)`));return t?decodeURIComponent(t[2]):null}function Wt(e=me){return async function(r,n={}){const o=ve(e.cookieName);o||console.warn("CSRF token not found");const a=new Headers(n.headers);return o&&e.headerName&&a.set(e.headerName,o),fetch(r,{...n,headers:a})}}function Ht(e=me){const t=ve(e.cookieName);return{token:t,inputProps:{type:"hidden",name:e.fieldName,value:t||""},headerName:e.headerName}}function He(e){const t=new Map,r=e.keyGenerator||(a=>a.url);function n(a){const c=r(a),i=Date.now();let p=t.get(c);(!p||i>p.resetAt)&&(p={count:0,resetAt:i+e.windowMs}),p.count++,t.set(c,p);const b=p.count<=e.maxRequests,y=Math.max(0,e.maxRequests-p.count);return{allowed:b,remaining:y,resetAt:p.resetAt}}function o(a){a?t.delete(a):t.clear()}return{checkLimit:n,reset:o}}function Ot(e){const t=He(e);return{checkAndFetch:async(n,o)=>{const a=t.checkLimit({url:n,method:o==null?void 0:o.method});if(!a.allowed){const c=Math.ceil((a.resetAt-Date.now())/1e3);throw new Error(`Rate limit exceeded. Retry after ${c} seconds.`)}return fetch(n,o)},checkLimit:t.checkLimit,reset:t.reset}}function Oe(e,t){const r=[];if(t.allowedTypes&&t.allowedTypes.length>0&&(t.allowedTypes.includes(e.type)||r.push(`File type '${e.type}' is not allowed. Allowed types: ${t.allowedTypes.join(", ")}`)),t.maxSize&&e.size>t.maxSize){const a=(t.maxSize/1048576).toFixed(2),c=(e.size/(1024*1024)).toFixed(2);r.push(`File size (${c}MB) exceeds maximum allowed size (${a}MB)`)}const n=[".exe",".bat",".cmd",".sh",".ps1",".vbs",".js",".jar"],o=e.name.toLowerCase();for(const a of n)if(o.includes(a+".")||o.endsWith(a)){r.push(`File extension '${a}' is not allowed`);break}return{valid:r.length===0,errors:r,file:r.length===0?e:void 0}}function Ut(e,t){const r=[],n=[],o=[];t.maxFiles&&e.length>t.maxFiles&&r.push(`Too many files. Maximum allowed: ${t.maxFiles}`);const a=e.reduce((c,i)=>c+i.size,0);if(t.maxTotalSize&&a>t.maxTotalSize){const c=(t.maxTotalSize/1048576).toFixed(2),i=(a/(1024*1024)).toFixed(2);r.push(`Total file size (${i}MB) exceeds maximum (${c}MB)`)}return e.forEach(c=>{const i=Oe(c,t);i.valid?n.push(c):o.push({file:c,errors:i.errors})}),{valid:r.length===0&&o.length===0,errors:[...r,...o.flatMap(c=>c.errors)],validFiles:n,invalidFiles:o}}async function qt(e,t){const r=new FormData;r.append("file",e);try{const n=await fetch(t,{method:"POST",body:r});if(!n.ok)throw new Error("Virus scan failed");return await n.json()}catch(n){return console.error("Virus scan error:",n),{clean:!1,threat:"Scan failed"}}}function Ue(){if(typeof localStorage>"u")return null;const e=localStorage.getItem("nice2dev_consent");if(!e)return null;try{return JSON.parse(e)}catch{return null}}function Kt(e){typeof localStorage>"u"||localStorage.setItem("nice2dev_consent",JSON.stringify({...e,necessary:!0,timestamp:new Date().toISOString()}))}function Gt(e){const t=Ue();return t?t[e]===!0:!1}function Yt(e){if(typeof document>"u")return;document.cookie.split(";").forEach(r=>{const[n]=r.trim().split("=");e.includes(n)||(document.cookie=`${n}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`)})}async function Jt(e,t,r=fetch){const n={exportDate:new Date().toISOString(),userId:e};return await Promise.all(Object.entries(t).map(async([o,a])=>{try{const c=await r(a);c.ok&&(n[o]=await c.json())}catch(c){console.error(`Failed to fetch ${o} data:`,c),n[o]={error:"Failed to retrieve data"}}})),n}async function Zt(e,t,r=fetch){try{const n=await r(t,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:e,timestamp:new Date().toISOString()})});return n.ok?{success:!0,confirmationId:(await n.json()).confirmationId}:{success:!1,error:"Deletion request failed"}}catch(n){return{success:!1,error:String(n)}}}function Vt(e,t){var n;const r={...e,id:((n=crypto.randomUUID)==null?void 0:n.call(crypto))||Math.random().toString(36),timestamp:new Date};return t&&fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}).catch(console.error),process.env.NODE_ENV==="development"&&console.warn("[HIPAA] PHI Access:",r),r}function Xt(e){let t=null,r=null,n=Date.now();const o=e.timeoutMinutes*60*1e3,a=e.warningBeforeMs||6e4;function c(){n=Date.now(),t&&clearTimeout(t),r&&clearTimeout(r),e.onWarning&&(r=setTimeout(()=>{var y;const b=o-(Date.now()-n);(y=e.onWarning)==null||y.call(e,b)},o-a)),t=setTimeout(e.onTimeout,o)}function i(){t&&clearTimeout(t),r&&clearTimeout(r)}function p(){return Math.max(0,o-(Date.now()-n))}return c(),typeof window<"u"&&["mousedown","keypress","touchstart","scroll"].forEach(y=>{window.addEventListener(y,c,{passive:!0})}),{resetTimer:c,destroy:i,getTimeRemaining:p}}function Qt(e,t){const r=c=>{const i=c.replace("#",""),p=parseInt(i.substr(0,2),16)/255,b=parseInt(i.substr(2,2),16)/255,y=parseInt(i.substr(4,2),16)/255,w=j=>j<=.03928?j/12.92:Math.pow((j+.055)/1.055,2.4);return .2126*w(p)+.7152*w(b)+.0722*w(y)},n=r(e),o=r(t),a=(Math.max(n,o)+.05)/(Math.min(n,o)+.05);return{ratio:Math.round(a*100)/100,passesAA:a>=4.5,passesAAA:a>=7,passesAALarge:a>=3,passesAAALarge:a>=4.5}}function er(e){var r,n,o;if(e.getAttribute("aria-label"))return!0;const t=e.getAttribute("aria-labelledby");if(t){const a=document.getElementById(t);if((r=a==null?void 0:a.textContent)!=null&&r.trim())return!0}if(e.id){const a=document.querySelector(`label[for="${e.id}"]`);if((n=a==null?void 0:a.textContent)!=null&&n.trim())return!0}return!!((o=e.textContent)!=null&&o.trim()||e.getAttribute("title")||e.placeholder)}function tr(e){const r=(e||document.body).querySelectorAll("h1, h2, h3, h4, h5, h6"),n=[];let o=0,a=!1;return r.forEach(c=>{const i=parseInt(c.tagName[1]);i===1&&(a&&n.push({level:i,element:c,issue:"Multiple H1 elements found"}),a=!0),i>o+1&&o!==0&&n.push({level:i,element:c,issue:`Skipped heading level: H${o} to H${i}`}),o=i}),!a&&r.length>0&&n.push({level:0,element:r[0],issue:"Missing H1 element"}),{valid:n.length===0,issues:n}}function rr(e){const t=[];let r=null;const n=e.batchSize||10,o=e.flushInterval||5e3;async function a(){if(t.length===0)return;const b=t.splice(0,n);try{await fetch(e.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({entries:b})})}catch(y){console.error("Failed to send audit logs:",y),t.unshift(...b)}}function c(){r||(r=setTimeout(()=>{r=null,a()},o))}function i(b){var w;const y={...b,id:((w=crypto.randomUUID)==null?void 0:w.call(crypto))||Math.random().toString(36),timestamp:new Date,userAgent:e.includeUserAgent&&typeof navigator<"u"?navigator.userAgent:void 0};t.push(y),t.length>=n?a():c()}function p(){r&&clearTimeout(r),a()}return{log:i,flush:a,destroy:p}}function sr(){return[{controlId:"CC6.1",name:"Logical and Physical Access Controls",category:"security",status:"in_progress",lastAssessed:new Date},{controlId:"CC6.2",name:"User Registration and Authorization",category:"security",status:"in_progress",lastAssessed:new Date},{controlId:"CC6.3",name:"Access Control Removal",category:"security",status:"in_progress",lastAssessed:new Date},{controlId:"A1.1",name:"System Capacity",category:"availability",status:"in_progress",lastAssessed:new Date},{controlId:"A1.2",name:"Backup and Recovery",category:"availability",status:"in_progress",lastAssessed:new Date},{controlId:"C1.1",name:"Confidential Information Classification",category:"confidentiality",status:"in_progress",lastAssessed:new Date},{controlId:"C1.2",name:"Confidential Information Disposal",category:"confidentiality",status:"in_progress",lastAssessed:new Date},{controlId:"P1.1",name:"Privacy Notice",category:"privacy",status:"in_progress",lastAssessed:new Date},{controlId:"P2.1",name:"Consent",category:"privacy",status:"in_progress",lastAssessed:new Date},{controlId:"P3.1",name:"Collection",category:"privacy",status:"in_progress",lastAssessed:new Date}]}const nr={hardcodedSecrets:[{pattern:/password\s*[:=]\s*["'][^"']+["']/gi,name:"Hardcoded password"},{pattern:/api[_-]?key\s*[:=]\s*["'][^"']+["']/gi,name:"Hardcoded API key"},{pattern:/secret\s*[:=]\s*["'][^"']+["']/gi,name:"Hardcoded secret"},{pattern:/token\s*[:=]\s*["'][^"']+["']/gi,name:"Hardcoded token"}],sqlInjection:[{pattern:/execute\s*\(\s*["'`].*\$\{/gi,name:"Potential SQL injection (template literal)"},{pattern:/query\s*\(\s*["'`].*\+/gi,name:"Potential SQL injection (string concatenation)"}],xss:[{pattern:/dangerouslySetInnerHTML/g,name:"dangerouslySetInnerHTML usage"},{pattern:/innerHTML\s*=/g,name:"innerHTML assignment"},{pattern:/document\.write\s*\(/g,name:"document.write usage"},{pattern:/eval\s*\(/g,name:"eval usage"}],insecureFunctions:[{pattern:/Math\.random\s*\(\)/g,name:"Insecure random (use crypto)"},{pattern:/new Function\s*\(/g,name:"Function constructor (code injection risk)"},{pattern:/setTimeout\s*\(\s*["']/g,name:"setTimeout with string (code injection)"},{pattern:/setInterval\s*\(\s*["']/g,name:"setInterval with string (code injection)"}],infoExposure:[{pattern:/console\.(log|info|warn|error)\s*\(/g,name:"Console logging (remove in production)"},{pattern:/debugger/g,name:"Debugger statement"},{pattern:/TODO.*password/gi,name:"TODO mentioning password"}]};function ir(){return`# .github/workflows/sast.yml
7
7
  name: Security Scan (SAST)
8
8
 
9
9
  on:
@@ -289,4 +289,4 @@ We will not pursue legal action against researchers who:
289
289
  - Do not access, modify, or delete user data
290
290
  - Do not disrupt our services
291
291
  - Do not disclose vulnerabilities before they are fixed
292
- `}exports.NiceDeviceTrust=It;exports.NiceFaceRecognition=it;exports.NiceFingerprintScanner=tt;exports.NiceI18nProvider=Ve;exports.NiceIrisScanner=st;exports.NiceMfaSelector=jt;exports.NicePassphraseInput=Pt;exports.NicePatternLock=gt;exports.NicePinKeypad=dt;exports.NiceSecurityAuditLog=St;exports.NiceSessionManager=Ct;exports.NiceWebAuthnButton=xt;exports.SECRET_PATTERNS=or;exports.SECURITY_PATTERNS=nr;exports.authenticateWebAuthn=_e;exports.captureFrame=se;exports.checkColorContrast=Vt;exports.checkHeadingHierarchy=tr;exports.checkLiveness=ye;exports.clearNonEssentialCookies=Yt;exports.collectDeviceInfo=pe;exports.compareFaceToPhoto=Fe;exports.createAuditLogger=rr;exports.createCSRFFetch=Wt;exports.createHIPAASession=Qt;exports.createRateLimiter=He;exports.createSafeHtml=_t;exports.detectIris=De;exports.escapeHtml=We;exports.extractFaceFeatures=ae;exports.extractMinutiae=Te;exports.faceToTemplate=Ne;exports.fingerprintToTemplate=Ie;exports.generateCSPHeader=Mt;exports.generateCSRFToken=Bt;exports.generateDataExport=Jt;exports.generateDeviceFingerprint=ie;exports.generateLivenessChallenge=Xe;exports.generateNonce=Ft;exports.generatePreCommitHook=cr;exports.generateSASTConfig=ir;exports.generateSCAConfig=ar;exports.generateSecretScanningConfig=lr;exports.generateSecurityAdvisory=ur;exports.generateSecurityMd=dr;exports.getCSRFTokenFromCookie=ve;exports.getCameraStream=le;exports.getConsentPreferences=Ue;exports.getRecommendedCSP=Et;exports.getSOC2Checklist=sr;exports.hasAccessibleName=er;exports.hasConsent=Gt;exports.irisToTemplate=Me;exports.isPasskeyAvailable=Le;exports.isWebAuthnAvailable=ge;exports.logPHIAccess=Xt;exports.matchFaces=fe;exports.matchFingerprints=Ce;exports.matchIris=Pe;exports.registerWebAuthn=$e;exports.requestDataDeletion=Zt;exports.resolveConfig=oe;exports.sanitizeInput=zt;exports.sanitizeSvg=$t;exports.sanitizeUrl=Lt;exports.saveConsentPreferences=Kt;exports.scanFileForViruses=qt;exports.templateToFace=ze;exports.templateToFingerprint=Re;exports.templateToIris=Ee;exports.useCSRFToken=Ht;exports.useNiceTranslation=Q;exports.useRateLimiter=Ot;exports.validateFile=Oe;exports.validateFiles=Ut;exports.verifyWithBackend=ue;
292
+ `}exports.NiceDeviceTrust=It;exports.NiceFaceRecognition=it;exports.NiceFingerprintScanner=tt;exports.NiceI18nProvider=Qe;exports.NiceIrisScanner=st;exports.NiceMfaSelector=jt;exports.NicePassphraseInput=Pt;exports.NicePatternLock=gt;exports.NicePinKeypad=dt;exports.NiceSecurityAuditLog=St;exports.NiceSessionManager=Ct;exports.NiceWebAuthnButton=xt;exports.SECRET_PATTERNS=or;exports.SECURITY_PATTERNS=nr;exports.authenticateWebAuthn=_e;exports.captureFrame=se;exports.checkColorContrast=Qt;exports.checkHeadingHierarchy=tr;exports.checkLiveness=ye;exports.clearNonEssentialCookies=Yt;exports.collectDeviceInfo=pe;exports.compareFaceToPhoto=Fe;exports.createAuditLogger=rr;exports.createCSRFFetch=Wt;exports.createHIPAASession=Xt;exports.createRateLimiter=He;exports.createSafeHtml=_t;exports.detectIris=De;exports.escapeHtml=We;exports.extractFaceFeatures=ae;exports.extractMinutiae=Te;exports.faceToTemplate=Ne;exports.fingerprintToTemplate=Ie;exports.generateCSPHeader=Mt;exports.generateCSRFToken=Bt;exports.generateDataExport=Jt;exports.generateDeviceFingerprint=ie;exports.generateLivenessChallenge=Xe;exports.generateNonce=Ft;exports.generatePreCommitHook=cr;exports.generateSASTConfig=ir;exports.generateSCAConfig=ar;exports.generateSecretScanningConfig=lr;exports.generateSecurityAdvisory=ur;exports.generateSecurityMd=dr;exports.getCSRFTokenFromCookie=ve;exports.getCameraStream=le;exports.getConsentPreferences=Ue;exports.getRecommendedCSP=Et;exports.getSOC2Checklist=sr;exports.hasAccessibleName=er;exports.hasConsent=Gt;exports.irisToTemplate=Me;exports.isPasskeyAvailable=Le;exports.isWebAuthnAvailable=ge;exports.logPHIAccess=Vt;exports.matchFaces=fe;exports.matchFingerprints=Ce;exports.matchIris=Pe;exports.registerWebAuthn=$e;exports.requestDataDeletion=Zt;exports.resolveConfig=oe;exports.sanitizeInput=zt;exports.sanitizeSvg=$t;exports.sanitizeUrl=Lt;exports.saveConsentPreferences=Kt;exports.scanFileForViruses=qt;exports.templateToFace=ze;exports.templateToFingerprint=Re;exports.templateToIris=Ee;exports.useCSRFToken=Ht;exports.useNiceTranslation=X;exports.useRateLimiter=Ot;exports.validateFile=Oe;exports.validateFiles=Ut;exports.verifyWithBackend=ue;