@corbado/autocapture 1.0.1 → 1.1.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/dist/index.d.ts CHANGED
@@ -1,250 +1,7 @@
1
- import { WebAuthnIdentifierProjectors } from '@corbado/observe';
1
+ import { W as WebAuthnCaptureOptions, a as WebAuthnCaptureHandle, N as NetworkCaptureOptions, C as CaptureHandle, b as NavigationCaptureOptions } from './types-CXJAj2DU.js';
2
+ export { H as HttpExchange, c as HttpRequestStarted, L as Logger, d as NavigationEvent, e as NavigationSource, f as NetworkBodyDirection, g as NetworkBodyProjectionContext, h as NetworkBodyProjector, i as NetworkTransport, j as WebAuthnAttachSurface, k as WebAuthnCeremonyCompletedEvent, l as WebAuthnCeremonyContext, m as WebAuthnCeremonyEvent, n as WebAuthnCeremonyFailedEvent, o as WebAuthnCeremonyStartedEvent, p as WebAuthnMediation, q as WebAuthnUiMode } from './types-CXJAj2DU.js';
2
3
  export { WebAuthnIdentifierProjector, WebAuthnIdentifierProjectors, sanitizeAssertionResponse, sanitizeCreationOptions, sanitizeCreationResponse, sanitizeRequestOptions } from '@corbado/observe';
3
4
 
4
- /** Receives optional diagnostics. Capture functions remain silent when no logger is provided. */
5
- type Logger = {
6
- /** Records a non-fatal diagnostic message. */
7
- log: (...args: unknown[]) => void;
8
- };
9
- /** Controls a capture session. */
10
- type CaptureHandle = {
11
- /**
12
- * Result of starting the capture.
13
- *
14
- * - `"standard"`: capture started normally.
15
- * - `"unavailable"`: capture could not be started and will not emit events.
16
- */
17
- readonly mode: "standard" | "unavailable";
18
- /** Stops future event delivery. Safe to call more than once. */
19
- disconnect(): void;
20
- };
21
- /** Normalized Credential Management mediation. Missing mediation defaults to `optional`. */
22
- type WebAuthnMediation = "silent" | "optional" | "conditional" | "required" | "unknown";
23
- /** Normalized Credential Management UI mode for authentication ceremonies. */
24
- type WebAuthnUiMode = "default" | "immediate" | "unknown";
25
- /** Browser-native facts that remain stable for one ceremony. */
26
- type WebAuthnCeremonyContext = {
27
- kind: "authentication";
28
- mediation: WebAuthnMediation;
29
- uiMode: WebAuthnUiMode;
30
- /** Whether the RP supplied a non-empty allow list or requested discoverable credentials. */
31
- credentialSet: "allowlisted" | "discoverable";
32
- } | {
33
- kind: "registration";
34
- mediation: WebAuthnMediation;
35
- };
36
- type WebAuthnCeremonyBase = WebAuthnCeremonyContext & {
37
- /** Identifier shared by all events belonging to the same ceremony. */
38
- ceremonyId: string;
39
- };
40
- type WebAuthnCeremonyStartedEvent = WebAuthnCeremonyBase & {
41
- phase: "started";
42
- /** Whether transient user activation was active when the ceremony started, when exposed by the browser. */
43
- userActivation?: boolean;
44
- /**
45
- * JSON-encoded authentication publicKey options. All fields are retained.
46
- * Binary values are base64url-encoded. Treat this value as sensitive telemetry.
47
- */
48
- requestOptionsJson?: string;
49
- /** Creation publicKey options with user.name and user.displayName removed. */
50
- creationOptionsJson?: string;
51
- };
52
- type WebAuthnCeremonyCompletedEvent = WebAuthnCeremonyBase & {
53
- phase: "completed";
54
- /** JSON-encoded credential after the centralized blacklist; present only when applicable and serializable. Treat this value as sensitive telemetry. */
55
- credentialJson?: string;
56
- /** A credential manager may complete even after the ceremony signal was aborted. */
57
- aborted?: true;
58
- };
59
- type WebAuthnCeremonyFailedEvent = WebAuthnCeremonyBase & {
60
- phase: "failed";
61
- /** Rejection value from the failed ceremony. This may contain application-specific data. */
62
- error: unknown;
63
- /** DOM exception name, or `UnknownError` when no name is available. */
64
- errorName: string;
65
- /** Present when the request signal was aborted before settlement. */
66
- aborted?: true;
67
- };
68
- /** A protocol-native lifecycle event for WebAuthn authentication or registration. */
69
- type WebAuthnCeremonyEvent = WebAuthnCeremonyStartedEvent | WebAuthnCeremonyCompletedEvent | WebAuthnCeremonyFailedEvent;
70
- /**
71
- * Surface WebAuthn capture may attach to.
72
- *
73
- * - `"methods"`: `credentials.get` / `credentials.create` only.
74
- * - `"container"`: additionally the `navigator.credentials` container, used when the methods are
75
- * held by another integration in a form that cannot be shared.
76
- */
77
- type WebAuthnAttachSurface = "methods" | "container";
78
- /** Options for {@link captureWebAuthn}. */
79
- type WebAuthnCaptureOptions = {
80
- /** Receives WebAuthn lifecycle events. Return values are not awaited. */
81
- onEvent: (event: WebAuthnCeremonyEvent) => void;
82
- /** Optional diagnostic logger. */
83
- logger?: Logger;
84
- /**
85
- * Synchronous SDK user identifier projection for creation user.id and response userHandle.
86
- * Missing callbacks preserve user IDs; callback errors omit them. Credential IDs stay unchanged.
87
- * Use the same projector in network fallback serializers.
88
- * Projection affects telemetry only; authentication arguments, results and errors stay unchanged.
89
- */
90
- identifierProjectors?: WebAuthnIdentifierProjectors;
91
- /**
92
- * Highest surface capture may attach to. Defaults to `"methods"`.
93
- *
94
- * With `"container"`, a capture that cannot patch the methods attaches to the
95
- * `navigator.credentials` container instead: reads of `get`/`create` are observed while the
96
- * integration holding them keeps handling the ceremony. The methods surface is always tried
97
- * first, so this changes nothing when it is available.
98
- */
99
- attach?: WebAuthnAttachSurface;
100
- };
101
- /**
102
- * Handle returned by {@link captureWebAuthn}.
103
- *
104
- * `surface` reports where the capture actually attached, which is not implied by `mode`: an
105
- * `attach: "container"` capture reports `mode: "standard"` from either surface.
106
- */
107
- type WebAuthnCaptureHandle = CaptureHandle & {
108
- /** Surface this capture attached to; `"none"` when `mode` is `"unavailable"`. */
109
- readonly surface: WebAuthnAttachSurface | "none";
110
- };
111
- /** Network API used for an observed exchange. */
112
- type NetworkTransport = "xhr" | "fetch";
113
- /** Direction of a projected body within an observed network exchange. */
114
- type NetworkBodyDirection = "request" | "response";
115
- /** A matched network request immediately after the platform accepted it. */
116
- type HttpRequestStarted<RequestBody = unknown> = {
117
- /** Identifier shared with the eventual {@link HttpExchange}. */
118
- requestId: string;
119
- /** Network API used for the request. */
120
- transport: NetworkTransport;
121
- /** Uppercase HTTP method. */
122
- method: string;
123
- /** Resolved absolute request input URL. */
124
- url: string;
125
- /** Pathname component of the request URL. */
126
- path: string;
127
- /** Timestamp captured at the request boundary. */
128
- startedAt: number;
129
- /** Request-body value returned by the configured projector, when synchronously available. */
130
- requestBody?: RequestBody;
131
- };
132
- /** An observed network request and its outcome. */
133
- type HttpExchange<RequestBody = unknown, ResponseBody = unknown> = {
134
- /** Identifier shared with the corresponding {@link HttpRequestStarted}. */
135
- requestId: string;
136
- /** Network API used for the request. */
137
- transport: NetworkTransport;
138
- /** Uppercase HTTP method. */
139
- method: string;
140
- /**
141
- * Resolved absolute request input URL, including its query string and
142
- * fragment. Redact it before forwarding if either component may be sensitive.
143
- */
144
- url: string;
145
- /** Pathname component of the request URL. */
146
- path: string;
147
- /** HTTP status code, or `0` when a status is unavailable. */
148
- status: number;
149
- /** Whether the status code represents a successful response. */
150
- ok: boolean;
151
- /**
152
- * How the request completed. `load` includes successful and non-successful
153
- * HTTP responses; inspect `ok` or `status` for HTTP success.
154
- */
155
- outcome: "load" | "abort" | "timeout" | "error";
156
- /** Elapsed request time in milliseconds, when available. */
157
- durationMs?: number;
158
- /**
159
- * Final absolute response URL, when available. This may differ from `url`
160
- * after redirects and may contain sensitive query or fragment values.
161
- */
162
- responseUrl?: string;
163
- /** Request-body value returned by the configured projector, when available. */
164
- requestBody?: RequestBody;
165
- /** Response-body value returned by the configured projector, when available. */
166
- responseBody?: ResponseBody;
167
- };
168
- /** Metadata supplied to a body projector for one matched exchange. */
169
- type NetworkBodyProjectionContext<Direction extends NetworkBodyDirection = NetworkBodyDirection> = {
170
- /** Whether the observed body belongs to the request or response. */
171
- direction: Direction;
172
- /** Network API used by the application. */
173
- transport: NetworkTransport;
174
- /** Uppercase HTTP method. */
175
- method: string;
176
- /** Resolved absolute request URL. */
177
- url: string;
178
- /** Pathname component of the request URL. */
179
- path: string;
180
- };
181
- /**
182
- * Synchronously selects the only body data that may leave network capture.
183
- * Textual bodies are supplied as strings; an XHR with `responseType="json"`
184
- * supplies the browser-parsed value. Returning `undefined`, throwing, or
185
- * returning a Promise omits the body without affecting the application.
186
- * `ProjectedBody` describes the exact value delivered to callbacks.
187
- */
188
- type NetworkBodyProjector<ProjectedBody = unknown, Direction extends NetworkBodyDirection = NetworkBodyDirection> = (body: unknown, context: NetworkBodyProjectionContext<Direction>) => ProjectedBody | undefined;
189
- /**
190
- * Options for {@link captureNetwork}. Request and response body types are
191
- * inferred from their projectors and propagated to the corresponding callbacks.
192
- */
193
- type NetworkCaptureOptions<RequestBody = unknown, ResponseBody = unknown> = {
194
- /**
195
- * Selects requests to observe. The URL is resolved against the document base
196
- * URL and the method is uppercase. Return `true` to observe the request.
197
- * This callback must return synchronously; Promise results are not matched.
198
- */
199
- match: (url: URL, method: string) => boolean;
200
- /** Receives completed network exchanges. Return values are not awaited. */
201
- onExchange: (exchange: HttpExchange<NoInfer<RequestBody>, NoInfer<ResponseBody>>) => void;
202
- /**
203
- * Receives matched requests after the platform call succeeds. The request ID
204
- * matches the eventual exchange. Return values are not awaited.
205
- */
206
- onRequest?: (request: HttpRequestStarted<NoInfer<RequestBody>>) => void;
207
- /**
208
- * Network APIs to observe. Defaults to both `xhr` and `fetch`. Unavailable
209
- * transports are skipped if at least one requested transport can be observed.
210
- */
211
- transports?: readonly NetworkTransport[];
212
- /**
213
- * Best-effort body observation, enabled independently per direction by a
214
- * mandatory projector. Without a projector, that direction is never read.
215
- * Autocapture performs no generic parsing or redaction: the projector owns
216
- * data minimization and its return value is the only body data reported.
217
- */
218
- bodyCapture?: {
219
- /** Projects a request body. */
220
- request?: NetworkBodyProjector<RequestBody, "request">;
221
- /** Projects a response body. */
222
- response?: NetworkBodyProjector<ResponseBody, "response">;
223
- };
224
- /** Optional diagnostic logger. */
225
- logger?: Logger;
226
- };
227
- /** Mechanism that produced a navigation event. */
228
- type NavigationSource = "push" | "replace" | "pop" | "hash";
229
- /** A same-document navigation. */
230
- type NavigationEvent = {
231
- /** Current URL pathname. */
232
- path: string;
233
- /** Current URL query string, including the leading `?` when present. May contain sensitive data. */
234
- search: string;
235
- /** Current URL fragment, including the leading `#` when present. May contain sensitive data. */
236
- hash: string;
237
- /** Mechanism that produced the event. */
238
- source: NavigationSource;
239
- };
240
- /** Options for {@link captureNavigation}. */
241
- type NavigationCaptureOptions = {
242
- /** Receives same-document navigation events. Return values are not awaited. */
243
- onNavigate: (event: NavigationEvent) => void;
244
- /** Optional diagnostic logger. */
245
- logger?: Logger;
246
- };
247
-
248
5
  /**
249
6
  * Observes WebAuthn ceremonies initiated through
250
7
  * `navigator.credentials.get()` and `navigator.credentials.create()`.
@@ -377,4 +134,4 @@ declare function isValidationMessageVisible(element: Element | null): boolean;
377
134
  */
378
135
  declare function captureInputValidation(options: InputValidationCaptureOptions): InputValidationCaptureHandle;
379
136
 
380
- export { type CaptureHandle, type HttpExchange, type HttpRequestStarted, type InputValidationCaptureHandle, type InputValidationCaptureOptions, type InputValidationError, type InputValidationState, type Logger, type NavigationCaptureOptions, type NavigationEvent, type NavigationSource, type NetworkBodyDirection, type NetworkBodyProjectionContext, type NetworkBodyProjector, type NetworkCaptureOptions, type NetworkTransport, VERSION, type WebAuthnAttachSurface, type WebAuthnCaptureHandle, type WebAuthnCaptureOptions, type WebAuthnCeremonyCompletedEvent, type WebAuthnCeremonyContext, type WebAuthnCeremonyEvent, type WebAuthnCeremonyFailedEvent, type WebAuthnCeremonyStartedEvent, type WebAuthnMediation, type WebAuthnUiMode, captureInputValidation, captureNavigation, captureNetwork, captureWebAuthn, composedPath, inputValidationCode, isValidationMessageVisible };
137
+ export { CaptureHandle, type InputValidationCaptureHandle, type InputValidationCaptureOptions, type InputValidationError, type InputValidationState, NavigationCaptureOptions, NetworkCaptureOptions, VERSION, WebAuthnCaptureHandle, WebAuthnCaptureOptions, captureInputValidation, captureNavigation, captureNetwork, captureWebAuthn, composedPath, inputValidationCode, isValidationMessageVisible };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var ne=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var ke=(e,t)=>{for(var n in t)ne(e,n,{get:t[n],enumerable:!0})},Pe=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xe(t))!Ae.call(e,o)&&o!==n&&ne(e,o,{get:()=>t[o],enumerable:!(i=Oe(t,o))||i.enumerable});return e};var Ie=e=>Pe(ne({},"__esModule",{value:!0}),e);var Ve={};ke(Ve,{VERSION:()=>Re,captureInputValidation:()=>Ee,captureNavigation:()=>be,captureNetwork:()=>ge,captureWebAuthn:()=>ce,composedPath:()=>we,inputValidationCode:()=>ae,isValidationMessageVisible:()=>Ce,sanitizeAssertionResponse:()=>$.sanitizeAssertionResponse,sanitizeCreationOptions:()=>$.sanitizeCreationOptions,sanitizeCreationResponse:()=>$.sanitizeCreationResponse,sanitizeRequestOptions:()=>$.sanitizeRequestOptions});module.exports=Ie(Ve);var z=require("@corbado/observe");var Se={log:()=>{}};function F(e){return e?{log:(...t)=>{try{let n=e.log(...t);if(n&&(typeof n=="object"||typeof n=="function"))try{Promise.resolve(n).catch(()=>{})}catch{}}catch{}}}:Se}var ue=Symbol.for("corbado.autocapture.installed");function _(e){try{return typeof e=="function"&&Object.prototype.hasOwnProperty.call(e,ue)}catch{return!1}}function K(e,t){var i,o;let n=t;try{Object.defineProperty(e,ue,{value:t,configurable:!0})}catch{}try{Object.defineProperty(e,"name",{value:(i=n.name)!=null?i:"",configurable:!0})}catch{}try{Object.defineProperty(e,"length",{value:(o=n.length)!=null?o:0,configurable:!0})}catch{}return e}function N(){return{mode:"unavailable",disconnect:()=>{}}}function re(e,t){return!!e&&"value"in e&&"value"in t&&e.value===t.value&&e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable}function G(e,t,n,i,o,y=String(t)){try{let f=Object.getOwnPropertyDescriptor(e,t);re(f,{...i,value:n})&&Object.defineProperty(e,t,i)}catch(f){o.log(`${y} restoration skipped`,f)}}function J(e,t,n){let i=F(e);return o=>{try{let y=n(o);if(y&&(typeof y=="object"||typeof y=="function"))try{Promise.resolve(y).catch(f=>i.log(`${t} listener failed`,f))}catch(f){i.log(`${t} listener failed`,f)}}catch(y){i.log(`${t} listener failed`,y)}}}var de=e=>({get:e("get"),create:e("create")});function ce(e){let t=e.onEvent;if(typeof t!="function")throw new TypeError("captureWebAuthn requires an onEvent callback");let n=F(e.logger),i=c=>(n.log(`webauthn capture unavailable: ${c}`),{...N(),surface:"none"}),o=typeof navigator=="undefined"?void 0:navigator,y=o==null?void 0:o.credentials;if(!o||!y)return i("navigator.credentials missing");let f=y,A=de(c=>f[c]);if(typeof A.get!="function"||typeof A.create!="function")return i("credentials methods missing");if(_(A.get)||_(A.create))return i("an equivalent capture is already active");let s=!1,B=0,O=J(n,"webauthn",t),k=(c,h,b)=>{let T={invoke(...d){let g=d[0];if(!s||b!=null&&b()||!oe(g)||!oe(g.publicKey))return h(this,d);let l=g.publicKey,u=`wa-${++B}`,q=h(this,d),x=oe(g.signal)?g.signal:void 0,r=Te(c,g,l),p=m=>{s&&O({...r,ceremonyId:u,...m()})},w=()=>(x==null?void 0:x.aborted)===!0?{aborted:!0}:{};return p(()=>({phase:"started",userActivation:Me(o),...r.kind==="authentication"?{requestOptionsJson:(0,z.sanitizeRequestOptions)(l)}:{creationOptionsJson:(0,z.sanitizeCreationOptions)(l,e.identifierProjectors)}})),Promise.resolve(q).then(m=>(p(()=>({phase:"completed",credentialJson:c==="create"?(0,z.sanitizeCreationResponse)(m,e.identifierProjectors):(0,z.sanitizeAssertionResponse)(m,e.identifierProjectors),...w()})),m),m=>{throw p(()=>({phase:"failed",error:m,errorName:De(m),...w()})),m})}}.invoke;return K(T,{name:c,length:0})},D=c=>{var T;let h=k(c,(d,g)=>Reflect.apply(A[c],d,g)),b=Object.getOwnPropertyDescriptor(y,c);if(b&&(!("value"in b)||b.writable!==!0))return null;try{f[c]=h}catch{return null}if(((T=Object.getOwnPropertyDescriptor(y,c))==null?void 0:T.value)!==h){try{f[c]=A[c]}catch{}return null}return()=>{f[c]===h&&(b?f[c]=b.value:delete f[c])}},L=()=>{let c=de(()=>new WeakMap),h=(l,u)=>{let q=c[l].get(u);if(q)return q;let x=k(l,(r,p)=>Reflect.apply(u,y,p),()=>{try{let r=f[l];return r!==u&&r!==x}catch(r){return n.log("suppress check failed; ceremony unreported",r),!0}});return c[l].set(u,x),x},b=l=>{let u=Object.getOwnPropertyDescriptor(y,l);return u?u.configurable===!0||!("value"in u)||u.writable===!0:!0},T=new WeakMap,d=new Proxy(y,{get(l,u){let q=Reflect.get(y,u,y);if((u==="get"||u==="create")&&b(u))return typeof q!="function"||_(q)?q:h(u,q);if(typeof q!="function"||!b(u)||u==="constructor")return q;let x=T.get(q);if(x)return x;let r=q.bind(y);return T.set(q,r),r},set(l,u,q){return Reflect.set(y,u,q,y)}}),g=Object.getOwnPropertyDescriptor(o,"credentials");if(g&&g.configurable!==!0)return null;try{Object.defineProperty(o,"credentials",{value:d,writable:!0,enumerable:!0,configurable:!0})}catch{return null}return o.credentials!==d?null:()=>{o.credentials===d&&(g?Object.defineProperty(o,"credentials",g):delete o.credentials)}},S=(c,h)=>(s=!0,{mode:"standard",surface:c,disconnect:()=>{s=!1,h()}}),P=D("get"),j=P?D("create"):null;if(P&&j)return S("methods",()=>{P(),j()});if(P==null||P(),e.attach==="container"){let c=L();if(c)return n.log("webauthn capture attached at the credentials container"),S("container",c)}return i("credentials methods cannot be patched safely")}function Te(e,t,n){let i=Le(t.mediation);if(e==="create")return{kind:"registration",mediation:i};let o=n;return{kind:"authentication",mediation:i,uiMode:Be(t.uiMode),credentialSet:Array.isArray(o.allowCredentials)&&o.allowCredentials.length>0?"allowlisted":"discoverable"}}function Le(e){return e===void 0?"optional":e==="silent"||e==="optional"||e==="conditional"||e==="required"?e:"unknown"}function Be(e){return e===void 0?"default":e==="immediate"?"immediate":"unknown"}function Me(e){let t=e.userActivation;return typeof(t==null?void 0:t.isActive)=="boolean"?t.isActive:void 0}function oe(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function De(e){return e instanceof DOMException?e.name:"UnknownError"}var le=0;function pe(){return le+=1,`network-${le}`}function Ne(e,t){let n=e.responseType;if(n===""||n==="text")return t(e.responseText);if(n==="json"){let i=e.response;return i==null?void 0:t(i)}}var He=500,fe=Symbol("body-read-timeout");function he(e){return/event-stream|octet-stream/i.test(e)?!1:/json|text|urlencoded/i.test(e)}async function ye(e,t){let n=e.body;if(!n)return;let i=n.getReader(),o;try{let y=new Promise(s=>{o=setTimeout(()=>s(fe),He)}),f=new TextDecoder,A=[];for(;;){let s=await Promise.race([i.read(),y]);if(s===fe){t.log("body omitted: read timed out"),i.cancel().catch(()=>{});return}if(s.done)break;A.push(f.decode(s.value,{stream:!0}))}return A.push(f.decode()),A.join("")}catch{i.cancel().catch(()=>{});return}finally{o!==void 0&&clearTimeout(o)}}function ie(e){var t;(t=e==null?void 0:e.body)==null||t.cancel().catch(()=>{})}function ge(e){var h,b,T;let{onExchange:t,onRequest:n,match:i}=e;if(typeof t!="function"||typeof i!="function")throw new TypeError("captureNetwork requires onExchange and match callbacks");let o=F(e.logger),y=(h=e.transports)!=null?h:["xhr","fetch"],f=(b=e.bodyCapture)==null?void 0:b.request,A=(T=e.bodyCapture)==null?void 0:T.response,s=typeof f=="function",B=typeof A=="function",O=!1,k=J(o,"network",d=>{if(O)return t(d)}),D=J(o,"network request",d=>{if(O)return n==null?void 0:n(d)}),L=(d,g,l)=>{if(typeof l=="function")try{return l(d,g)}catch(u){o.log("body projection failed",u);return}},S=(d,g)=>{try{let l=typeof document!="undefined"?document.baseURI:void 0,u=new URL(String(d),l);return i(u,g)===!0?{url:u.href,path:u.pathname}:void 0}catch{return}},P=()=>{if(typeof XMLHttpRequest=="undefined")return o.log("xhr capture unavailable: XMLHttpRequest missing"),null;let d=XMLHttpRequest.prototype,g=Object.getOwnPropertyDescriptor(d,"open"),l=Object.getOwnPropertyDescriptor(d,"send");if(!g||!("value"in g)||typeof g.value!="function"||!l||!("value"in l)||typeof l.value!="function")return o.log("xhr capture unavailable: XMLHttpRequest methods missing"),null;let u=g.value,q=l.value;if(_(u)||_(q))return o.log("xhr capture unavailable: an equivalent capture is already active"),null;let x=new WeakMap,r=new Set,p=!1,w={open(...R){var C;let a=Reflect.apply(u,this,R);if(!O||!p)return a;try{let M=x.get(this);M&&(M.reported=!0,(C=M.cleanupListeners)==null||C.call(M));let H=String(R[0]).toUpperCase(),I=S(R[1],H);I?x.set(this,{method:H,url:I.url,path:I.path,reported:!1}):x.delete(this)}catch(M){o.log("xhr open observation failed",M)}return a}}.open,m={send(...R){let a=O&&p?x.get(this):void 0;if(!a||a.reported||a.cleanupListeners)return Reflect.apply(q,this,R);let C=()=>{},M=!1;try{a.requestId=pe();let I={direction:"request",transport:"xhr",method:a.method,url:a.url,path:a.path};a.requestBody=s&&typeof R[0]=="string"?L(R[0],I,f):void 0;let Y=()=>{a.outcome===void 0&&(a.outcome="abort")},Q=()=>{a.outcome===void 0&&(a.outcome="timeout")},v=()=>{a.outcome===void 0&&(a.outcome="error")},E=()=>{var X;C();try{if(!O||!p||a.reported||!a.requestId)return;a.reported=!0;let W={direction:"response",transport:"xhr",method:a.method,url:a.url,path:a.path},te=this.status,se={requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,status:te,ok:te>=200&&te<300,outcome:(X=a.outcome)!=null?X:"load",durationMs:a.startedAt!==void 0?Date.now()-a.startedAt:void 0,responseUrl:this.responseURL||void 0,requestBody:a.requestBody,responseBody:B?Ne(this,qe=>L(qe,W,A)):void 0};a.requestEmitted?k(se):a.pendingExchange=se}catch(W){o.log("xhr exchange observation failed",W)}finally{x.get(this)===a&&x.delete(this)}},V=()=>{try{this.readyState===XMLHttpRequest.DONE&&this.status!==0&&E()}catch(X){o.log("xhr ready-state observation failed",X)}},U=()=>E();C=()=>{for(let[X,W]of[["readystatechange",V],["abort",Y],["timeout",Q],["error",v],["loadend",U]])this.removeEventListener(X,W);a.cleanupListeners===C&&(a.cleanupListeners=void 0),r.delete(C)},this.addEventListener("readystatechange",V),this.addEventListener("abort",Y),this.addEventListener("timeout",Q),this.addEventListener("error",v),this.addEventListener("loadend",U),a.cleanupListeners=C,r.add(C),a.startedAt=Date.now(),M=!0}catch(I){o.log("xhr send observation failed",I),C()}let H;try{H=Reflect.apply(q,this,R)}catch(I){throw C(),I}if(M&&a.requestId!==void 0&&a.startedAt!==void 0){a.requestEmitted=!0,D({requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,startedAt:a.startedAt,requestBody:a.requestBody});let I=a.pendingExchange;a.pendingExchange=void 0,I&&k(I)}return H}}.send;return K(w,u),K(m,q),g.writable!==!0||l.writable!==!0?(o.log("xhr capture unavailable: XMLHttpRequest methods are not writable"),null):(Object.defineProperty(d,"open",{...g,value:w}),Object.defineProperty(d,"send",{...l,value:m}),p=!0,()=>{p=!1;for(let R of[...r])R();G(d,"open",w,g,o),G(d,"send",m,l,o)})},j=()=>{let d=globalThis,g=Object.getOwnPropertyDescriptor(d,"fetch");if(!g||!("value"in g))return o.log("fetch capture unavailable: fetch is not an own data property"),null;let l=g.value;if(typeof l!="function")return o.log("fetch capture unavailable: fetch missing"),null;if(_(l))return o.log("fetch capture unavailable: an equivalent capture is already active"),null;let u=!1,q=async(r,p,w,m)=>{try{if(!O||!u){ie(w);return}let[R,a]=await Promise.all([m!=null?m:Promise.resolve(void 0),w?ye(w,o):Promise.resolve(void 0)]);if(!O||!u)return;let C={direction:"request",transport:"fetch",method:r.method,url:r.url,path:r.path},M={...C,direction:"response"},H=r.requestBody;H===void 0&&R!==void 0&&(H=L(R,C,f));let I=a!==void 0?L(a,M,A):void 0;k({requestId:r.requestId,transport:"fetch",method:r.method,url:r.url,path:r.path,status:p.status,ok:p.ok,outcome:"load",durationMs:Date.now()-r.startedAt,responseUrl:p.url||void 0,requestBody:H,responseBody:I})}catch(R){o.log("fetch exchange observation failed",R)}},x={fetch(...r){var H,I,Y,Q;let p;try{let v=r[0],E=r[1];if(O&&u&&s&&typeof Request!="undefined"&&v instanceof Request&&(E==null?void 0:E.body)===void 0&&v.body){let V=String((H=E==null?void 0:E.method)!=null?H:v.method).toUpperCase(),U=(I=v.headers.get("content-type"))!=null?I:"";S(v.url,V)&&he(U)&&(p=v.clone())}}catch(v){o.log("fetch observation failed",v)}let w,m=Date.now();try{w=Reflect.apply(l,this,r)}catch(v){throw ie(p),v}let R,a;try{if(O&&u){let v=r[0],E=r[1],V=typeof Request!="undefined"&&v instanceof Request,U=String((Y=E==null?void 0:E.method)!=null?Y:V?v.method:"GET").toUpperCase(),X=V?v.url:v,W=S(X,U);W&&(R={requestId:pe(),method:U,url:W.url,path:W.path,startedAt:m},a=(Q=E==null?void 0:E.signal)!=null?Q:V?v.signal:void 0,s&&typeof(E==null?void 0:E.body)=="string"&&(R.requestBody=L(E.body,{direction:"request",transport:"fetch",method:U,url:W.url,path:W.path},f)))}}catch(v){o.log("fetch observation failed",v)}if(!R)return ie(p),w;let C=R;D({requestId:C.requestId,transport:"fetch",method:C.method,url:C.url,path:C.path,startedAt:C.startedAt,requestBody:C.requestBody});let M=p?ye(p,o):void 0;return w.then(v=>{var V;let E;try{if(O&&u&&B){let U=(V=v.headers.get("content-type"))!=null?V:"";he(U)&&v.body&&(E=v.clone())}}catch{}q(C,v,E,M)},v=>{try{if(!O||!u)return;let E=(a==null?void 0:a.aborted)===!0||(v==null?void 0:v.name)==="AbortError"||typeof DOMException!="undefined"&&v instanceof DOMException&&v.code===DOMException.ABORT_ERR;k({requestId:C.requestId,transport:"fetch",method:C.method,url:C.url,path:C.path,status:0,ok:!1,outcome:E?"abort":"error",durationMs:Date.now()-C.startedAt})}catch(E){o.log("fetch failure observation failed",E)}}),w}}.fetch;return K(x,l),g.writable!==!0?(o.log("fetch capture unavailable: fetch is not writable"),null):(Object.defineProperty(d,"fetch",{...g,value:x}),u=!0,()=>{u=!1,G(d,"fetch",x,g,o)})},c=[];if(y.includes("xhr")){let d=P();d&&c.push(d)}if(y.includes("fetch")){let d=j();d&&c.push(d)}return c.length===0?N():(O=!0,{mode:"standard",disconnect:()=>{O=!1;for(let d of c.splice(0))d()}})}function be(e){let t=e.onNavigate;if(typeof t!="function")throw new TypeError("captureNavigation requires an onNavigate callback");let n=F(e.logger),i,o,y,f,A,s;try{if(i=window,o=i==null?void 0:i.history,!i||!o)return n.log("navigation capture unavailable: window/history missing"),N();if(A=me(o,"pushState"),s=me(o,"replaceState"),!A||!s)return n.log("navigation capture unavailable: history method descriptors missing"),N();if(y=A.descriptor.value,f=s.descriptor.value,typeof y!="function"||typeof f!="function")return n.log("navigation capture unavailable: history methods missing"),N();if(typeof i.addEventListener!="function"||typeof i.removeEventListener!="function")return n.log("navigation capture unavailable: window event methods missing"),N()}catch(h){return n.log("navigation capture unavailable: history inspection failed",h),N()}if(_(y)||_(f))return n.log("navigation capture unavailable: an equivalent capture is already active"),N();let B=!1,O=()=>({path:i.location.pathname,search:i.location.search,hash:i.location.hash}),k;try{k=O()}catch(h){return n.log("navigation capture unavailable: location inspection failed",h),N()}let D=J(n,"navigation",h=>{if(B)return t(h)}),L=h=>{if(B)try{let b=O();if(b.path===k.path&&b.search===k.search&&b.hash===k.hash)return;k=b,D({...b,source:h})}catch(b){n.log("navigation observation failed",b)}},S={pushState(...h){let b=Reflect.apply(y,this,h);return L("push"),b}}.pushState,P={replaceState(...h){let b=Reflect.apply(f,this,h);return L("replace"),b}}.replaceState;K(S,y),K(P,f);let j=()=>L("pop"),c=()=>L("hash");try{if(ve(A,S),ve(s,P),o.pushState!==S||o.replaceState!==P)throw new Error("history method replacement did not take effect");i.addEventListener("popstate",j),i.addEventListener("hashchange",c),B=!0}catch(h){return B=!1,ee(i,"popstate",j,n),ee(i,"hashchange",c,n),Z(s,P,n),Z(A,S,n),n.log("navigation capture unavailable: history methods are not writable",h),t=()=>{},D=()=>{},n=F(),N()}return{mode:"standard",disconnect:()=>{B=!1,t=()=>{},ee(i,"popstate",j,n),ee(i,"hashchange",c,n),Z(A,S,n),Z(s,P,n),D=()=>{},n=F()}}}function me(e,t){let n=e;for(;n;){let i=Object.getOwnPropertyDescriptor(n,t);if(i)return!("value"in i)||typeof i.value!="function"?null:{owner:n,key:t,descriptor:i};n=Object.getPrototypeOf(n)}return null}function ve(e,t){if(e.descriptor.writable!==!0)throw new TypeError(`${e.key} is not writable`);let n=Object.getOwnPropertyDescriptor(e.owner,e.key);if(!re(n,e.descriptor))throw new Error(`${e.key} changed during installation`);Object.defineProperty(e.owner,e.key,{...e.descriptor,value:t})}function Z(e,t,n){G(e.owner,e.key,t,e.descriptor,n,`navigation ${e.key}`)}function ee(e,t,n,i){try{e.removeEventListener(t,n)}catch(o){i.log(`navigation ${t} listener removal skipped`,o)}}function we(e){let t=e.composedPath();return t.length>0?t:e.target?[e.target]:[]}var Re="1.0.1";var je=["valueMissing","typeMismatch","patternMismatch","tooShort","tooLong","rangeUnderflow","rangeOverflow","stepMismatch","badInput","customError"];function ae(e){return je.find(t=>e.validity[t])}function Ce(e){if(!(e!=null&&e.isConnected)||!e.getClientRects().length)return!1;let t=e.ownerDocument.defaultView;if(!t)return!1;for(let n=e;n;n=n.parentElement){let i=t.getComputedStyle(n);if(n.hasAttribute("hidden")||i.display==="none"||i.visibility==="hidden"||i.visibility==="collapse"||i.opacity==="0")return!1}return!0}function Ee(e){var q,x;if(typeof e.readValidation!="function"||typeof e.onError!="function")throw new TypeError("captureInputValidation requires readValidation and onError callbacks");let{form:t}=e,n=[...e.fields],i=(q=e.maxObservationMs)!=null?q:1e4;if(!n.length||!Number.isFinite(i)||i<=0)throw new TypeError("captureInputValidation requires fields and a positive maxObservationMs");let o={mode:"unavailable",disconnect(){},beginAttempt:()=>{},requestStarted(){},refresh(){}},y=(x=t==null?void 0:t.ownerDocument)==null?void 0:x.defaultView;if(!y||!n.every(r=>r.form===t))return o;let f=!0,A=0,s,B=!1,O,k,D,L,S=[],P=()=>t.isConnected&&n.every(r=>r.isConnected&&r.form===t),j=()=>{try{let r=e.readValidation();if(r&&["clear","pending","unknown"].includes(r.status)||(r==null?void 0:r.status)==="invalid"&&typeof r.code=="string"&&["constraint","application"].includes(r.source))return r}catch{}return{status:"unknown"}},c=r=>r.status==="invalid"?JSON.stringify([r.code,r.fieldIndex]):void 0,h=()=>{s=void 0,clearTimeout(k),clearTimeout(D),k=D=void 0},b=()=>{k=void 0;let r=s;if(!f||!(r!=null&&r.confirmed))return;if(!P()){h();return}let p=r.nativeInvalid?(()=>{for(let[m,R]of n.entries()){let a=ae(R);if(a)return{status:"invalid",source:"constraint",code:a,fieldIndex:m}}return{status:"clear"}})():j();if(p.status==="clear"){r.serverBaseline=void 0;return}if(p.status!=="invalid"||p.source==="application"&&r.serverBaseline===c(p))return;let w={attemptId:r.id,startedAt:r.startedAt,timestamp:Date.now(),code:p.code,...p.fieldIndex===void 0?{}:{fieldIndex:p.fieldIndex}};h(),B=!1;try{Promise.resolve(e.onError(w)).catch(()=>{})}catch{}},T=()=>{!f||!s||k!==void 0||(k=setTimeout(b,0))},d=r=>{if(!f||!P())return;h();let p=B?c(j()):void 0;return s={id:++A,startedAt:Date.now(),confirmed:r,nativeInvalid:!1,serverBaseline:p},D=setTimeout(h,i),T(),s.id},g=()=>{O===void 0&&(O=d(!1),L=setTimeout(()=>{s&&s.id===O&&!s.confirmed&&h(),O=void 0},0))},l=(r,p,w)=>{r.addEventListener(p,w,!0),S.push(()=>r.removeEventListener(p,w,!0))},u={mode:"standard",beginAttempt:()=>d(!0),refresh:T,requestStarted(r={}){f&&(r.attemptId!==void 0&&r.attemptId!==(s==null?void 0:s.id)||s&&r.timestamp!==void 0&&r.timestamp<s.startedAt||(h(),B=!0))},disconnect(){if(f){f=!1,h(),clearTimeout(L);for(let r of S.splice(0))r()}}};try{let r=w=>{var a;let m=w.target,R=(a=m==null?void 0:m.closest)==null?void 0:a.call(m,"button,input");(R==null?void 0:R.form)===t&&!R.disabled&&["submit","image"].includes(R.type)&&g()};l(t.ownerDocument,"click",r),l(t,"click",r),l(t,"keydown",w=>{let m=w;m.key==="Enter"&&!m.isComposing&&!m.defaultPrevented&&n.includes(m.target)&&g()}),l(t,"submit",()=>{(s==null?void 0:s.id)===O&&s?(s.confirmed=!0,T()):d(!0),O=void 0}),l(t,"invalid",w=>{!s||!n.includes(w.target)||(s.confirmed=!0,s.nativeInvalid=!0,T())}),l(t,"input",w=>{n.includes(w.target)&&h()});let p=new y.MutationObserver(T);p.observe(t,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),S.push(()=>p.disconnect())}catch{return u.disconnect(),o}return u}var $=require("@corbado/observe");0&&(module.exports={VERSION,captureInputValidation,captureNavigation,captureNetwork,captureWebAuthn,composedPath,inputValidationCode,isValidationMessageVisible,sanitizeAssertionResponse,sanitizeCreationOptions,sanitizeCreationResponse,sanitizeRequestOptions});
1
+ "use strict";var ne=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var ke=(e,t)=>{for(var n in t)ne(e,n,{get:t[n],enumerable:!0})},Pe=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xe(t))!Ae.call(e,o)&&o!==n&&ne(e,o,{get:()=>t[o],enumerable:!(i=Oe(t,o))||i.enumerable});return e};var Ie=e=>Pe(ne({},"__esModule",{value:!0}),e);var Ve={};ke(Ve,{VERSION:()=>Re,captureInputValidation:()=>Ee,captureNavigation:()=>be,captureNetwork:()=>ge,captureWebAuthn:()=>ce,composedPath:()=>we,inputValidationCode:()=>ae,isValidationMessageVisible:()=>Ce,sanitizeAssertionResponse:()=>$.sanitizeAssertionResponse,sanitizeCreationOptions:()=>$.sanitizeCreationOptions,sanitizeCreationResponse:()=>$.sanitizeCreationResponse,sanitizeRequestOptions:()=>$.sanitizeRequestOptions});module.exports=Ie(Ve);var z=require("@corbado/observe");var Se={log:()=>{}};function F(e){return e?{log:(...t)=>{try{let n=e.log(...t);if(n&&(typeof n=="object"||typeof n=="function"))try{Promise.resolve(n).catch(()=>{})}catch{}}catch{}}}:Se}var ue=Symbol.for("corbado.autocapture.installed");function _(e){try{return typeof e=="function"&&Object.prototype.hasOwnProperty.call(e,ue)}catch{return!1}}function K(e,t){var i,o;let n=t;try{Object.defineProperty(e,ue,{value:t,configurable:!0})}catch{}try{Object.defineProperty(e,"name",{value:(i=n.name)!=null?i:"",configurable:!0})}catch{}try{Object.defineProperty(e,"length",{value:(o=n.length)!=null?o:0,configurable:!0})}catch{}return e}function N(){return{mode:"unavailable",disconnect:()=>{}}}function re(e,t){return!!e&&"value"in e&&"value"in t&&e.value===t.value&&e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable}function G(e,t,n,i,o,y=String(t)){try{let f=Object.getOwnPropertyDescriptor(e,t);re(f,{...i,value:n})&&Object.defineProperty(e,t,i)}catch(f){o.log(`${y} restoration skipped`,f)}}function J(e,t,n){let i=F(e);return o=>{try{let y=n(o);if(y&&(typeof y=="object"||typeof y=="function"))try{Promise.resolve(y).catch(f=>i.log(`${t} listener failed`,f))}catch(f){i.log(`${t} listener failed`,f)}}catch(y){i.log(`${t} listener failed`,y)}}}var de=e=>({get:e("get"),create:e("create")});function ce(e){let t=e.onEvent;if(typeof t!="function")throw new TypeError("captureWebAuthn requires an onEvent callback");let n=F(e.logger),i=c=>(n.log(`webauthn capture unavailable: ${c}`),{...N(),surface:"none"}),o=typeof navigator=="undefined"?void 0:navigator,y=o==null?void 0:o.credentials;if(!o||!y)return i("navigator.credentials missing");let f=y,A=de(c=>f[c]);if(typeof A.get!="function"||typeof A.create!="function")return i("credentials methods missing");if(_(A.get)||_(A.create))return i("an equivalent capture is already active");let s=!1,B=0,O=J(n,"webauthn",t),k=(c,h,b)=>{let T={invoke(...d){let g=d[0];if(!s||b!=null&&b()||!oe(g)||!oe(g.publicKey))return h(this,d);let l=g.publicKey,u=`wa-${++B}`,q=h(this,d),x=oe(g.signal)?g.signal:void 0,r=Te(c,g,l),p=m=>{s&&O({...r,ceremonyId:u,...m()})},w=()=>(x==null?void 0:x.aborted)===!0?{aborted:!0}:{};return p(()=>({phase:"started",userActivation:Me(o),...r.kind==="authentication"?{requestOptionsJson:(0,z.sanitizeRequestOptions)(l)}:{creationOptionsJson:(0,z.sanitizeCreationOptions)(l,e.identifierProjectors)}})),Promise.resolve(q).then(m=>(p(()=>({phase:"completed",credentialJson:c==="create"?(0,z.sanitizeCreationResponse)(m,e.identifierProjectors):(0,z.sanitizeAssertionResponse)(m,e.identifierProjectors),...w()})),m),m=>{throw p(()=>({phase:"failed",error:m,errorName:De(m),...w()})),m})}}.invoke;return K(T,{name:c,length:0})},D=c=>{var T;let h=k(c,(d,g)=>Reflect.apply(A[c],d,g)),b=Object.getOwnPropertyDescriptor(y,c);if(b&&(!("value"in b)||b.writable!==!0))return null;try{f[c]=h}catch{return null}if(((T=Object.getOwnPropertyDescriptor(y,c))==null?void 0:T.value)!==h){try{f[c]=A[c]}catch{}return null}return()=>{f[c]===h&&(b?f[c]=b.value:delete f[c])}},L=()=>{let c=de(()=>new WeakMap),h=(l,u)=>{let q=c[l].get(u);if(q)return q;let x=k(l,(r,p)=>Reflect.apply(u,y,p),()=>{try{let r=f[l];return r!==u&&r!==x}catch(r){return n.log("suppress check failed; ceremony unreported",r),!0}});return c[l].set(u,x),x},b=l=>{let u=Object.getOwnPropertyDescriptor(y,l);return u?u.configurable===!0||!("value"in u)||u.writable===!0:!0},T=new WeakMap,d=new Proxy(y,{get(l,u){let q=Reflect.get(y,u,y);if((u==="get"||u==="create")&&b(u))return typeof q!="function"||_(q)?q:h(u,q);if(typeof q!="function"||!b(u)||u==="constructor")return q;let x=T.get(q);if(x)return x;let r=q.bind(y);return T.set(q,r),r},set(l,u,q){return Reflect.set(y,u,q,y)}}),g=Object.getOwnPropertyDescriptor(o,"credentials");if(g&&g.configurable!==!0)return null;try{Object.defineProperty(o,"credentials",{value:d,writable:!0,enumerable:!0,configurable:!0})}catch{return null}return o.credentials!==d?null:()=>{o.credentials===d&&(g?Object.defineProperty(o,"credentials",g):delete o.credentials)}},S=(c,h)=>(s=!0,{mode:"standard",surface:c,disconnect:()=>{s=!1,h()}}),P=D("get"),j=P?D("create"):null;if(P&&j)return S("methods",()=>{P(),j()});if(P==null||P(),e.attach==="container"){let c=L();if(c)return n.log("webauthn capture attached at the credentials container"),S("container",c)}return i("credentials methods cannot be patched safely")}function Te(e,t,n){let i=Le(t.mediation);if(e==="create")return{kind:"registration",mediation:i};let o=n;return{kind:"authentication",mediation:i,uiMode:Be(t.uiMode),credentialSet:Array.isArray(o.allowCredentials)&&o.allowCredentials.length>0?"allowlisted":"discoverable"}}function Le(e){return e===void 0?"optional":e==="silent"||e==="optional"||e==="conditional"||e==="required"?e:"unknown"}function Be(e){return e===void 0?"default":e==="immediate"?"immediate":"unknown"}function Me(e){let t=e.userActivation;return typeof(t==null?void 0:t.isActive)=="boolean"?t.isActive:void 0}function oe(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function De(e){return e instanceof DOMException?e.name:"UnknownError"}var le=0;function pe(){return le+=1,`network-${le}`}function Ne(e,t){let n=e.responseType;if(n===""||n==="text")return t(e.responseText);if(n==="json"){let i=e.response;return i==null?void 0:t(i)}}var He=500,fe=Symbol("body-read-timeout");function he(e){return/event-stream|octet-stream/i.test(e)?!1:/json|text|urlencoded/i.test(e)}async function ye(e,t){let n=e.body;if(!n)return;let i=n.getReader(),o;try{let y=new Promise(s=>{o=setTimeout(()=>s(fe),He)}),f=new TextDecoder,A=[];for(;;){let s=await Promise.race([i.read(),y]);if(s===fe){t.log("body omitted: read timed out"),i.cancel().catch(()=>{});return}if(s.done)break;A.push(f.decode(s.value,{stream:!0}))}return A.push(f.decode()),A.join("")}catch{i.cancel().catch(()=>{});return}finally{o!==void 0&&clearTimeout(o)}}function ie(e){var t;(t=e==null?void 0:e.body)==null||t.cancel().catch(()=>{})}function ge(e){var h,b,T;let{onExchange:t,onRequest:n,match:i}=e;if(typeof t!="function"||typeof i!="function")throw new TypeError("captureNetwork requires onExchange and match callbacks");let o=F(e.logger),y=(h=e.transports)!=null?h:["xhr","fetch"],f=(b=e.bodyCapture)==null?void 0:b.request,A=(T=e.bodyCapture)==null?void 0:T.response,s=typeof f=="function",B=typeof A=="function",O=!1,k=J(o,"network",d=>{if(O)return t(d)}),D=J(o,"network request",d=>{if(O)return n==null?void 0:n(d)}),L=(d,g,l)=>{if(typeof l=="function")try{return l(d,g)}catch(u){o.log("body projection failed",u);return}},S=(d,g)=>{try{let l=typeof document!="undefined"?document.baseURI:void 0,u=new URL(String(d),l);return i(u,g)===!0?{url:u.href,path:u.pathname}:void 0}catch{return}},P=()=>{if(typeof XMLHttpRequest=="undefined")return o.log("xhr capture unavailable: XMLHttpRequest missing"),null;let d=XMLHttpRequest.prototype,g=Object.getOwnPropertyDescriptor(d,"open"),l=Object.getOwnPropertyDescriptor(d,"send");if(!g||!("value"in g)||typeof g.value!="function"||!l||!("value"in l)||typeof l.value!="function")return o.log("xhr capture unavailable: XMLHttpRequest methods missing"),null;let u=g.value,q=l.value;if(_(u)||_(q))return o.log("xhr capture unavailable: an equivalent capture is already active"),null;let x=new WeakMap,r=new Set,p=!1,w={open(...R){var C;let a=Reflect.apply(u,this,R);if(!O||!p)return a;try{let M=x.get(this);M&&(M.reported=!0,(C=M.cleanupListeners)==null||C.call(M));let H=String(R[0]).toUpperCase(),I=S(R[1],H);I?x.set(this,{method:H,url:I.url,path:I.path,reported:!1}):x.delete(this)}catch(M){o.log("xhr open observation failed",M)}return a}}.open,m={send(...R){let a=O&&p?x.get(this):void 0;if(!a||a.reported||a.cleanupListeners)return Reflect.apply(q,this,R);let C=()=>{},M=!1;try{a.requestId=pe();let I={direction:"request",transport:"xhr",method:a.method,url:a.url,path:a.path};a.requestBody=s&&typeof R[0]=="string"?L(R[0],I,f):void 0;let Y=()=>{a.outcome===void 0&&(a.outcome="abort")},Q=()=>{a.outcome===void 0&&(a.outcome="timeout")},v=()=>{a.outcome===void 0&&(a.outcome="error")},E=()=>{var X;C();try{if(!O||!p||a.reported||!a.requestId)return;a.reported=!0;let W={direction:"response",transport:"xhr",method:a.method,url:a.url,path:a.path},te=this.status,se={requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,status:te,ok:te>=200&&te<300,outcome:(X=a.outcome)!=null?X:"load",durationMs:a.startedAt!==void 0?Date.now()-a.startedAt:void 0,responseUrl:this.responseURL||void 0,requestBody:a.requestBody,responseBody:B?Ne(this,qe=>L(qe,W,A)):void 0};a.requestEmitted?k(se):a.pendingExchange=se}catch(W){o.log("xhr exchange observation failed",W)}finally{x.get(this)===a&&x.delete(this)}},V=()=>{try{this.readyState===XMLHttpRequest.DONE&&this.status!==0&&E()}catch(X){o.log("xhr ready-state observation failed",X)}},U=()=>E();C=()=>{for(let[X,W]of[["readystatechange",V],["abort",Y],["timeout",Q],["error",v],["loadend",U]])this.removeEventListener(X,W);a.cleanupListeners===C&&(a.cleanupListeners=void 0),r.delete(C)},this.addEventListener("readystatechange",V),this.addEventListener("abort",Y),this.addEventListener("timeout",Q),this.addEventListener("error",v),this.addEventListener("loadend",U),a.cleanupListeners=C,r.add(C),a.startedAt=Date.now(),M=!0}catch(I){o.log("xhr send observation failed",I),C()}let H;try{H=Reflect.apply(q,this,R)}catch(I){throw C(),I}if(M&&a.requestId!==void 0&&a.startedAt!==void 0){a.requestEmitted=!0,D({requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,startedAt:a.startedAt,requestBody:a.requestBody});let I=a.pendingExchange;a.pendingExchange=void 0,I&&k(I)}return H}}.send;return K(w,u),K(m,q),g.writable!==!0||l.writable!==!0?(o.log("xhr capture unavailable: XMLHttpRequest methods are not writable"),null):(Object.defineProperty(d,"open",{...g,value:w}),Object.defineProperty(d,"send",{...l,value:m}),p=!0,()=>{p=!1;for(let R of[...r])R();G(d,"open",w,g,o),G(d,"send",m,l,o)})},j=()=>{let d=globalThis,g=Object.getOwnPropertyDescriptor(d,"fetch");if(!g||!("value"in g))return o.log("fetch capture unavailable: fetch is not an own data property"),null;let l=g.value;if(typeof l!="function")return o.log("fetch capture unavailable: fetch missing"),null;if(_(l))return o.log("fetch capture unavailable: an equivalent capture is already active"),null;let u=!1,q=async(r,p,w,m)=>{try{if(!O||!u){ie(w);return}let[R,a]=await Promise.all([m!=null?m:Promise.resolve(void 0),w?ye(w,o):Promise.resolve(void 0)]);if(!O||!u)return;let C={direction:"request",transport:"fetch",method:r.method,url:r.url,path:r.path},M={...C,direction:"response"},H=r.requestBody;H===void 0&&R!==void 0&&(H=L(R,C,f));let I=a!==void 0?L(a,M,A):void 0;k({requestId:r.requestId,transport:"fetch",method:r.method,url:r.url,path:r.path,status:p.status,ok:p.ok,outcome:"load",durationMs:Date.now()-r.startedAt,responseUrl:p.url||void 0,requestBody:H,responseBody:I})}catch(R){o.log("fetch exchange observation failed",R)}},x={fetch(...r){var H,I,Y,Q;let p;try{let v=r[0],E=r[1];if(O&&u&&s&&typeof Request!="undefined"&&v instanceof Request&&(E==null?void 0:E.body)===void 0&&v.body){let V=String((H=E==null?void 0:E.method)!=null?H:v.method).toUpperCase(),U=(I=v.headers.get("content-type"))!=null?I:"";S(v.url,V)&&he(U)&&(p=v.clone())}}catch(v){o.log("fetch observation failed",v)}let w,m=Date.now();try{w=Reflect.apply(l,this,r)}catch(v){throw ie(p),v}let R,a;try{if(O&&u){let v=r[0],E=r[1],V=typeof Request!="undefined"&&v instanceof Request,U=String((Y=E==null?void 0:E.method)!=null?Y:V?v.method:"GET").toUpperCase(),X=V?v.url:v,W=S(X,U);W&&(R={requestId:pe(),method:U,url:W.url,path:W.path,startedAt:m},a=(Q=E==null?void 0:E.signal)!=null?Q:V?v.signal:void 0,s&&typeof(E==null?void 0:E.body)=="string"&&(R.requestBody=L(E.body,{direction:"request",transport:"fetch",method:U,url:W.url,path:W.path},f)))}}catch(v){o.log("fetch observation failed",v)}if(!R)return ie(p),w;let C=R;D({requestId:C.requestId,transport:"fetch",method:C.method,url:C.url,path:C.path,startedAt:C.startedAt,requestBody:C.requestBody});let M=p?ye(p,o):void 0;return w.then(v=>{var V;let E;try{if(O&&u&&B){let U=(V=v.headers.get("content-type"))!=null?V:"";he(U)&&v.body&&(E=v.clone())}}catch{}q(C,v,E,M)},v=>{try{if(!O||!u)return;let E=(a==null?void 0:a.aborted)===!0||(v==null?void 0:v.name)==="AbortError"||typeof DOMException!="undefined"&&v instanceof DOMException&&v.code===DOMException.ABORT_ERR;k({requestId:C.requestId,transport:"fetch",method:C.method,url:C.url,path:C.path,status:0,ok:!1,outcome:E?"abort":"error",durationMs:Date.now()-C.startedAt})}catch(E){o.log("fetch failure observation failed",E)}}),w}}.fetch;return K(x,l),g.writable!==!0?(o.log("fetch capture unavailable: fetch is not writable"),null):(Object.defineProperty(d,"fetch",{...g,value:x}),u=!0,()=>{u=!1,G(d,"fetch",x,g,o)})},c=[];if(y.includes("xhr")){let d=P();d&&c.push(d)}if(y.includes("fetch")){let d=j();d&&c.push(d)}return c.length===0?N():(O=!0,{mode:"standard",disconnect:()=>{O=!1;for(let d of c.splice(0))d()}})}function be(e){let t=e.onNavigate;if(typeof t!="function")throw new TypeError("captureNavigation requires an onNavigate callback");let n=F(e.logger),i,o,y,f,A,s;try{if(i=window,o=i==null?void 0:i.history,!i||!o)return n.log("navigation capture unavailable: window/history missing"),N();if(A=me(o,"pushState"),s=me(o,"replaceState"),!A||!s)return n.log("navigation capture unavailable: history method descriptors missing"),N();if(y=A.descriptor.value,f=s.descriptor.value,typeof y!="function"||typeof f!="function")return n.log("navigation capture unavailable: history methods missing"),N();if(typeof i.addEventListener!="function"||typeof i.removeEventListener!="function")return n.log("navigation capture unavailable: window event methods missing"),N()}catch(h){return n.log("navigation capture unavailable: history inspection failed",h),N()}if(_(y)||_(f))return n.log("navigation capture unavailable: an equivalent capture is already active"),N();let B=!1,O=()=>({path:i.location.pathname,search:i.location.search,hash:i.location.hash}),k;try{k=O()}catch(h){return n.log("navigation capture unavailable: location inspection failed",h),N()}let D=J(n,"navigation",h=>{if(B)return t(h)}),L=h=>{if(B)try{let b=O();if(b.path===k.path&&b.search===k.search&&b.hash===k.hash)return;k=b,D({...b,source:h})}catch(b){n.log("navigation observation failed",b)}},S={pushState(...h){let b=Reflect.apply(y,this,h);return L("push"),b}}.pushState,P={replaceState(...h){let b=Reflect.apply(f,this,h);return L("replace"),b}}.replaceState;K(S,y),K(P,f);let j=()=>L("pop"),c=()=>L("hash");try{if(ve(A,S),ve(s,P),o.pushState!==S||o.replaceState!==P)throw new Error("history method replacement did not take effect");i.addEventListener("popstate",j),i.addEventListener("hashchange",c),B=!0}catch(h){return B=!1,ee(i,"popstate",j,n),ee(i,"hashchange",c,n),Z(s,P,n),Z(A,S,n),n.log("navigation capture unavailable: history methods are not writable",h),t=()=>{},D=()=>{},n=F(),N()}return{mode:"standard",disconnect:()=>{B=!1,t=()=>{},ee(i,"popstate",j,n),ee(i,"hashchange",c,n),Z(A,S,n),Z(s,P,n),D=()=>{},n=F()}}}function me(e,t){let n=e;for(;n;){let i=Object.getOwnPropertyDescriptor(n,t);if(i)return!("value"in i)||typeof i.value!="function"?null:{owner:n,key:t,descriptor:i};n=Object.getPrototypeOf(n)}return null}function ve(e,t){if(e.descriptor.writable!==!0)throw new TypeError(`${e.key} is not writable`);let n=Object.getOwnPropertyDescriptor(e.owner,e.key);if(!re(n,e.descriptor))throw new Error(`${e.key} changed during installation`);Object.defineProperty(e.owner,e.key,{...e.descriptor,value:t})}function Z(e,t,n){G(e.owner,e.key,t,e.descriptor,n,`navigation ${e.key}`)}function ee(e,t,n,i){try{e.removeEventListener(t,n)}catch(o){i.log(`navigation ${t} listener removal skipped`,o)}}function we(e){let t=e.composedPath();return t.length>0?t:e.target?[e.target]:[]}var Re="1.1.0";var je=["valueMissing","typeMismatch","patternMismatch","tooShort","tooLong","rangeUnderflow","rangeOverflow","stepMismatch","badInput","customError"];function ae(e){return je.find(t=>e.validity[t])}function Ce(e){if(!(e!=null&&e.isConnected)||!e.getClientRects().length)return!1;let t=e.ownerDocument.defaultView;if(!t)return!1;for(let n=e;n;n=n.parentElement){let i=t.getComputedStyle(n);if(n.hasAttribute("hidden")||i.display==="none"||i.visibility==="hidden"||i.visibility==="collapse"||i.opacity==="0")return!1}return!0}function Ee(e){var q,x;if(typeof e.readValidation!="function"||typeof e.onError!="function")throw new TypeError("captureInputValidation requires readValidation and onError callbacks");let{form:t}=e,n=[...e.fields],i=(q=e.maxObservationMs)!=null?q:1e4;if(!n.length||!Number.isFinite(i)||i<=0)throw new TypeError("captureInputValidation requires fields and a positive maxObservationMs");let o={mode:"unavailable",disconnect(){},beginAttempt:()=>{},requestStarted(){},refresh(){}},y=(x=t==null?void 0:t.ownerDocument)==null?void 0:x.defaultView;if(!y||!n.every(r=>r.form===t))return o;let f=!0,A=0,s,B=!1,O,k,D,L,S=[],P=()=>t.isConnected&&n.every(r=>r.isConnected&&r.form===t),j=()=>{try{let r=e.readValidation();if(r&&["clear","pending","unknown"].includes(r.status)||(r==null?void 0:r.status)==="invalid"&&typeof r.code=="string"&&["constraint","application"].includes(r.source))return r}catch{}return{status:"unknown"}},c=r=>r.status==="invalid"?JSON.stringify([r.code,r.fieldIndex]):void 0,h=()=>{s=void 0,clearTimeout(k),clearTimeout(D),k=D=void 0},b=()=>{k=void 0;let r=s;if(!f||!(r!=null&&r.confirmed))return;if(!P()){h();return}let p=r.nativeInvalid?(()=>{for(let[m,R]of n.entries()){let a=ae(R);if(a)return{status:"invalid",source:"constraint",code:a,fieldIndex:m}}return{status:"clear"}})():j();if(p.status==="clear"){r.serverBaseline=void 0;return}if(p.status!=="invalid"||p.source==="application"&&r.serverBaseline===c(p))return;let w={attemptId:r.id,startedAt:r.startedAt,timestamp:Date.now(),code:p.code,...p.fieldIndex===void 0?{}:{fieldIndex:p.fieldIndex}};h(),B=!1;try{Promise.resolve(e.onError(w)).catch(()=>{})}catch{}},T=()=>{!f||!s||k!==void 0||(k=setTimeout(b,0))},d=r=>{if(!f||!P())return;h();let p=B?c(j()):void 0;return s={id:++A,startedAt:Date.now(),confirmed:r,nativeInvalid:!1,serverBaseline:p},D=setTimeout(h,i),T(),s.id},g=()=>{O===void 0&&(O=d(!1),L=setTimeout(()=>{s&&s.id===O&&!s.confirmed&&h(),O=void 0},0))},l=(r,p,w)=>{r.addEventListener(p,w,!0),S.push(()=>r.removeEventListener(p,w,!0))},u={mode:"standard",beginAttempt:()=>d(!0),refresh:T,requestStarted(r={}){f&&(r.attemptId!==void 0&&r.attemptId!==(s==null?void 0:s.id)||s&&r.timestamp!==void 0&&r.timestamp<s.startedAt||(h(),B=!0))},disconnect(){if(f){f=!1,h(),clearTimeout(L);for(let r of S.splice(0))r()}}};try{let r=w=>{var a;let m=w.target,R=(a=m==null?void 0:m.closest)==null?void 0:a.call(m,"button,input");(R==null?void 0:R.form)===t&&!R.disabled&&["submit","image"].includes(R.type)&&g()};l(t.ownerDocument,"click",r),l(t,"click",r),l(t,"keydown",w=>{let m=w;m.key==="Enter"&&!m.isComposing&&!m.defaultPrevented&&n.includes(m.target)&&g()}),l(t,"submit",()=>{(s==null?void 0:s.id)===O&&s?(s.confirmed=!0,T()):d(!0),O=void 0}),l(t,"invalid",w=>{!s||!n.includes(w.target)||(s.confirmed=!0,s.nativeInvalid=!0,T())}),l(t,"input",w=>{n.includes(w.target)&&h()});let p=new y.MutationObserver(T);p.observe(t,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),S.push(()=>p.disconnect())}catch{return u.disconnect(),o}return u}var $=require("@corbado/observe");0&&(module.exports={VERSION,captureInputValidation,captureNavigation,captureNetwork,captureWebAuthn,composedPath,inputValidationCode,isValidationMessageVisible,sanitizeAssertionResponse,sanitizeCreationOptions,sanitizeCreationResponse,sanitizeRequestOptions});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{sanitizeCreationOptions as ge,sanitizeCreationResponse as me,sanitizeRequestOptions as ve,sanitizeAssertionResponse as be}from"@corbado/observe";var ye={log:()=>{}};function F(e){return e?{log:(...t)=>{try{let n=e.log(...t);if(n&&(typeof n=="object"||typeof n=="function"))try{Promise.resolve(n).catch(()=>{})}catch{}}catch{}}}:ye}var oe=Symbol.for("corbado.autocapture.installed");function _(e){try{return typeof e=="function"&&Object.prototype.hasOwnProperty.call(e,oe)}catch{return!1}}function K(e,t){var a,i;let n=t;try{Object.defineProperty(e,oe,{value:t,configurable:!0})}catch{}try{Object.defineProperty(e,"name",{value:(a=n.name)!=null?a:"",configurable:!0})}catch{}try{Object.defineProperty(e,"length",{value:(i=n.length)!=null?i:0,configurable:!0})}catch{}return e}function N(){return{mode:"unavailable",disconnect:()=>{}}}function ee(e,t){return!!e&&"value"in e&&"value"in t&&e.value===t.value&&e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable}function $(e,t,n,a,i,y=String(t)){try{let f=Object.getOwnPropertyDescriptor(e,t);ee(f,{...a,value:n})&&Object.defineProperty(e,t,a)}catch(f){i.log(`${y} restoration skipped`,f)}}function z(e,t,n){let a=F(e);return i=>{try{let y=n(i);if(y&&(typeof y=="object"||typeof y=="function"))try{Promise.resolve(y).catch(f=>a.log(`${t} listener failed`,f))}catch(f){a.log(`${t} listener failed`,f)}}catch(y){a.log(`${t} listener failed`,y)}}}var ie=e=>({get:e("get"),create:e("create")});function we(e){let t=e.onEvent;if(typeof t!="function")throw new TypeError("captureWebAuthn requires an onEvent callback");let n=F(e.logger),a=c=>(n.log(`webauthn capture unavailable: ${c}`),{...N(),surface:"none"}),i=typeof navigator=="undefined"?void 0:navigator,y=i==null?void 0:i.credentials;if(!i||!y)return a("navigator.credentials missing");let f=y,A=ie(c=>f[c]);if(typeof A.get!="function"||typeof A.create!="function")return a("credentials methods missing");if(_(A.get)||_(A.create))return a("an equivalent capture is already active");let s=!1,B=0,O=z(n,"webauthn",t),k=(c,h,b)=>{let T={invoke(...d){let g=d[0];if(!s||b!=null&&b()||!te(g)||!te(g.publicKey))return h(this,d);let l=g.publicKey,u=`wa-${++B}`,q=h(this,d),x=te(g.signal)?g.signal:void 0,r=Re(c,g,l),p=m=>{s&&O({...r,ceremonyId:u,...m()})},w=()=>(x==null?void 0:x.aborted)===!0?{aborted:!0}:{};return p(()=>({phase:"started",userActivation:qe(i),...r.kind==="authentication"?{requestOptionsJson:ve(l)}:{creationOptionsJson:ge(l,e.identifierProjectors)}})),Promise.resolve(q).then(m=>(p(()=>({phase:"completed",credentialJson:c==="create"?me(m,e.identifierProjectors):be(m,e.identifierProjectors),...w()})),m),m=>{throw p(()=>({phase:"failed",error:m,errorName:Oe(m),...w()})),m})}}.invoke;return K(T,{name:c,length:0})},D=c=>{var T;let h=k(c,(d,g)=>Reflect.apply(A[c],d,g)),b=Object.getOwnPropertyDescriptor(y,c);if(b&&(!("value"in b)||b.writable!==!0))return null;try{f[c]=h}catch{return null}if(((T=Object.getOwnPropertyDescriptor(y,c))==null?void 0:T.value)!==h){try{f[c]=A[c]}catch{}return null}return()=>{f[c]===h&&(b?f[c]=b.value:delete f[c])}},L=()=>{let c=ie(()=>new WeakMap),h=(l,u)=>{let q=c[l].get(u);if(q)return q;let x=k(l,(r,p)=>Reflect.apply(u,y,p),()=>{try{let r=f[l];return r!==u&&r!==x}catch(r){return n.log("suppress check failed; ceremony unreported",r),!0}});return c[l].set(u,x),x},b=l=>{let u=Object.getOwnPropertyDescriptor(y,l);return u?u.configurable===!0||!("value"in u)||u.writable===!0:!0},T=new WeakMap,d=new Proxy(y,{get(l,u){let q=Reflect.get(y,u,y);if((u==="get"||u==="create")&&b(u))return typeof q!="function"||_(q)?q:h(u,q);if(typeof q!="function"||!b(u)||u==="constructor")return q;let x=T.get(q);if(x)return x;let r=q.bind(y);return T.set(q,r),r},set(l,u,q){return Reflect.set(y,u,q,y)}}),g=Object.getOwnPropertyDescriptor(i,"credentials");if(g&&g.configurable!==!0)return null;try{Object.defineProperty(i,"credentials",{value:d,writable:!0,enumerable:!0,configurable:!0})}catch{return null}return i.credentials!==d?null:()=>{i.credentials===d&&(g?Object.defineProperty(i,"credentials",g):delete i.credentials)}},S=(c,h)=>(s=!0,{mode:"standard",surface:c,disconnect:()=>{s=!1,h()}}),P=D("get"),j=P?D("create"):null;if(P&&j)return S("methods",()=>{P(),j()});if(P==null||P(),e.attach==="container"){let c=L();if(c)return n.log("webauthn capture attached at the credentials container"),S("container",c)}return a("credentials methods cannot be patched safely")}function Re(e,t,n){let a=Ce(t.mediation);if(e==="create")return{kind:"registration",mediation:a};let i=n;return{kind:"authentication",mediation:a,uiMode:Ee(t.uiMode),credentialSet:Array.isArray(i.allowCredentials)&&i.allowCredentials.length>0?"allowlisted":"discoverable"}}function Ce(e){return e===void 0?"optional":e==="silent"||e==="optional"||e==="conditional"||e==="required"?e:"unknown"}function Ee(e){return e===void 0?"default":e==="immediate"?"immediate":"unknown"}function qe(e){let t=e.userActivation;return typeof(t==null?void 0:t.isActive)=="boolean"?t.isActive:void 0}function te(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function Oe(e){return e instanceof DOMException?e.name:"UnknownError"}var ae=0;function se(){return ae+=1,`network-${ae}`}function xe(e,t){let n=e.responseType;if(n===""||n==="text")return t(e.responseText);if(n==="json"){let a=e.response;return a==null?void 0:t(a)}}var Ae=500,ue=Symbol("body-read-timeout");function de(e){return/event-stream|octet-stream/i.test(e)?!1:/json|text|urlencoded/i.test(e)}async function ce(e,t){let n=e.body;if(!n)return;let a=n.getReader(),i;try{let y=new Promise(s=>{i=setTimeout(()=>s(ue),Ae)}),f=new TextDecoder,A=[];for(;;){let s=await Promise.race([a.read(),y]);if(s===ue){t.log("body omitted: read timed out"),a.cancel().catch(()=>{});return}if(s.done)break;A.push(f.decode(s.value,{stream:!0}))}return A.push(f.decode()),A.join("")}catch{a.cancel().catch(()=>{});return}finally{i!==void 0&&clearTimeout(i)}}function ne(e){var t;(t=e==null?void 0:e.body)==null||t.cancel().catch(()=>{})}function ke(e){var h,b,T;let{onExchange:t,onRequest:n,match:a}=e;if(typeof t!="function"||typeof a!="function")throw new TypeError("captureNetwork requires onExchange and match callbacks");let i=F(e.logger),y=(h=e.transports)!=null?h:["xhr","fetch"],f=(b=e.bodyCapture)==null?void 0:b.request,A=(T=e.bodyCapture)==null?void 0:T.response,s=typeof f=="function",B=typeof A=="function",O=!1,k=z(i,"network",d=>{if(O)return t(d)}),D=z(i,"network request",d=>{if(O)return n==null?void 0:n(d)}),L=(d,g,l)=>{if(typeof l=="function")try{return l(d,g)}catch(u){i.log("body projection failed",u);return}},S=(d,g)=>{try{let l=typeof document!="undefined"?document.baseURI:void 0,u=new URL(String(d),l);return a(u,g)===!0?{url:u.href,path:u.pathname}:void 0}catch{return}},P=()=>{if(typeof XMLHttpRequest=="undefined")return i.log("xhr capture unavailable: XMLHttpRequest missing"),null;let d=XMLHttpRequest.prototype,g=Object.getOwnPropertyDescriptor(d,"open"),l=Object.getOwnPropertyDescriptor(d,"send");if(!g||!("value"in g)||typeof g.value!="function"||!l||!("value"in l)||typeof l.value!="function")return i.log("xhr capture unavailable: XMLHttpRequest methods missing"),null;let u=g.value,q=l.value;if(_(u)||_(q))return i.log("xhr capture unavailable: an equivalent capture is already active"),null;let x=new WeakMap,r=new Set,p=!1,w={open(...R){var C;let o=Reflect.apply(u,this,R);if(!O||!p)return o;try{let M=x.get(this);M&&(M.reported=!0,(C=M.cleanupListeners)==null||C.call(M));let H=String(R[0]).toUpperCase(),I=S(R[1],H);I?x.set(this,{method:H,url:I.url,path:I.path,reported:!1}):x.delete(this)}catch(M){i.log("xhr open observation failed",M)}return o}}.open,m={send(...R){let o=O&&p?x.get(this):void 0;if(!o||o.reported||o.cleanupListeners)return Reflect.apply(q,this,R);let C=()=>{},M=!1;try{o.requestId=se();let I={direction:"request",transport:"xhr",method:o.method,url:o.url,path:o.path};o.requestBody=s&&typeof R[0]=="string"?L(R[0],I,f):void 0;let J=()=>{o.outcome===void 0&&(o.outcome="abort")},G=()=>{o.outcome===void 0&&(o.outcome="timeout")},v=()=>{o.outcome===void 0&&(o.outcome="error")},E=()=>{var X;C();try{if(!O||!p||o.reported||!o.requestId)return;o.reported=!0;let W={direction:"response",transport:"xhr",method:o.method,url:o.url,path:o.path},Z=this.status,re={requestId:o.requestId,transport:"xhr",method:o.method,url:o.url,path:o.path,status:Z,ok:Z>=200&&Z<300,outcome:(X=o.outcome)!=null?X:"load",durationMs:o.startedAt!==void 0?Date.now()-o.startedAt:void 0,responseUrl:this.responseURL||void 0,requestBody:o.requestBody,responseBody:B?xe(this,he=>L(he,W,A)):void 0};o.requestEmitted?k(re):o.pendingExchange=re}catch(W){i.log("xhr exchange observation failed",W)}finally{x.get(this)===o&&x.delete(this)}},V=()=>{try{this.readyState===XMLHttpRequest.DONE&&this.status!==0&&E()}catch(X){i.log("xhr ready-state observation failed",X)}},U=()=>E();C=()=>{for(let[X,W]of[["readystatechange",V],["abort",J],["timeout",G],["error",v],["loadend",U]])this.removeEventListener(X,W);o.cleanupListeners===C&&(o.cleanupListeners=void 0),r.delete(C)},this.addEventListener("readystatechange",V),this.addEventListener("abort",J),this.addEventListener("timeout",G),this.addEventListener("error",v),this.addEventListener("loadend",U),o.cleanupListeners=C,r.add(C),o.startedAt=Date.now(),M=!0}catch(I){i.log("xhr send observation failed",I),C()}let H;try{H=Reflect.apply(q,this,R)}catch(I){throw C(),I}if(M&&o.requestId!==void 0&&o.startedAt!==void 0){o.requestEmitted=!0,D({requestId:o.requestId,transport:"xhr",method:o.method,url:o.url,path:o.path,startedAt:o.startedAt,requestBody:o.requestBody});let I=o.pendingExchange;o.pendingExchange=void 0,I&&k(I)}return H}}.send;return K(w,u),K(m,q),g.writable!==!0||l.writable!==!0?(i.log("xhr capture unavailable: XMLHttpRequest methods are not writable"),null):(Object.defineProperty(d,"open",{...g,value:w}),Object.defineProperty(d,"send",{...l,value:m}),p=!0,()=>{p=!1;for(let R of[...r])R();$(d,"open",w,g,i),$(d,"send",m,l,i)})},j=()=>{let d=globalThis,g=Object.getOwnPropertyDescriptor(d,"fetch");if(!g||!("value"in g))return i.log("fetch capture unavailable: fetch is not an own data property"),null;let l=g.value;if(typeof l!="function")return i.log("fetch capture unavailable: fetch missing"),null;if(_(l))return i.log("fetch capture unavailable: an equivalent capture is already active"),null;let u=!1,q=async(r,p,w,m)=>{try{if(!O||!u){ne(w);return}let[R,o]=await Promise.all([m!=null?m:Promise.resolve(void 0),w?ce(w,i):Promise.resolve(void 0)]);if(!O||!u)return;let C={direction:"request",transport:"fetch",method:r.method,url:r.url,path:r.path},M={...C,direction:"response"},H=r.requestBody;H===void 0&&R!==void 0&&(H=L(R,C,f));let I=o!==void 0?L(o,M,A):void 0;k({requestId:r.requestId,transport:"fetch",method:r.method,url:r.url,path:r.path,status:p.status,ok:p.ok,outcome:"load",durationMs:Date.now()-r.startedAt,responseUrl:p.url||void 0,requestBody:H,responseBody:I})}catch(R){i.log("fetch exchange observation failed",R)}},x={fetch(...r){var H,I,J,G;let p;try{let v=r[0],E=r[1];if(O&&u&&s&&typeof Request!="undefined"&&v instanceof Request&&(E==null?void 0:E.body)===void 0&&v.body){let V=String((H=E==null?void 0:E.method)!=null?H:v.method).toUpperCase(),U=(I=v.headers.get("content-type"))!=null?I:"";S(v.url,V)&&de(U)&&(p=v.clone())}}catch(v){i.log("fetch observation failed",v)}let w,m=Date.now();try{w=Reflect.apply(l,this,r)}catch(v){throw ne(p),v}let R,o;try{if(O&&u){let v=r[0],E=r[1],V=typeof Request!="undefined"&&v instanceof Request,U=String((J=E==null?void 0:E.method)!=null?J:V?v.method:"GET").toUpperCase(),X=V?v.url:v,W=S(X,U);W&&(R={requestId:se(),method:U,url:W.url,path:W.path,startedAt:m},o=(G=E==null?void 0:E.signal)!=null?G:V?v.signal:void 0,s&&typeof(E==null?void 0:E.body)=="string"&&(R.requestBody=L(E.body,{direction:"request",transport:"fetch",method:U,url:W.url,path:W.path},f)))}}catch(v){i.log("fetch observation failed",v)}if(!R)return ne(p),w;let C=R;D({requestId:C.requestId,transport:"fetch",method:C.method,url:C.url,path:C.path,startedAt:C.startedAt,requestBody:C.requestBody});let M=p?ce(p,i):void 0;return w.then(v=>{var V;let E;try{if(O&&u&&B){let U=(V=v.headers.get("content-type"))!=null?V:"";de(U)&&v.body&&(E=v.clone())}}catch{}q(C,v,E,M)},v=>{try{if(!O||!u)return;let E=(o==null?void 0:o.aborted)===!0||(v==null?void 0:v.name)==="AbortError"||typeof DOMException!="undefined"&&v instanceof DOMException&&v.code===DOMException.ABORT_ERR;k({requestId:C.requestId,transport:"fetch",method:C.method,url:C.url,path:C.path,status:0,ok:!1,outcome:E?"abort":"error",durationMs:Date.now()-C.startedAt})}catch(E){i.log("fetch failure observation failed",E)}}),w}}.fetch;return K(x,l),g.writable!==!0?(i.log("fetch capture unavailable: fetch is not writable"),null):(Object.defineProperty(d,"fetch",{...g,value:x}),u=!0,()=>{u=!1,$(d,"fetch",x,g,i)})},c=[];if(y.includes("xhr")){let d=P();d&&c.push(d)}if(y.includes("fetch")){let d=j();d&&c.push(d)}return c.length===0?N():(O=!0,{mode:"standard",disconnect:()=>{O=!1;for(let d of c.splice(0))d()}})}function Pe(e){let t=e.onNavigate;if(typeof t!="function")throw new TypeError("captureNavigation requires an onNavigate callback");let n=F(e.logger),a,i,y,f,A,s;try{if(a=window,i=a==null?void 0:a.history,!a||!i)return n.log("navigation capture unavailable: window/history missing"),N();if(A=le(i,"pushState"),s=le(i,"replaceState"),!A||!s)return n.log("navigation capture unavailable: history method descriptors missing"),N();if(y=A.descriptor.value,f=s.descriptor.value,typeof y!="function"||typeof f!="function")return n.log("navigation capture unavailable: history methods missing"),N();if(typeof a.addEventListener!="function"||typeof a.removeEventListener!="function")return n.log("navigation capture unavailable: window event methods missing"),N()}catch(h){return n.log("navigation capture unavailable: history inspection failed",h),N()}if(_(y)||_(f))return n.log("navigation capture unavailable: an equivalent capture is already active"),N();let B=!1,O=()=>({path:a.location.pathname,search:a.location.search,hash:a.location.hash}),k;try{k=O()}catch(h){return n.log("navigation capture unavailable: location inspection failed",h),N()}let D=z(n,"navigation",h=>{if(B)return t(h)}),L=h=>{if(B)try{let b=O();if(b.path===k.path&&b.search===k.search&&b.hash===k.hash)return;k=b,D({...b,source:h})}catch(b){n.log("navigation observation failed",b)}},S={pushState(...h){let b=Reflect.apply(y,this,h);return L("push"),b}}.pushState,P={replaceState(...h){let b=Reflect.apply(f,this,h);return L("replace"),b}}.replaceState;K(S,y),K(P,f);let j=()=>L("pop"),c=()=>L("hash");try{if(pe(A,S),pe(s,P),i.pushState!==S||i.replaceState!==P)throw new Error("history method replacement did not take effect");a.addEventListener("popstate",j),a.addEventListener("hashchange",c),B=!0}catch(h){return B=!1,Q(a,"popstate",j,n),Q(a,"hashchange",c,n),Y(s,P,n),Y(A,S,n),n.log("navigation capture unavailable: history methods are not writable",h),t=()=>{},D=()=>{},n=F(),N()}return{mode:"standard",disconnect:()=>{B=!1,t=()=>{},Q(a,"popstate",j,n),Q(a,"hashchange",c,n),Y(A,S,n),Y(s,P,n),D=()=>{},n=F()}}}function le(e,t){let n=e;for(;n;){let a=Object.getOwnPropertyDescriptor(n,t);if(a)return!("value"in a)||typeof a.value!="function"?null:{owner:n,key:t,descriptor:a};n=Object.getPrototypeOf(n)}return null}function pe(e,t){if(e.descriptor.writable!==!0)throw new TypeError(`${e.key} is not writable`);let n=Object.getOwnPropertyDescriptor(e.owner,e.key);if(!ee(n,e.descriptor))throw new Error(`${e.key} changed during installation`);Object.defineProperty(e.owner,e.key,{...e.descriptor,value:t})}function Y(e,t,n){$(e.owner,e.key,t,e.descriptor,n,`navigation ${e.key}`)}function Q(e,t,n,a){try{e.removeEventListener(t,n)}catch(i){a.log(`navigation ${t} listener removal skipped`,i)}}function Ie(e){let t=e.composedPath();return t.length>0?t:e.target?[e.target]:[]}var Se="1.0.1";var Te=["valueMissing","typeMismatch","patternMismatch","tooShort","tooLong","rangeUnderflow","rangeOverflow","stepMismatch","badInput","customError"];function fe(e){return Te.find(t=>e.validity[t])}function Le(e){if(!(e!=null&&e.isConnected)||!e.getClientRects().length)return!1;let t=e.ownerDocument.defaultView;if(!t)return!1;for(let n=e;n;n=n.parentElement){let a=t.getComputedStyle(n);if(n.hasAttribute("hidden")||a.display==="none"||a.visibility==="hidden"||a.visibility==="collapse"||a.opacity==="0")return!1}return!0}function Be(e){var q,x;if(typeof e.readValidation!="function"||typeof e.onError!="function")throw new TypeError("captureInputValidation requires readValidation and onError callbacks");let{form:t}=e,n=[...e.fields],a=(q=e.maxObservationMs)!=null?q:1e4;if(!n.length||!Number.isFinite(a)||a<=0)throw new TypeError("captureInputValidation requires fields and a positive maxObservationMs");let i={mode:"unavailable",disconnect(){},beginAttempt:()=>{},requestStarted(){},refresh(){}},y=(x=t==null?void 0:t.ownerDocument)==null?void 0:x.defaultView;if(!y||!n.every(r=>r.form===t))return i;let f=!0,A=0,s,B=!1,O,k,D,L,S=[],P=()=>t.isConnected&&n.every(r=>r.isConnected&&r.form===t),j=()=>{try{let r=e.readValidation();if(r&&["clear","pending","unknown"].includes(r.status)||(r==null?void 0:r.status)==="invalid"&&typeof r.code=="string"&&["constraint","application"].includes(r.source))return r}catch{}return{status:"unknown"}},c=r=>r.status==="invalid"?JSON.stringify([r.code,r.fieldIndex]):void 0,h=()=>{s=void 0,clearTimeout(k),clearTimeout(D),k=D=void 0},b=()=>{k=void 0;let r=s;if(!f||!(r!=null&&r.confirmed))return;if(!P()){h();return}let p=r.nativeInvalid?(()=>{for(let[m,R]of n.entries()){let o=fe(R);if(o)return{status:"invalid",source:"constraint",code:o,fieldIndex:m}}return{status:"clear"}})():j();if(p.status==="clear"){r.serverBaseline=void 0;return}if(p.status!=="invalid"||p.source==="application"&&r.serverBaseline===c(p))return;let w={attemptId:r.id,startedAt:r.startedAt,timestamp:Date.now(),code:p.code,...p.fieldIndex===void 0?{}:{fieldIndex:p.fieldIndex}};h(),B=!1;try{Promise.resolve(e.onError(w)).catch(()=>{})}catch{}},T=()=>{!f||!s||k!==void 0||(k=setTimeout(b,0))},d=r=>{if(!f||!P())return;h();let p=B?c(j()):void 0;return s={id:++A,startedAt:Date.now(),confirmed:r,nativeInvalid:!1,serverBaseline:p},D=setTimeout(h,a),T(),s.id},g=()=>{O===void 0&&(O=d(!1),L=setTimeout(()=>{s&&s.id===O&&!s.confirmed&&h(),O=void 0},0))},l=(r,p,w)=>{r.addEventListener(p,w,!0),S.push(()=>r.removeEventListener(p,w,!0))},u={mode:"standard",beginAttempt:()=>d(!0),refresh:T,requestStarted(r={}){f&&(r.attemptId!==void 0&&r.attemptId!==(s==null?void 0:s.id)||s&&r.timestamp!==void 0&&r.timestamp<s.startedAt||(h(),B=!0))},disconnect(){if(f){f=!1,h(),clearTimeout(L);for(let r of S.splice(0))r()}}};try{let r=w=>{var o;let m=w.target,R=(o=m==null?void 0:m.closest)==null?void 0:o.call(m,"button,input");(R==null?void 0:R.form)===t&&!R.disabled&&["submit","image"].includes(R.type)&&g()};l(t.ownerDocument,"click",r),l(t,"click",r),l(t,"keydown",w=>{let m=w;m.key==="Enter"&&!m.isComposing&&!m.defaultPrevented&&n.includes(m.target)&&g()}),l(t,"submit",()=>{(s==null?void 0:s.id)===O&&s?(s.confirmed=!0,T()):d(!0),O=void 0}),l(t,"invalid",w=>{!s||!n.includes(w.target)||(s.confirmed=!0,s.nativeInvalid=!0,T())}),l(t,"input",w=>{n.includes(w.target)&&h()});let p=new y.MutationObserver(T);p.observe(t,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),S.push(()=>p.disconnect())}catch{return u.disconnect(),i}return u}import{sanitizeCreationOptions as et,sanitizeCreationResponse as tt,sanitizeRequestOptions as nt,sanitizeAssertionResponse as rt}from"@corbado/observe";export{Se as VERSION,Be as captureInputValidation,Pe as captureNavigation,ke as captureNetwork,we as captureWebAuthn,Ie as composedPath,fe as inputValidationCode,Le as isValidationMessageVisible,rt as sanitizeAssertionResponse,et as sanitizeCreationOptions,tt as sanitizeCreationResponse,nt as sanitizeRequestOptions};
1
+ import{a as H,b as R,c as N,d as L,e as j,f as D,g as F,h as z}from"./chunk-7E5QDUX5.mjs";import"./chunk-JR557W27.mjs";import{sanitizeCreationOptions as B,sanitizeCreationResponse as U,sanitizeRequestOptions as J,sanitizeAssertionResponse as _}from"@corbado/observe";var q=t=>({get:t("get"),create:t("create")});function $(t){let n=t.onEvent;if(typeof n!="function")throw new TypeError("captureWebAuthn requires an onEvent callback");let s=H(t.logger),f=r=>(s.log(`webauthn capture unavailable: ${r}`),{...L(),surface:"none"}),p=typeof navigator=="undefined"?void 0:navigator,b=p==null?void 0:p.credentials;if(!p||!b)return f("navigator.credentials missing");let h=b,I=q(r=>h[r]);if(typeof I.get!="function"||typeof I.create!="function")return f("credentials methods missing");if(R(I.get)||R(I.create))return f("an equivalent capture is already active");let i=!1,M=0,E=j(s,"webauthn",n),O=(r,d,v)=>{let g={invoke(...C){let m=C[0];if(!i||v!=null&&v()||!S(m)||!S(m.publicKey))return d(this,C);let c=m.publicKey,o=`wa-${++M}`,l=d(this,C),w=S(m.signal)?m.signal:void 0,e=Q(r,m,c),u=a=>{i&&E({...e,ceremonyId:o,...a()})},y=()=>(w==null?void 0:w.aborted)===!0?{aborted:!0}:{};return u(()=>({phase:"started",userActivation:Z(p),...e.kind==="authentication"?{requestOptionsJson:J(c)}:{creationOptionsJson:B(c,t.identifierProjectors)}})),Promise.resolve(l).then(a=>(u(()=>({phase:"completed",credentialJson:r==="create"?U(a,t.identifierProjectors):_(a,t.identifierProjectors),...y()})),a),a=>{throw u(()=>({phase:"failed",error:a,errorName:G(a),...y()})),a})}}.invoke;return N(g,{name:r,length:0})},k=r=>{var g;let d=O(r,(C,m)=>Reflect.apply(I[r],C,m)),v=Object.getOwnPropertyDescriptor(b,r);if(v&&(!("value"in v)||v.writable!==!0))return null;try{h[r]=d}catch{return null}if(((g=Object.getOwnPropertyDescriptor(b,r))==null?void 0:g.value)!==d){try{h[r]=I[r]}catch{}return null}return()=>{h[r]===d&&(v?h[r]=v.value:delete h[r])}},P=()=>{let r=q(()=>new WeakMap),d=(c,o)=>{let l=r[c].get(o);if(l)return l;let w=O(c,(e,u)=>Reflect.apply(o,b,u),()=>{try{let e=h[c];return e!==o&&e!==w}catch(e){return s.log("suppress check failed; ceremony unreported",e),!0}});return r[c].set(o,w),w},v=c=>{let o=Object.getOwnPropertyDescriptor(b,c);return o?o.configurable===!0||!("value"in o)||o.writable===!0:!0},g=new WeakMap,C=new Proxy(b,{get(c,o){let l=Reflect.get(b,o,b);if((o==="get"||o==="create")&&v(o))return typeof l!="function"||R(l)?l:d(o,l);if(typeof l!="function"||!v(o)||o==="constructor")return l;let w=g.get(l);if(w)return w;let e=l.bind(b);return g.set(l,e),e},set(c,o,l){return Reflect.set(b,o,l,b)}}),m=Object.getOwnPropertyDescriptor(p,"credentials");if(m&&m.configurable!==!0)return null;try{Object.defineProperty(p,"credentials",{value:C,writable:!0,enumerable:!0,configurable:!0})}catch{return null}return p.credentials!==C?null:()=>{p.credentials===C&&(m?Object.defineProperty(p,"credentials",m):delete p.credentials)}},T=(r,d)=>(i=!0,{mode:"standard",surface:r,disconnect:()=>{i=!1,d()}}),A=k("get"),V=A?k("create"):null;if(A&&V)return T("methods",()=>{A(),V()});if(A==null||A(),t.attach==="container"){let r=P();if(r)return s.log("webauthn capture attached at the credentials container"),T("container",r)}return f("credentials methods cannot be patched safely")}function Q(t,n,s){let f=X(n.mediation);if(t==="create")return{kind:"registration",mediation:f};let p=s;return{kind:"authentication",mediation:f,uiMode:Y(n.uiMode),credentialSet:Array.isArray(p.allowCredentials)&&p.allowCredentials.length>0?"allowlisted":"discoverable"}}function X(t){return t===void 0?"optional":t==="silent"||t==="optional"||t==="conditional"||t==="required"?t:"unknown"}function Y(t){return t===void 0?"default":t==="immediate"?"immediate":"unknown"}function Z(t){let n=t.userActivation;return typeof(n==null?void 0:n.isActive)=="boolean"?n.isActive:void 0}function S(t){return t!==null&&(typeof t=="object"||typeof t=="function")}function G(t){return t instanceof DOMException?t.name:"UnknownError"}function ee(t){let n=t.composedPath();return n.length>0?n:t.target?[t.target]:[]}var te=["valueMissing","typeMismatch","patternMismatch","tooShort","tooLong","rangeUnderflow","rangeOverflow","stepMismatch","badInput","customError"];function K(t){return te.find(n=>t.validity[n])}function ne(t){if(!(t!=null&&t.isConnected)||!t.getClientRects().length)return!1;let n=t.ownerDocument.defaultView;if(!n)return!1;for(let s=t;s;s=s.parentElement){let f=n.getComputedStyle(s);if(s.hasAttribute("hidden")||f.display==="none"||f.visibility==="hidden"||f.visibility==="collapse"||f.opacity==="0")return!1}return!0}function re(t){var l,w;if(typeof t.readValidation!="function"||typeof t.onError!="function")throw new TypeError("captureInputValidation requires readValidation and onError callbacks");let{form:n}=t,s=[...t.fields],f=(l=t.maxObservationMs)!=null?l:1e4;if(!s.length||!Number.isFinite(f)||f<=0)throw new TypeError("captureInputValidation requires fields and a positive maxObservationMs");let p={mode:"unavailable",disconnect(){},beginAttempt:()=>{},requestStarted(){},refresh(){}},b=(w=n==null?void 0:n.ownerDocument)==null?void 0:w.defaultView;if(!b||!s.every(e=>e.form===n))return p;let h=!0,I=0,i,M=!1,E,O,k,P,T=[],A=()=>n.isConnected&&s.every(e=>e.isConnected&&e.form===n),V=()=>{try{let e=t.readValidation();if(e&&["clear","pending","unknown"].includes(e.status)||(e==null?void 0:e.status)==="invalid"&&typeof e.code=="string"&&["constraint","application"].includes(e.source))return e}catch{}return{status:"unknown"}},r=e=>e.status==="invalid"?JSON.stringify([e.code,e.fieldIndex]):void 0,d=()=>{i=void 0,clearTimeout(O),clearTimeout(k),O=k=void 0},v=()=>{O=void 0;let e=i;if(!h||!(e!=null&&e.confirmed))return;if(!A()){d();return}let u=e.nativeInvalid?(()=>{for(let[a,x]of s.entries()){let W=K(x);if(W)return{status:"invalid",source:"constraint",code:W,fieldIndex:a}}return{status:"clear"}})():V();if(u.status==="clear"){e.serverBaseline=void 0;return}if(u.status!=="invalid"||u.source==="application"&&e.serverBaseline===r(u))return;let y={attemptId:e.id,startedAt:e.startedAt,timestamp:Date.now(),code:u.code,...u.fieldIndex===void 0?{}:{fieldIndex:u.fieldIndex}};d(),M=!1;try{Promise.resolve(t.onError(y)).catch(()=>{})}catch{}},g=()=>{!h||!i||O!==void 0||(O=setTimeout(v,0))},C=e=>{if(!h||!A())return;d();let u=M?r(V()):void 0;return i={id:++I,startedAt:Date.now(),confirmed:e,nativeInvalid:!1,serverBaseline:u},k=setTimeout(d,f),g(),i.id},m=()=>{E===void 0&&(E=C(!1),P=setTimeout(()=>{i&&i.id===E&&!i.confirmed&&d(),E=void 0},0))},c=(e,u,y)=>{e.addEventListener(u,y,!0),T.push(()=>e.removeEventListener(u,y,!0))},o={mode:"standard",beginAttempt:()=>C(!0),refresh:g,requestStarted(e={}){h&&(e.attemptId!==void 0&&e.attemptId!==(i==null?void 0:i.id)||i&&e.timestamp!==void 0&&e.timestamp<i.startedAt||(d(),M=!0))},disconnect(){if(h){h=!1,d(),clearTimeout(P);for(let e of T.splice(0))e()}}};try{let e=y=>{var W;let a=y.target,x=(W=a==null?void 0:a.closest)==null?void 0:W.call(a,"button,input");(x==null?void 0:x.form)===n&&!x.disabled&&["submit","image"].includes(x.type)&&m()};c(n.ownerDocument,"click",e),c(n,"click",e),c(n,"keydown",y=>{let a=y;a.key==="Enter"&&!a.isComposing&&!a.defaultPrevented&&s.includes(a.target)&&m()}),c(n,"submit",()=>{(i==null?void 0:i.id)===E&&i?(i.confirmed=!0,g()):C(!0),E=void 0}),c(n,"invalid",y=>{!i||!s.includes(y.target)||(i.confirmed=!0,i.nativeInvalid=!0,g())}),c(n,"input",y=>{s.includes(y.target)&&d()});let u=new b.MutationObserver(g);u.observe(n,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),T.push(()=>u.disconnect())}catch{return o.disconnect(),p}return o}import{sanitizeCreationOptions as he,sanitizeCreationResponse as ve,sanitizeRequestOptions as ge,sanitizeAssertionResponse as Ce}from"@corbado/observe";export{z as VERSION,re as captureInputValidation,F as captureNavigation,D as captureNetwork,$ as captureWebAuthn,ee as composedPath,K as inputValidationCode,ne as isValidationMessageVisible,Ce as sanitizeAssertionResponse,he as sanitizeCreationOptions,ve as sanitizeCreationResponse,ge as sanitizeRequestOptions};
@@ -0,0 +1,38 @@
1
+ import { P as ProbeConfig } from '../guards-C1SJi1-7.mjs';
2
+ export { E as applyGuards, F as createProbeTaint } from '../guards-C1SJi1-7.mjs';
3
+ import '../types-CXJAj2DU.mjs';
4
+ import '@corbado/observe';
5
+
6
+ type ProbeGuardFixtureInput = {
7
+ /** Exchange URL (also redacted as a URL). */
8
+ url?: string;
9
+ request?: unknown;
10
+ response?: unknown;
11
+ /** Free text (UI text, console / error message, client log line). */
12
+ text?: string;
13
+ /** Values typed into password / one-time-code fields before the item was captured. */
14
+ typed?: string[];
15
+ /** WebAuthn ceremony seen by the WebAuthn source. */
16
+ webauthn?: {
17
+ requestOptionsJson?: string;
18
+ creationOptionsJson?: string;
19
+ credentialJson?: string;
20
+ };
21
+ /** `document.cookie` at capture time. */
22
+ cookie?: string;
23
+ };
24
+ type ProbeGuardFixture = {
25
+ name: string;
26
+ input: ProbeGuardFixtureInput;
27
+ mustNotContain: string[];
28
+ };
29
+ /** Fixed inputs whose secrets must never appear in an emitted item. */
30
+ declare const probeGuardFixtures: ProbeGuardFixture[];
31
+ /**
32
+ * Runs a fixture through the engine's redaction paths (URL, request / response body, free text) at every
33
+ * level, under `config.rules`, followed by the always-on guards. Returns the emitted payloads (guard
34
+ * failures are dropped, as in the live engine). Used by the conformance suite.
35
+ */
36
+ declare function runProbeGuardFixture(config: ProbeConfig, fixture: ProbeGuardFixture): unknown[];
37
+
38
+ export { type ProbeGuardFixture, type ProbeGuardFixtureInput, probeGuardFixtures, runProbeGuardFixture };
@@ -0,0 +1,38 @@
1
+ import { P as ProbeConfig } from '../guards-wCMqiGRi.js';
2
+ export { E as applyGuards, F as createProbeTaint } from '../guards-wCMqiGRi.js';
3
+ import '../types-CXJAj2DU.js';
4
+ import '@corbado/observe';
5
+
6
+ type ProbeGuardFixtureInput = {
7
+ /** Exchange URL (also redacted as a URL). */
8
+ url?: string;
9
+ request?: unknown;
10
+ response?: unknown;
11
+ /** Free text (UI text, console / error message, client log line). */
12
+ text?: string;
13
+ /** Values typed into password / one-time-code fields before the item was captured. */
14
+ typed?: string[];
15
+ /** WebAuthn ceremony seen by the WebAuthn source. */
16
+ webauthn?: {
17
+ requestOptionsJson?: string;
18
+ creationOptionsJson?: string;
19
+ credentialJson?: string;
20
+ };
21
+ /** `document.cookie` at capture time. */
22
+ cookie?: string;
23
+ };
24
+ type ProbeGuardFixture = {
25
+ name: string;
26
+ input: ProbeGuardFixtureInput;
27
+ mustNotContain: string[];
28
+ };
29
+ /** Fixed inputs whose secrets must never appear in an emitted item. */
30
+ declare const probeGuardFixtures: ProbeGuardFixture[];
31
+ /**
32
+ * Runs a fixture through the engine's redaction paths (URL, request / response body, free text) at every
33
+ * level, under `config.rules`, followed by the always-on guards. Returns the emitted payloads (guard
34
+ * failures are dropped, as in the live engine). Used by the conformance suite.
35
+ */
36
+ declare function runProbeGuardFixture(config: ProbeConfig, fixture: ProbeGuardFixture): unknown[];
37
+
38
+ export { type ProbeGuardFixture, type ProbeGuardFixtureInput, probeGuardFixtures, runProbeGuardFixture };
@@ -0,0 +1 @@
1
+ "use strict";var M=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var lt=Object.prototype.hasOwnProperty;var ht=(n,t,e)=>t in n?M(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var gt=(n,t)=>{for(var e in t)M(n,e,{get:t[e],enumerable:!0})},mt=(n,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of pt(t))!lt.call(n,i)&&i!==e&&M(n,i,{get:()=>t[i],enumerable:!(r=dt(t,i))||r.enumerable});return n};var bt=n=>mt(M({},"__esModule",{value:!0}),n);var O=(n,t,e)=>ht(n,typeof t!="symbol"?t+"":t,e);var ue={};gt(ue,{applyGuards:()=>z,createProbeTaint:()=>P,probeGuardFixtures:()=>ie,runProbeGuardFixture:()=>ae});module.exports=bt(ue);function X(n,t=2166136261){let e=t>>>0;for(let r=0;r<n.length;r++)e^=n.charCodeAt(r),e=Math.imul(e,16777619);return e>>>0}function V(n){return X(n).toString(36).padStart(7,"0")+X(n,1540483477).toString(36).padStart(7,"0")}var m=n=>n.toLowerCase().replace(/[-_\s]/g,""),_=new Map;function yt(n){let t=_.get(n);if(!t){let e=n.split("").map(r=>r==="*"?".*":r==="?"?".":r.replace(/[.+^${}()|[\]\\/]/g,"\\$&")).join("");t=new RegExp(`^${e}$`,"i"),_.size>500&&_.clear(),_.set(n,t)}return t}function S(n,t){if(n===void 0)return!0;let e=typeof n=="string"?[n]:n;for(let r of e)if(yt(r).test(t))return!0;return!1}var C=n=>n===void 0?[]:Array.isArray(n)?n:[n];function Q(n){let t=new Uint8Array(n);try{let e=typeof crypto!="undefined"?crypto:void 0;if(e&&typeof e.getRandomValues=="function")return e.getRandomValues(t),t}catch{}for(let e=0;e<n;e++)t[e]=Math.floor(Math.random()*256);return t}function L(n){let t=n.trim();if(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]"))try{return JSON.parse(t)}catch{return}}function v(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}var tt=6,wt=4096,At=400,j=class{constructor(){O(this,"base1");O(this,"base2");O(this,"byLength",new Map);O(this,"order",[]);let t=Q(8),e=r=>(t[r]<<24|t[r+1]<<16|t[r+2]<<8|t[r+3])>>>0;this.base1=(e(0)|65537)>>>0,this.base2=(e(4)|65537)>>>0}get size(){return this.order.length}add(t){if(typeof t!="string"||t.length<tt||t.length>wt)return;let e=new Set([t]);try{e.add(encodeURIComponent(t))}catch{}try{e.add(new URLSearchParams({v:t}).toString().slice(2))}catch{}e.add(JSON.stringify(t).slice(1,-1));for(let r of e)this.addOne(r)}addOne(t){var i;let e=this.fingerprint(t,0,t.length),r=this.byLength.get(t.length);if(r||this.byLength.set(t.length,r=new Set),!r.has(e))for(r.add(e),this.order.push([t.length,e]);this.order.length>At;){let[s,o]=this.order.shift();(i=this.byLength.get(s))==null||i.delete(o)}}fingerprint(t,e,r){let i=0,s=0;for(let o=e;o<e+r;o++){let a=t.charCodeAt(o);i=Math.imul(i,this.base1)+a>>>0,s=Math.imul(s,this.base2)+a>>>0}return`${i}:${s}`}scrub(t){if(this.order.length===0||t.length<tt)return t;let e=[];for(let[o,a]of this.byLength){if(a.size===0||o>t.length)continue;let c=1,d=1;for(let f=0;f<o-1;f++)c=Math.imul(c,this.base1)>>>0,d=Math.imul(d,this.base2)>>>0;let p=0,u=0;for(let f=0;f<o;f++){let l=t.charCodeAt(f);p=Math.imul(p,this.base1)+l>>>0,u=Math.imul(u,this.base2)+l>>>0}for(let f=0;;f++){a.has(`${p}:${u}`)&&e.push([f,f+o]);let l=f+o;if(l>=t.length)break;let h=t.charCodeAt(f),b=t.charCodeAt(l);p=Math.imul(p-Math.imul(h,c)>>>0,this.base1)+b>>>0,u=Math.imul(u-Math.imul(h,d)>>>0,this.base2)+b>>>0}}if(e.length===0)return t;e.sort((o,a)=>o[0]-a[0]||a[1]-o[1]);let r="",i=0,s=0;for(;s<e.length;){let[o,a]=e[s];for(s++;s<e.length&&e[s][0]<a;)a=Math.max(a,e[s][1]),s++;o<i&&(o=i),r+=t.slice(i,o)+`<tainted:${a-o}>`,i=a}return r+t.slice(i)}};function P(n=[]){let t=new j;for(let e of n)t.add(e);return t}var $t=new Set(["challenge","id","rawId","userHandle","signature","clientDataJSON","authenticatorData","attestationObject","publicKey"].map(m));function rt(n,t){if(!t||typeof t!="object")return;let e=t;for(let r of["requestOptionsJson","creationOptionsJson","credentialJson"]){let i=e[r];if(typeof i!="string")continue;n.add(i);let s;try{s=JSON.parse(i)}catch{continue}let o=0,a=(c,d,p)=>{if(!(p>8||++o>500)){if(typeof c=="string"){$t.has(m(d))&&n.add(c);return}if(Array.isArray(c)){for(let u of c.slice(0,50))a(u,d,p+1);return}if(c&&typeof c=="object")for(let[u,f]of Object.entries(c))a(f,u,p+1)}};a(s,"",0)}}function it(n,t){for(let e of t.split(";").slice(0,100)){let r=e.indexOf("=");if(r<0)continue;let i=e.slice(r+1).trim();n.add(i);try{let s=decodeURIComponent(i);s!==i&&n.add(s)}catch{}}}var St=new Set(["password","passwd","pwd","passphrase","clientDataJSON","authenticatorData","signature","attestationObject","userHandle","authorization","proxyAuthorization","cookie","setCookie","privateKey","clientSecret"].map(m));function y(n){let t=m(n);return St.has(t)||t.includes("password")}var Rt=/eyJ0eXBlIjoid2ViYXV0aG4u[A-Za-z0-9_\-+/=]*/gi,Et=/eyJ[A-Za-z0-9_-]{16,}(?:\.[A-Za-z0-9_-]*){0,4}/gi,Nt=/("|\\")(password|passwd|pwd|clientDataJSON|authenticatorData|signature|attestationObject|userHandle|authorization)\1(\s*:\s*)\1(?!<)((?:(?!\1)[^\\]|\\.)*?)\1/gi,Tt=/(^|[?&;\s,])(password|passwd|pwd)=([^&\s;,]+)/gi,Ot=/\b(Bearer|Basic)\s+([A-Za-z0-9._~+/=-]{8,})/g,kt=/\b((?:proxy-)?authorization)(\s*[:=]\s*|"\s*:\s*")((?:Bearer|Basic|Digest|Token|Negotiate)\s+)?(?!<)([^\s,;"&]+)/gi;function U(n){return n.replace(kt,(t,e,r,i,s)=>`${e}${r}${i!=null?i:""}<redacted:${s.length}>`)}var xt=/\d(?:[ -]?\d){12,}/g,Mt=/[A-Za-z0-9_\-+/]{24,}={0,2}/g;function _t(n){let t=0,e=!1;for(let r=n.length-1;r>=0;r--){let i=n.charCodeAt(r)-48;e&&(i*=2,i>9&&(i-=9)),t+=i,e=!e}return t%10===0}function st(n){for(let t=13;t<=Math.min(19,n.length);t++)for(let e=0;e+t<=n.length;e++)if(_t(n.slice(e,e+t)))return!0;return!1}function Lt(n){var r;let t=new Map;for(let i of n)t.set(i,((r=t.get(i))!=null?r:0)+1);let e=0;for(let i of t.values()){let s=i/n.length;e-=s*Math.log2(s)}return e}function et(n){return n.length>=24&&/\d/.test(n)&&/[A-Za-z]/.test(n)&&Lt(n)>=3}var Pt=/^([A-Za-z][a-z]*(?:[-_.][A-Za-z]+)*|v\d{1,2}|\d{1,5}|)$/;function zt(n){if(!n.includes("/"))return!1;let t=n.split("/");return t.filter(r=>Pt.test(r)).length*2>=t.length}function It(n){return zt(n)?n.split("/").map(t=>et(t)?`<tok:${t.length}>`:t).join("/"):et(n)?`<tok:${n.length}>`:n}function nt(n,t){let e=t?t.scrub(n):n;return e=U(e),e=e.replace(Nt,(r,i,s,o,a)=>`${i}${s}${i}${o}${i}<redacted:${a.length}>${i}`),e=e.replace(Tt,(r,i,s,o)=>o.startsWith("<")?r:`${i}${s}=<redacted:${o.length}>`),e=e.replace(Ot,(r,i,s)=>`${i} <redacted:${s.length}>`),e=e.replace(Rt,r=>`<webauthn:${r.length}>`),e=e.replace(Et,r=>`<jwt:${r.length}>`),e=e.replace(xt,r=>{let i=r.replace(/[ -]/g,"");return i.length>19?`<digits:${i.length}>`:st(i)?`<card:${i.length}>`:r}),e=e.replace(Mt,It),e}function Jt(n){if(!Number.isFinite(n))return null;if(!Number.isInteger(n))return n;let t=String(Math.abs(n));return t.length>=13&&st(t)?`<card:${t.length}>`:n}function Ct(n){return n==null||typeof n=="boolean"?n:typeof n=="string"?jt.test(n)?n:`<redacted:${n.length}>`:typeof n=="number"?"<redacted:num>":"<redacted:obj>"}var jt=/^<[a-z]+(?::[A-Za-z0-9.]{1,12})?>$/,Dt=24;function D(n,t,e){if(e>Dt)return"<deep>";if(n===null||typeof n=="boolean")return n;if(typeof n=="string")return nt(n,t);if(typeof n=="number")return Jt(n);if(Array.isArray(n))return n.map(r=>{let i=D(r,t,e+1);return i===void 0?null:i});if(typeof n=="object"){let r={};for(let[i,s]of Object.entries(n)){let o=nt(i,t),a=y(i)?Ct(s):D(s,t,e+1);a!==void 0&&(r[o]=a)}return r}}function z(n,t){try{return D(n,t!=null?t:void 0,0)}catch{return}}var Ut=/^[^\s@]{1,64}@[^\s@]+\.[^\s@]{2,}$/,Zt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ht=/^[a-z][a-z0-9+.-]*:\/\/\S+$/i,Ft=/^\d{4}-\d{2}-\d{2}([T ][\d:.]+(Z|[+-]\d{2}:?\d{2})?)?$/,Kt=/^\+?[\d\s().-]{7,20}$/;function g(n){if(n==="")return"";let t=n.length;return/^eyJ/i.test(n)&&t>20?`<jwt:${t}>`:Ut.test(n)?"<email>":Zt.test(n)?"<uuid>":Ht.test(n)?"<url>":Ft.test(n)?"<date>":/^\d+$/.test(n)?`<digits:${t}>`:Kt.test(n)&&/\d{3}/.test(n)?"<phone>":/^(true|false|null|undefined)$/i.test(n)?`<${n.toLowerCase()}>`:/^[A-Za-z]+$/.test(n)?`<alpha:${t}>`:/^[0-9a-f]+$/i.test(n)&&t>=8?`<hex:${t}>`:/^[A-Za-z0-9]+$/.test(n)?`<alnum:${t}>`:/^[A-Za-z0-9_-]+$/.test(n)?`<id:${t}>`:/^[A-Za-z0-9+/]+={0,2}$/.test(n)&&t>=16?`<b64:${t}>`:/\s/.test(n.trim())?`<text:${n.trim().split(/\s+/).length}w>`:`<str:${t}>`}function A(n){return n==null||typeof n=="boolean"?n:typeof n=="number"?Number.isFinite(n)&&Number.isInteger(n)?`<int:${String(Math.abs(n)).length}>`:"<num>":typeof n=="string"?g(n):Array.isArray(n)?`<arr:${n.length}>`:typeof n=="object"?`<obj:${Object.keys(n).length}>`:`<${typeof n}>`}function Z(n){return n===null?"null":Array.isArray(n)?"array":typeof n}function H(n,t=0){let e=Math.max(0,Math.min(t,n.length));return n.slice(0,e)+n.slice(e).replace(/[0-9]/g,"9").replace(/[A-Za-zÀ-ɏ]/g,"a")}function ot(n,t=0,e=0){let r=Math.max(0,t),i=Math.max(0,e);return r+i>=n.length?"*".repeat(n.length):n.slice(0,r)+"*".repeat(n.length-r-i)+n.slice(n.length-i)}var Bt=/^[A-Za-zÀ-ɏͰ-ϿЀ-ӿ]+(?:['’_.-][A-Za-zÀ-ɏͰ-ϿЀ-ӿ]+)*$/;function I(n){return n.length<=40&&Bt.test(n)}var R=Symbol("probe.drop"),Gt=new Set(["otp","passcode","onetimepassword","onetimecode","securitycode","verificationcode","smscode","pin","cvv","cvc","answer","answers","securityanswer","useranswer","ssn","taxid","tin","socialsecuritynumber","token","accesstoken","idtoken","refreshtoken","sessiontoken","authtoken","bearer","apikey","ticket","codeverifier","secret","samlresponse","samlrequest","wresult","csrf","xsrf","csrftoken","xsrftoken","sessionid","deviceid","publickey","keypair","challenge","credential","assertion"].map(m)),Wt=/(password|passwd|token|secret|^otp|otp$|answer|ssn|ticket|cookie|credential)/,qt=/^[A-Za-z0-9_-]{16,}$/,F=3e5,K=4e3,Yt=12,B=100,at=200,Xt=new Set(["drop","presence","length","hash"]),G=/^<[a-z]+(?::[^<>\s]{0,24})?>$/,Vt=/<[a-z]+(?::[^<>\s]{0,24})?>/,Qt=/(<[a-z]+(?::[^<>\s]{0,24})?>)/,vt=/(^|[^A-Za-z0-9_%]|%[0-9A-Fa-f]{2})([A-Za-z_][A-Za-z0-9_.-]{0,40})(\s*[:=]\s*|%3D|%3A)((?:(?!%26|%2C|%20|%23|%3B|%7C)[^\s&"',;#<>|])+)/gi;function E(n){let t=m(n);return Gt.has(t)||Wt.test(t)}function te(n,t){return/^[A-Za-z_$][\w$.:-]{0,63}$/.test(n)&&!/\d{5,}/.test(n)||/^\d{1,4}$/.test(n)?n:`<key${t}:${g(n).replace(/[<>]/g,"")}>`}function ut(n){return n.split("/").map(t=>{if(t==="")return t;let e=t;try{e=decodeURIComponent(t)}catch{}return I(e)||/^v\d{1,2}(\.\d{1,2})?$/i.test(e)||/^\d{1,3}$/.test(e)||/^[A-Za-z][A-Za-z0-9_-]{0,40}(\.[A-Za-z0-9_-]{1,40}){0,3}\.[a-z0-9]{1,6}$/i.test(e)&&!/\d{6,}/.test(e)||/^[a-z]+[-_][a-z0-9]{1,3}$/i.test(e)?t:g(e)}).join("/")}var J=class{constructor(t,e){this.rules=t;this.salt=e}ruleFor(t,e,r){for(let i of this.rules)if(this.matches(i,t,e,r))return i}matches(t,e,r,i){if(t.surface!==void 0&&!C(t.surface).includes(e.surface)||t.part!==void 0&&t.part!==e.part||t.host!==void 0&&(e.host===void 0||!S(t.host,e.host))||t.path!==void 0&&(e.path===void 0||!S(t.path,e.path)))return!1;if(t.selector!==void 0){if(!e.el)return!1;try{if(!e.el.closest(t.selector))return!1}catch{return!1}}return t.key!==void 0?r===void 0?!1:C(t.key).some(s=>ee(s,r,i!=null?i:r)):!0}method(t,e,r,i=""){var s;switch(e.method){case"drop":return R;case"presence":return t==null?t:t===""||Array.isArray(t)&&t.length===0?"<empty>":"<set>";case"length":return t==null?t:typeof t=="string"?`<len:${t.length}>`:Array.isArray(t)?`<len:${t.length}>`:typeof t=="object"?`<len:${Object.keys(t).length}>`:`<len:${String(t).length}>`;case"hash":return t==null?t:`<h:${V(this.salt+(typeof t=="string"?t:JSON.stringify(t)))}>`;case"shape":return typeof t=="string"?H(t,e.keepPrefix):typeof t=="number"?H(String(t),e.keepPrefix):typeof t=="object"&&t!==null?this.tree(t,r,"shape",i):t;case"mask":return typeof t=="string"||typeof t=="number"?ot(String(t),e.keepStart,e.keepEnd):A(t);case"enum":return t==null||typeof t=="boolean"?t:typeof t=="string"||typeof t=="number"?((s=e.values)!=null?s:[]).includes(String(t))?t:A(t):A(t);case"clear":return this.leaf(t,r,i,e);default:return this.leaf(t,r,i,void 0)}}leaf(t,e,r,i){if(typeof t=="string"){if(t.length>F)return`<len:${t.length}>`;let s=L(t);return s!==void 0&&typeof s=="object"&&s!==null?this.tree(s,e,"values",r,i):/^https?:\/\/\S+$/i.test(t)?this.url(t,e,"values",i):/\s/.test(t.trim())?this.text(t,e,"values",i):i?t:g(t)}return t!==null&&typeof t=="object"?this.tree(t,e,"values",r,i):i?t:A(t)}keyed(t,e,r,i,s){if(y(t))return this.method(e,{method:"length"},r);let o=this.ruleFor(r,t,i);return o?this.method(e,o,r,i):E(t)?this.method(e,{method:"length"},r):m(t)==="code"&&typeof e=="string"&&qt.test(e)?this.method(e,{method:"length"},r):this.leaf(e,r,i,s)}tree(t,e,r,i="",s,o=0){var a;if(o>Yt)return"<deep>";if(Array.isArray(t)){let c=(a=i.split(".").pop())!=null?a:"",d=[];for(let p of t.slice(0,B)){let u=p!==null&&typeof p=="object"?this.tree(p,e,r,i,s,o+1):this.scalar(c,p,e,r,i,s);u!==R&&d.push(u)}return t.length>B&&d.push(`<more:${t.length-B}>`),d}if(v(t)){let c={},d=typeof t.type=="string"&&"value"in t?t.type:void 0,p=0;for(let[u,f]of Object.entries(t)){if(p>=at){c["<more>"]=Object.keys(t).length-at;break}let l=d!==void 0&&u==="value"?d:u,h=i?`${i}.${l}`:l,b,w=r==="values"?this.hasKeyRule(l,e,h):!!this.restrictiveRule(l,e,h,r);f!==null&&typeof f=="object"&&!w?b=y(l)?this.method(f,{method:"length"},e):this.tree(f,e,r,h,s,o+1):b=this.scalar(l,f,e,r,h,s),b!==R&&(c[te(u,p)]=b),p++}return c}return this.scalar("",t,e,r,i,s)}hasKeyRule(t,e,r){var i;return y(t)||E(t)||((i=this.ruleFor(e,t,r))==null?void 0:i.key)!==void 0}restrictiveRule(t,e,r,i){if(!t)return;let s=this.ruleFor(e,t,r);if(!(!s||s.key===void 0))return s.method==="drop"||i==="shape"&&Xt.has(s.method)?s:void 0}scalar(t,e,r,i,s,o){if(i!=="values"){let c=this.restrictiveRule(t,r,s,i);if(c)return this.method(e,c,r,s)}if(i==="inventory")return Z(e);if(i==="shape"){if(t&&(y(t)||E(t)))return this.method(e,{method:"length"},r);if(typeof e=="string"){let c=e.length<=F?L(e):void 0;if(c!==void 0&&typeof c=="object"&&c!==null)return this.tree(c,r,"shape",s)}return A(e)}if(t)return this.keyed(t,e,r,s,o);let a=this.ruleFor(r);return a?this.method(e,a,r,s):this.leaf(e,r,s,o)}text(t,e,r,i){if(r==="inventory"||r==="shape")return g(t);if(!i){let o=this.ruleFor(e);if(o){if(o.method==="class")return g(t);let a=this.method(t,o,e);if(a===R)return"";if(o.method!=="clear")return typeof a=="string"?a:JSON.stringify(a);i=o}}let s=U(t).replace(vt,(o,a,c,d,p)=>{if(G.test(p))return o;let u;if(y(c))u=`<redacted:${p.length}>`;else{let f=this.ruleFor(e,c,c);f&&f.key!==void 0?u=this.method(p,f,e,c):E(c)&&(u=`<redacted:${p.length}>`)}return u===void 0?o:`${a}${c}${d}${u===R?"<dropped>":String(u)}`});return i?s:s.replace(/\S+/g,o=>this.token(o,e))}token(t,e,r=0){var c,d,p,u;if(G.test(t))return t;if(Vt.test(t))return t.split(Qt).map((f,l)=>l%2===1||f===""?f:this.token(f,e,r)).join("");let i=(d=(c=/^[([{"'“‘|<]+/.exec(t))==null?void 0:c[0])!=null?d:"",s=(u=(p=/[)\]}"'”’,.;:=!?|>/]+$/.exec(t.slice(i.length)))==null?void 0:p[0])!=null?u:"",o=t.slice(i.length,t.length-s.length);if(o===""||G.test(o)||I(o)||/^\d{1,3}$/.test(o))return t;if(/^https?:\/\//i.test(o))return i+this.url(o,e,"values")+s;let a=r===0?/[:=]/.exec(o):null;if(a&&a.index>0&&a.index<o.length-1){let f=o.slice(0,a.index),l=o.slice(a.index+1);return i+this.token(f,e,1)+a[0]+this.token(l,e,1)+s}return i+g(o)+s}url(t,e,r,i){var p;let s;try{s=new URL(t,typeof location!="undefined"?location.href:void 0)}catch{return r==="inventory"?"<url>":g(t)}let o={...e,host:s.hostname,path:s.pathname,part:(p=e.part)!=null?p:"url"},a=`${s.protocol}//${s.host}${ut(s.pathname)}`;if(r==="inventory")return a;let c=u=>{let f=[];return new URLSearchParams(u).forEach((l,h)=>{if(f.length>=60)return;let b=/^[\w.[\]-]{1,64}$/.test(h)?h:g(h),w;if(r==="shape"){let Y=this.restrictiveRule(h,o,h,r);w=Y?this.method(l,Y,o,h):y(h)||E(h)?`<len:${l.length}>`:A(l)}else w=this.keyed(h,l,o,h,i);w!==R&&f.push(`${b}=${typeof w=="string"?w:JSON.stringify(w)}`)}),f.join("&")};s.search.length>1&&(a+=`?${c(s.search.slice(1))}`);let d=s.hash.slice(1);if(d)if(d.startsWith("/")){let u=d.indexOf("?");a+=`#${ut(u<0?d:d.slice(0,u))}${u<0?"":`?${c(d.slice(u+1))}`}`}else d.includes("=")?a+=`#${c(d)}`:a+=`#${I(d)?d:g(d)}`;return a}body(t,e,r){try{if(t==null)return;if(r==="inventory")return{type:Z(t)};if(typeof t=="string"){if(t.length>F)return{len:t.length,skipped:"size"};let i=L(t);if(i!==void 0)return this.tree(i,e,r);if(ne(t))return{form:this.tree(ct(new URLSearchParams(t)),e,r)};if(r==="shape")return{text:g(t)};let s=t.length>K?t.slice(0,K):t,o=re(s),a=/^\s*</.test(o)?o.replace(/</g," <").replace(/>/g,"> "):o;return{text:this.text(a,e,r).trim(),...t.length>K?{len:t.length}:{}}}if(typeof URLSearchParams!="undefined"&&t instanceof URLSearchParams)return{form:this.tree(ct(t),e,r)};if(typeof FormData!="undefined"&&t instanceof FormData){let i={};return t.forEach((s,o)=>{i[o]=typeof s=="string"?s:`<file:${s.size}>`}),{formData:this.tree(i,e,r)}}return typeof Blob!="undefined"&&t instanceof Blob?{blob:t.size}:typeof ArrayBuffer!="undefined"&&(t instanceof ArrayBuffer||ArrayBuffer.isView(t))?{bytes:t.byteLength}:typeof t=="object"?this.tree(t,e,r):this.scalar("",t,e,r,"")}catch{return{error:"redact-failed"}}}};function ee(n,t,e){return n.includes(".")?S(n,e)||S(`*.${n}`,e):n.includes("*")||n.includes("?")?S(n,t):m(n)===m(t)}function ne(n){return/^[^\s<>{}=&]+=[^\s<>]*(&[^\s<>{}=&]+=[^\s<>]*)*$/.test(n.trim())}function ct(n){let t={};return n.forEach((e,r)=>{r in t?t[r]=[].concat(t[r],e):t[r]=e}),t}function re(n){let t=e=>y(e)||E(e);return n.replace(/(<input\b[^>]*\bname\s*=\s*["']?([\w.-]+)["']?[^>]*\bvalue\s*=\s*)(["'])([^"'>]*)\3/gi,(e,r,i,s,o)=>t(i)?`${r}${s}<redacted:${o.length}>${s}`:e).replace(/(<input\b[^>]*\bvalue\s*=\s*)(["'])([^"'>]*)\2([^>]*\bname\s*=\s*["']?([\w.-]+)["']?)/gi,(e,r,i,s,o,a)=>t(a)?`${r}${i}<redacted:${s.length}>${i}${o}`:e)}var $="eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJlLXZhbHVl",ft="eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0.zQ8xLm4Pw7Rt2Yb9Nc3Vd6Hg",N="eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiY2gtMTIzNDU2Nzg5MCJ9",k="MEUCIQDsig8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1",W="SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ",x="dXNlci1oYW5kbGUtOTg3NjU0",q="Y2hhbGxlbmdlLXJhbmRvbS1ieXRlcy0wMDE",T="Y3JlZGVudGlhbC1pZC1hYmNkZWYxMjM0NTY",ie=[{name:"password in a JSON login body",input:{url:"https://login.example.com/usernamepassword/login",request:JSON.stringify({username:"jane",password:"hunter2-secret"})},mustNotContain:["hunter2-secret"]},{name:"typed password under an unrelated key (taint)",input:{url:"https://api.example.com/v1/session",request:{x_field:"typed-Pa55word!",note:"pw typed-Pa55word! here"},typed:["typed-Pa55word!"]},mustNotContain:["typed-Pa55word!","typed-Pa55word%21"]},{name:"passkey assertion carried in the password form field (Auth0)",input:{url:"https://login.example.com/u/login",request:`state=abc&username=jane&password=${encodeURIComponent(JSON.stringify({id:T,response:{clientDataJSON:N,authenticatorData:W,signature:k,userHandle:x}}))}`},mustNotContain:[N,k,W,x]},{name:"WebAuthn ceremony parts under foreign keys (taint from the WebAuthn feed)",input:{url:"https://api.example.com/fido/verify",request:{fido_payload:{a:k,b:x,c:q},cid:T},webauthn:{requestOptionsJson:JSON.stringify({challenge:q,allowCredentials:[{id:T,type:"public-key"}]}),credentialJson:JSON.stringify({id:T,rawId:T,response:{signature:k,userHandle:x,clientDataJSON:N,authenticatorData:W}})}},mustNotContain:[k,x,q,T]},{name:"JWT / JWE in a response body and a lowercased JWT in a beacon URL",input:{url:`https://collect.example.net/c?en=page_view&dl=${encodeURIComponent(`https://app.example.com/cb?session_token=${$}`).toLowerCase()}`,response:JSON.stringify({id_token:$,data:{token:ft,note:`bearer ${$}`}})},mustNotContain:[$,$.toLowerCase(),ft,"eyjhbgcioijsuzi1nij9"]},{name:"WebAuthn client data JSON (base64url) anywhere",input:{text:`debug: got ${N} from the authenticator`,response:{blob:N}},mustNotContain:[N]},{name:"card numbers (Luhn) as text, digits and number",input:{text:"card 4111 1111 1111 1111 ok",response:{pan:"5500005555555559",n:0xe41b380beb2d9}},mustNotContain:["4111 1111 1111 1111","5500005555555559","4012888888881881"]},{name:"Authorization / Bearer values in text and bodies",input:{text:"request failed Authorization: Bearer abcDEF123456ghiJKL789",request:{headers:{Authorization:"Basic dXNlcjpwYXNzd29yZA=="}}},mustNotContain:["abcDEF123456ghiJKL789","dXNlcjpwYXNzd29yZA=="]},{name:"cookie values echoed in a body (taint)",input:{url:"https://api.example.com/echo",response:{seen:"c00kie-session-value-42"},cookie:"sid=c00kie-session-value-42; theme=dark"},mustNotContain:["c00kie-session-value-42"]},{name:"typed one-time code echoed in a request (taint)",input:{url:"https://api.example.com/verify",request:{code_value:"482913",data:{otp:"482913"}},typed:["482913"]},mustNotContain:["482913"]},{name:"high-entropy opaque token under an unknown key",input:{response:{foo:"Zx8Kq2Lm9Pw4Rt7Yb3Nc6Vd1Hg5Jf0Ts"}},mustNotContain:["Zx8Kq2Lm9Pw4Rt7Yb3Nc6Vd1Hg5Jf0Ts"]},{name:"auto-post form HTML with a JWT wresult and a hidden password input",input:{response:`<form method="post" action="https://login.example.com/callback"><input type="hidden" name="wresult" value="${$}"><input type="hidden" value="hunter2-hidden" name="password"></form>`},mustNotContain:[$,"hunter2-hidden"]},{name:"password in free text and query strings",input:{url:"https://legacy.example.com/login?user=jane&password=qwerty-url-123",text:"retry with password=qwerty-txt-456 failed"},mustNotContain:["qwerty-url-123","qwerty-txt-456"]}],se=["inventory","shape","values"],oe=["ui","act","console","err","msg"];function ae(n,t){var c,d,p;let e=new J((c=n.rules)!=null?c:[],"conformance"),r=P((d=t.input.typed)!=null?d:[]);t.input.cookie&&it(r,t.input.cookie),t.input.webauthn&&rt(r,t.input.webauthn);let i=[],s=u=>{let f=z(u,r);f!==void 0&&i.push(f)},o,a;try{let u=new URL((p=t.input.url)!=null?p:"https://app.example.com/");o=u.hostname,a=u.pathname}catch{}for(let u of se){let f=l=>({surface:"net",host:o,path:a,part:l});if(t.input.url&&s({url:e.url(t.input.url,f("url"),u)}),t.input.request!==void 0&&s({rq:e.body(t.input.request,f("request"),u)}),t.input.response!==void 0&&s({rs:e.body(t.input.response,f("response"),u)}),t.input.text!==void 0)for(let l of oe)s({x:e.text(t.input.text,{surface:l,host:o,path:a},u)})}return i}0&&(module.exports={applyGuards,createProbeTaint,probeGuardFixtures,runProbeGuardFixture});
@@ -0,0 +1 @@
1
+ import{B as C,q as h,r as k,t as x,v as b}from"../chunk-WY3VIPYX.mjs";import"../chunk-JR557W27.mjs";var n="eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJlLXZhbHVl",A="eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0.zQ8xLm4Pw7Rt2Yb9Nc3Vd6Hg",a="eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiY2gtMTIzNDU2Nzg5MCJ9",s="MEUCIQDsig8f7a6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d1",y="SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAABQ",i="dXNlci1oYW5kbGUtOTg3NjU0",w="Y2hhbGxlbmdlLXJhbmRvbS1ieXRlcy0wMDE",r="Y3JlZGVudGlhbC1pZC1hYmNkZWYxMjM0NTY",O=[{name:"password in a JSON login body",input:{url:"https://login.example.com/usernamepassword/login",request:JSON.stringify({username:"jane",password:"hunter2-secret"})},mustNotContain:["hunter2-secret"]},{name:"typed password under an unrelated key (taint)",input:{url:"https://api.example.com/v1/session",request:{x_field:"typed-Pa55word!",note:"pw typed-Pa55word! here"},typed:["typed-Pa55word!"]},mustNotContain:["typed-Pa55word!","typed-Pa55word%21"]},{name:"passkey assertion carried in the password form field (Auth0)",input:{url:"https://login.example.com/u/login",request:`state=abc&username=jane&password=${encodeURIComponent(JSON.stringify({id:r,response:{clientDataJSON:a,authenticatorData:y,signature:s,userHandle:i}}))}`},mustNotContain:[a,s,y,i]},{name:"WebAuthn ceremony parts under foreign keys (taint from the WebAuthn feed)",input:{url:"https://api.example.com/fido/verify",request:{fido_payload:{a:s,b:i,c:w},cid:r},webauthn:{requestOptionsJson:JSON.stringify({challenge:w,allowCredentials:[{id:r,type:"public-key"}]}),credentialJson:JSON.stringify({id:r,rawId:r,response:{signature:s,userHandle:i,clientDataJSON:a,authenticatorData:y}})}},mustNotContain:[s,i,w,r]},{name:"JWT / JWE in a response body and a lowercased JWT in a beacon URL",input:{url:`https://collect.example.net/c?en=page_view&dl=${encodeURIComponent(`https://app.example.com/cb?session_token=${n}`).toLowerCase()}`,response:JSON.stringify({id_token:n,data:{token:A,note:`bearer ${n}`}})},mustNotContain:[n,n.toLowerCase(),A,"eyjhbgcioijsuzi1nij9"]},{name:"WebAuthn client data JSON (base64url) anywhere",input:{text:`debug: got ${a} from the authenticator`,response:{blob:a}},mustNotContain:[a]},{name:"card numbers (Luhn) as text, digits and number",input:{text:"card 4111 1111 1111 1111 ok",response:{pan:"5500005555555559",n:0xe41b380beb2d9}},mustNotContain:["4111 1111 1111 1111","5500005555555559","4012888888881881"]},{name:"Authorization / Bearer values in text and bodies",input:{text:"request failed Authorization: Bearer abcDEF123456ghiJKL789",request:{headers:{Authorization:"Basic dXNlcjpwYXNzd29yZA=="}}},mustNotContain:["abcDEF123456ghiJKL789","dXNlcjpwYXNzd29yZA=="]},{name:"cookie values echoed in a body (taint)",input:{url:"https://api.example.com/echo",response:{seen:"c00kie-session-value-42"},cookie:"sid=c00kie-session-value-42; theme=dark"},mustNotContain:["c00kie-session-value-42"]},{name:"typed one-time code echoed in a request (taint)",input:{url:"https://api.example.com/verify",request:{code_value:"482913",data:{otp:"482913"}},typed:["482913"]},mustNotContain:["482913"]},{name:"high-entropy opaque token under an unknown key",input:{response:{foo:"Zx8Kq2Lm9Pw4Rt7Yb3Nc6Vd1Hg5Jf0Ts"}},mustNotContain:["Zx8Kq2Lm9Pw4Rt7Yb3Nc6Vd1Hg5Jf0Ts"]},{name:"auto-post form HTML with a JWT wresult and a hidden password input",input:{response:`<form method="post" action="https://login.example.com/callback"><input type="hidden" name="wresult" value="${n}"><input type="hidden" value="hunter2-hidden" name="password"></form>`},mustNotContain:[n,"hunter2-hidden"]},{name:"password in free text and query strings",input:{url:"https://legacy.example.com/login?user=jane&password=qwerty-url-123",text:"retry with password=qwerty-txt-456 failed"},mustNotContain:["qwerty-url-123","qwerty-txt-456"]}],q=["inventory","shape","values"],P=["ui","act","console","err","msg"];function E(L,e){var N,f,J;let u=new C((N=L.rules)!=null?N:[],"conformance"),d=h((f=e.input.typed)!=null?f:[]);e.input.cookie&&x(d,e.input.cookie),e.input.webauthn&&k(d,e.input.webauthn);let g=[],p=t=>{let o=b(t,d);o!==void 0&&g.push(o)},c,l;try{let t=new URL((J=e.input.url)!=null?J:"https://app.example.com/");c=t.hostname,l=t.pathname}catch{}for(let t of q){let o=m=>({surface:"net",host:c,path:l,part:m});if(e.input.url&&p({url:u.url(e.input.url,o("url"),t)}),e.input.request!==void 0&&p({rq:u.body(e.input.request,o("request"),t)}),e.input.response!==void 0&&p({rs:u.body(e.input.response,o("response"),t)}),e.input.text!==void 0)for(let m of P)p({x:u.text(e.input.text,{surface:m,host:c,path:l},t)})}return g}export{b as applyGuards,h as createProbeTaint,O as probeGuardFixtures,E as runProbeGuardFixture};