@corbado/autocapture 1.0.1 → 1.2.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, F as FederatedIdentityCaptureOptions, b as FederatedIdentityCaptureHandle, N as NetworkCaptureOptions, C as CaptureHandle, c as NavigationCaptureOptions } from './types-lamU1Fd3.js';
2
+ export { d as CredentialMediation, e as FederatedIdentityCompletedEvent, f as FederatedIdentityContext, g as FederatedIdentityEvent, h as FederatedIdentityFailedEvent, i as FederatedIdentityMode, j as FederatedIdentityProvider, k as FederatedIdentityStartedEvent, H as HttpExchange, l as HttpRequestStarted, L as Logger, m as NavigationEvent, n as NavigationSource, o as NetworkBodyDirection, p as NetworkBodyProjectionContext, q as NetworkBodyProjector, r as NetworkTransport, s as WebAuthnAttachSurface, t as WebAuthnCeremonyCompletedEvent, u as WebAuthnCeremonyContext, v as WebAuthnCeremonyEvent, w as WebAuthnCeremonyFailedEvent, x as WebAuthnCeremonyStartedEvent, y as WebAuthnMediation, z as WebAuthnUiMode } from './types-lamU1Fd3.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()`.
@@ -259,7 +16,8 @@ type NavigationCaptureOptions = {
259
16
  * current environment — the API is missing, a capture is already active, or
260
17
  * another integration holds the credential methods in a form that cannot be
261
18
  * shared — nothing is modified and the returned handle reports
262
- * `mode: "unavailable"`.
19
+ * `mode: "unavailable"`. {@link captureFederatedIdentity} shares the same
20
+ * attachment; either capture can run and stop independently.
263
21
  *
264
22
  * Assumptions and limitations:
265
23
  *
@@ -281,6 +39,28 @@ type NavigationCaptureOptions = {
281
39
  */
282
40
  declare function captureWebAuthn(options: WebAuthnCaptureOptions): WebAuthnCaptureHandle;
283
41
 
42
+ /**
43
+ * Observes FedCM requests made through `navigator.credentials.get({ identity })`, such as Google
44
+ * One Tap on Chromium.
45
+ *
46
+ * Each request emits a `started` event followed by a correlated `completed` (an account was
47
+ * chosen) or `failed` event. Calls without `identity` options are not reported. Tokens, nonces,
48
+ * provider parameters and login hints are never read into events. Observation never changes a
49
+ * request's arguments, result, or error; the request is delegated synchronously before anything is
50
+ * observed, so user activation reaches the browser unchanged.
51
+ *
52
+ * Shares one attachment to `navigator.credentials` with {@link captureWebAuthn}; either capture can
53
+ * start first and stop independently, and a later one joins at whatever surface the first attached
54
+ * to. `attach` applies only when this capture attaches first, as in {@link captureWebAuthn}. The
55
+ * handle reports `mode: "unavailable"` when the credential methods cannot be observed or a federated
56
+ * identity capture is already active.
57
+ *
58
+ * @param options Event callback and optional diagnostic logger.
59
+ * @returns A handle used to inspect the capture mode or stop event delivery.
60
+ * @throws TypeError when `onEvent` is not a function.
61
+ */
62
+ declare function captureFederatedIdentity(options: FederatedIdentityCaptureOptions): FederatedIdentityCaptureHandle;
63
+
284
64
  /**
285
65
  * Observes selected requests made through `XMLHttpRequest` and `fetch`.
286
66
  *
@@ -377,4 +157,4 @@ declare function isValidationMessageVisible(element: Element | null): boolean;
377
157
  */
378
158
  declare function captureInputValidation(options: InputValidationCaptureOptions): InputValidationCaptureHandle;
379
159
 
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 };
160
+ export { CaptureHandle, FederatedIdentityCaptureHandle, FederatedIdentityCaptureOptions, type InputValidationCaptureHandle, type InputValidationCaptureOptions, type InputValidationError, type InputValidationState, NavigationCaptureOptions, NetworkCaptureOptions, VERSION, WebAuthnCaptureHandle, WebAuthnCaptureOptions, captureFederatedIdentity, 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 ue=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var Me=Object.prototype.hasOwnProperty;var Be=(e,t)=>{for(var n in t)ue(e,n,{get:t[n],enumerable:!0})},Ne=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Le(t))!Me.call(e,o)&&o!==n&&ue(e,o,{get:()=>t[o],enumerable:!(r=Te(t,o))||r.enumerable});return e};var He=e=>Ne(ue({},"__esModule",{value:!0}),e);var Je={};Be(Je,{VERSION:()=>qe,captureFederatedIdentity:()=>me,captureInputValidation:()=>Se,captureNavigation:()=>ke,captureNetwork:()=>Ee,captureWebAuthn:()=>ge,composedPath:()=>Ae,inputValidationCode:()=>le,isValidationMessageVisible:()=>Oe,sanitizeAssertionResponse:()=>G.sanitizeAssertionResponse,sanitizeCreationOptions:()=>G.sanitizeCreationOptions,sanitizeCreationResponse:()=>G.sanitizeCreationResponse,sanitizeRequestOptions:()=>G.sanitizeRequestOptions});module.exports=He(Je);var J=require("@corbado/observe");var De={log:()=>{}};function W(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{}}}:De}var fe=Symbol.for("corbado.autocapture.installed");function U(e){try{return typeof e=="function"&&Object.prototype.hasOwnProperty.call(e,fe)}catch{return!1}}function K(e,t){var r,o;let n=t;try{Object.defineProperty(e,fe,{value:t,configurable:!0})}catch{}try{Object.defineProperty(e,"name",{value:(r=n.name)!=null?r:"",configurable:!0})}catch{}try{Object.defineProperty(e,"length",{value:(o=n.length)!=null?o:0,configurable:!0})}catch{}return e}function B(){return{mode:"unavailable",disconnect:()=>{}}}function de(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 Y(e,t,n,r,o,y=String(t)){try{let l=Object.getOwnPropertyDescriptor(e,t);de(l,{...r,value:n})&&Object.defineProperty(e,t,r)}catch(l){o.log(`${y} restoration skipped`,l)}}function z(e,t,n){let r=W(e);return o=>{try{let y=n(o);if(y&&(typeof y=="object"||typeof y=="function"))try{Promise.resolve(y).catch(l=>r.log(`${t} listener failed`,l))}catch(l){r.log(`${t} listener failed`,l)}}catch(y){r.log(`${t} listener failed`,y)}}}var he=e=>({get:e("get"),create:e("create")}),Q;function te(e){if(Q)return[...Q.subscribers].some(n=>n.channel===e.channel)?{attached:!1,reason:"an equivalent capture is already active"}:ye(Q,e);let t=je(e);return typeof t=="string"?{attached:!1,reason:t}:(Q=t,ye(t,e))}function ye(e,t){e.subscribers.add(t);let n=!0;return{attached:!0,surface:e.surface,unsubscribe:()=>{n&&(n=!1,e.subscribers.delete(t),!(e.subscribers.size>0)&&(e.active=!1,e.detach(),Q===e&&(Q=void 0)))}}}function je(e){let t=typeof navigator=="undefined"?void 0:navigator,n=t==null?void 0:t.credentials;if(!t||!n)return"navigator.credentials missing";let r=n,o=he(d=>r[d]);if(typeof o.get!="function"||typeof o.create!="function")return"credentials methods missing";if(U(o.get)||U(o.create))return"an equivalent capture is already active";let y={surface:"methods",subscribers:new Set,active:!1,detach:()=>{}},l=(...d)=>y.subscribers.forEach(f=>f.logger.log(...d)),A=(d,f,g)=>{let b={invoke(...P){let h=P[0];if(!y.active||g!=null&&g()||!$(h))return f(this,P);let E=f(this,P),v=[];for(let p of[...y.subscribers])try{let c=p.onCall(d,h);c&&v.push([p,c])}catch(c){p.logger.log("credentials observation failed",c)}if(v.length===0)return E;let s=p=>{for(let[c,O]of v)try{p(O)}catch(j){c.logger.log("credentials observation failed",j)}};return Promise.resolve(E).then(p=>(s(c=>c.completed(p)),p),p=>{throw s(c=>c.failed(p)),p})}}.invoke;return K(b,{name:d,length:0})},u=d=>{var b;let f=A(d,(P,h)=>Reflect.apply(o[d],P,h)),g=Object.getOwnPropertyDescriptor(n,d);if(g&&(!("value"in g)||g.writable!==!0))return null;try{r[d]=f}catch{return null}if(((b=Object.getOwnPropertyDescriptor(n,d))==null?void 0:b.value)!==f){try{r[d]=o[d]}catch{}return null}return()=>{r[d]===f&&(g?r[d]=g.value:delete r[d])}},q=()=>{let d=he(()=>new WeakMap),f=(E,v)=>{let s=d[E].get(v);if(s)return s;let p=A(E,(c,O)=>Reflect.apply(v,n,O),()=>{try{let c=r[E];return c!==v&&c!==p}catch(c){return l("suppress check failed; ceremony unreported",c),!0}});return d[E].set(v,p),p},g=E=>{let v=Object.getOwnPropertyDescriptor(n,E);return v?v.configurable===!0||!("value"in v)||v.writable===!0:!0},b=new WeakMap,P=new Proxy(n,{get(E,v){let s=Reflect.get(n,v,n);if((v==="get"||v==="create")&&g(v))return typeof s!="function"||U(s)?s:f(v,s);if(typeof s!="function"||!g(v)||v==="constructor")return s;let p=b.get(s);if(p)return p;let c=s.bind(n);return b.set(s,c),c},set(E,v,s){return Reflect.set(n,v,s,n)}}),h=Object.getOwnPropertyDescriptor(t,"credentials");if(h&&h.configurable!==!0)return null;try{Object.defineProperty(t,"credentials",{value:P,writable:!0,enumerable:!0,configurable:!0})}catch{return null}return t.credentials!==P?null:()=>{t.credentials===P&&(h?Object.defineProperty(t,"credentials",h):delete t.credentials)}},m=(d,f)=>(y.surface=d,y.detach=f,y.active=!0,y),R=u("get"),L=R?u("create"):null;if(R&&L)return m("methods",()=>{R(),L()});if(R==null||R(),e.attach==="container"){let d=q();if(d)return m("container",d)}return"credentials methods cannot be patched safely"}function $(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function ne(){let e=navigator.userActivation;return typeof(e==null?void 0:e.isActive)=="boolean"?e.isActive:void 0}function re(e){return e===void 0?"optional":e==="silent"||e==="optional"||e==="conditional"||e==="required"?e:"unknown"}function oe(e){return e instanceof DOMException?e.name:"UnknownError"}function ge(e){var A;let t=e.onEvent;if(typeof t!="function")throw new TypeError("captureWebAuthn requires an onEvent callback");let n=W(e.logger),r=!0,o=0,y=z(n,"webauthn",t),l=te({channel:"webauthn",attach:(A=e.attach)!=null?A:"methods",logger:n,onCall(u,q){if(!r||!$(q.publicKey))return;let m=q.publicKey,R=`wa-${++o}`,L=$(q.signal)?q.signal:void 0,d=Fe(u,q,m),f=b=>{r&&y({...d,ceremonyId:R,...b()})},g=()=>(L==null?void 0:L.aborted)===!0?{aborted:!0}:{};return f(()=>({phase:"started",userActivation:ne(),...d.kind==="authentication"?{requestOptionsJson:(0,J.sanitizeRequestOptions)(m)}:{creationOptionsJson:(0,J.sanitizeCreationOptions)(m,e.identifierProjectors)}})),{completed:b=>f(()=>({phase:"completed",credentialJson:u==="create"?(0,J.sanitizeCreationResponse)(b,e.identifierProjectors):(0,J.sanitizeAssertionResponse)(b,e.identifierProjectors),...g()})),failed:b=>f(()=>({phase:"failed",error:b,errorName:oe(b),...g()}))}}});return l.attached?(l.surface==="container"&&n.log("webauthn capture attached at the credentials container"),{mode:"standard",surface:l.surface,disconnect:()=>{r=!1,l.unsubscribe()}}):(n.log(`webauthn capture unavailable: ${l.reason}`),{...B(),surface:"none"})}function Fe(e,t,n){let r=re(t.mediation);if(e==="create")return{kind:"registration",mediation:r};let o=n;return{kind:"authentication",mediation:r,uiMode:Ve(t.uiMode),credentialSet:Array.isArray(o.allowCredentials)&&o.allowCredentials.length>0?"allowlisted":"discoverable"}}function Ve(e){return e===void 0?"default":e==="immediate"?"immediate":"unknown"}function me(e){var A;let t=e.onEvent;if(typeof t!="function")throw new TypeError("captureFederatedIdentity requires an onEvent callback");let n=W(e.logger),r=!0,o=0,y=z(n,"federated identity",t),l=te({channel:"federated-identity",attach:(A=e.attach)!=null?A:"methods",logger:n,onCall(u,q){let m=q.identity;if(!r||u!=="get"||!$(m))return;let R=`fi-${++o}`,L=$(q.signal)?q.signal:void 0,d=m,f=g=>{r&&y(g)};return f({phase:"started",requestId:R,providers:We(d.providers),context:Ue(d.context),mode:_e(d.mode),mediation:re(q.mediation),userActivation:ne()}),{completed:g=>{if(g===null){f({phase:"failed",requestId:R,errorName:"NoCredential"});return}let b=g;f({phase:"completed",requestId:R,...typeof b.configURL=="string"?{configURL:b.configURL}:{},...typeof b.isAutoSelected=="boolean"?{isAutoSelected:b.isAutoSelected}:{}})},failed:g=>{let b=oe(g),P=b==="IdentityCredentialError"?Ke(g):void 0;f({phase:"failed",requestId:R,errorName:b,...P!==void 0?{code:P}:{},...(L==null?void 0:L.aborted)===!0?{aborted:!0}:{}})}}}});return l.attached?{mode:"standard",surface:l.surface,disconnect:()=>{r=!1,l.unsubscribe()}}:(n.log(`federated identity capture unavailable: ${l.reason}`),{...B(),surface:"none"})}function We(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!$(n))continue;let{configURL:r,clientId:o}=n;typeof r=="string"&&t.push(typeof o=="string"?{configURL:r,clientId:o}:{configURL:r})}return t}function Ue(e){return e===void 0?"signin":e==="signin"||e==="signup"||e==="use"||e==="continue"?e:"unknown"}function _e(e){return e===void 0?"passive":e==="passive"||e==="active"?e:"unknown"}function Ke(e){let{error:t,code:n}=e;return typeof t=="string"&&t!==""?t:typeof n=="string"&&n!==""?n:void 0}var be=0;function ve(){return be+=1,`network-${be}`}function ze(e,t){let n=e.responseType;if(n===""||n==="text")return t(e.responseText);if(n==="json"){let r=e.response;return r==null?void 0:t(r)}}var Xe=500,we=Symbol("body-read-timeout");function Ce(e){return/event-stream|octet-stream/i.test(e)?!1:/json|text|urlencoded/i.test(e)}async function Re(e,t){let n=e.body;if(!n)return;let r=n.getReader(),o;try{let y=new Promise(u=>{o=setTimeout(()=>u(we),Xe)}),l=new TextDecoder,A=[];for(;;){let u=await Promise.race([r.read(),y]);if(u===we){t.log("body omitted: read timed out"),r.cancel().catch(()=>{});return}if(u.done)break;A.push(l.decode(u.value,{stream:!0}))}return A.push(l.decode()),A.join("")}catch{r.cancel().catch(()=>{});return}finally{o!==void 0&&clearTimeout(o)}}function ce(e){var t;(t=e==null?void 0:e.body)==null||t.cancel().catch(()=>{})}function Ee(e){var h,E,v;let{onExchange:t,onRequest:n,match:r}=e;if(typeof t!="function"||typeof r!="function")throw new TypeError("captureNetwork requires onExchange and match callbacks");let o=W(e.logger),y=(h=e.transports)!=null?h:["xhr","fetch"],l=(E=e.bodyCapture)==null?void 0:E.request,A=(v=e.bodyCapture)==null?void 0:v.response,u=typeof l=="function",q=typeof A=="function",m=!1,R=z(o,"network",s=>{if(m)return t(s)}),L=z(o,"network request",s=>{if(m)return n==null?void 0:n(s)}),d=(s,p,c)=>{if(typeof c=="function")try{return c(s,p)}catch(O){o.log("body projection failed",O);return}},f=(s,p)=>{try{let c=typeof document!="undefined"?document.baseURI:void 0,O=new URL(String(s),c);return r(O,p)===!0?{url:O.href,path:O.pathname}:void 0}catch{return}},g=()=>{if(typeof XMLHttpRequest=="undefined")return o.log("xhr capture unavailable: XMLHttpRequest missing"),null;let s=XMLHttpRequest.prototype,p=Object.getOwnPropertyDescriptor(s,"open"),c=Object.getOwnPropertyDescriptor(s,"send");if(!p||!("value"in p)||typeof p.value!="function"||!c||!("value"in c)||typeof c.value!="function")return o.log("xhr capture unavailable: XMLHttpRequest methods missing"),null;let O=p.value,j=c.value;if(U(O)||U(j))return o.log("xhr capture unavailable: an equivalent capture is already active"),null;let H=new WeakMap,a=new Set,C=!1,S={open(...x){var I;let i=Reflect.apply(O,this,x);if(!m||!C)return i;try{let N=H.get(this);N&&(N.reported=!0,(I=N.cleanupListeners)==null||I.call(N));let D=String(x[0]).toUpperCase(),M=f(x[1],D);M?H.set(this,{method:D,url:M.url,path:M.path,reported:!1}):H.delete(this)}catch(N){o.log("xhr open observation failed",N)}return i}}.open,T={send(...x){let i=m&&C?H.get(this):void 0;if(!i||i.reported||i.cleanupListeners)return Reflect.apply(j,this,x);let I=()=>{},N=!1;try{i.requestId=ve();let M={direction:"request",transport:"xhr",method:i.method,url:i.url,path:i.path};i.requestBody=u&&typeof x[0]=="string"?d(x[0],M,l):void 0;let Z=()=>{i.outcome===void 0&&(i.outcome="abort")},ee=()=>{i.outcome===void 0&&(i.outcome="timeout")},w=()=>{i.outcome===void 0&&(i.outcome="error")},k=()=>{var X;I();try{if(!m||!C||i.reported||!i.requestId)return;i.reported=!0;let V={direction:"response",transport:"xhr",method:i.method,url:i.url,path:i.path},se=this.status,pe={requestId:i.requestId,transport:"xhr",method:i.method,url:i.url,path:i.path,status:se,ok:se>=200&&se<300,outcome:(X=i.outcome)!=null?X:"load",durationMs:i.startedAt!==void 0?Date.now()-i.startedAt:void 0,responseUrl:this.responseURL||void 0,requestBody:i.requestBody,responseBody:q?ze(this,Pe=>d(Pe,V,A)):void 0};i.requestEmitted?R(pe):i.pendingExchange=pe}catch(V){o.log("xhr exchange observation failed",V)}finally{H.get(this)===i&&H.delete(this)}},F=()=>{try{this.readyState===XMLHttpRequest.DONE&&this.status!==0&&k()}catch(X){o.log("xhr ready-state observation failed",X)}},_=()=>k();I=()=>{for(let[X,V]of[["readystatechange",F],["abort",Z],["timeout",ee],["error",w],["loadend",_]])this.removeEventListener(X,V);i.cleanupListeners===I&&(i.cleanupListeners=void 0),a.delete(I)},this.addEventListener("readystatechange",F),this.addEventListener("abort",Z),this.addEventListener("timeout",ee),this.addEventListener("error",w),this.addEventListener("loadend",_),i.cleanupListeners=I,a.add(I),i.startedAt=Date.now(),N=!0}catch(M){o.log("xhr send observation failed",M),I()}let D;try{D=Reflect.apply(j,this,x)}catch(M){throw I(),M}if(N&&i.requestId!==void 0&&i.startedAt!==void 0){i.requestEmitted=!0,L({requestId:i.requestId,transport:"xhr",method:i.method,url:i.url,path:i.path,startedAt:i.startedAt,requestBody:i.requestBody});let M=i.pendingExchange;i.pendingExchange=void 0,M&&R(M)}return D}}.send;return K(S,O),K(T,j),p.writable!==!0||c.writable!==!0?(o.log("xhr capture unavailable: XMLHttpRequest methods are not writable"),null):(Object.defineProperty(s,"open",{...p,value:S}),Object.defineProperty(s,"send",{...c,value:T}),C=!0,()=>{C=!1;for(let x of[...a])x();Y(s,"open",S,p,o),Y(s,"send",T,c,o)})},b=()=>{let s=globalThis,p=Object.getOwnPropertyDescriptor(s,"fetch");if(!p||!("value"in p))return o.log("fetch capture unavailable: fetch is not an own data property"),null;let c=p.value;if(typeof c!="function")return o.log("fetch capture unavailable: fetch missing"),null;if(U(c))return o.log("fetch capture unavailable: an equivalent capture is already active"),null;let O=!1,j=async(a,C,S,T)=>{try{if(!m||!O){ce(S);return}let[x,i]=await Promise.all([T!=null?T:Promise.resolve(void 0),S?Re(S,o):Promise.resolve(void 0)]);if(!m||!O)return;let I={direction:"request",transport:"fetch",method:a.method,url:a.url,path:a.path},N={...I,direction:"response"},D=a.requestBody;D===void 0&&x!==void 0&&(D=d(x,I,l));let M=i!==void 0?d(i,N,A):void 0;R({requestId:a.requestId,transport:"fetch",method:a.method,url:a.url,path:a.path,status:C.status,ok:C.ok,outcome:"load",durationMs:Date.now()-a.startedAt,responseUrl:C.url||void 0,requestBody:D,responseBody:M})}catch(x){o.log("fetch exchange observation failed",x)}},H={fetch(...a){var D,M,Z,ee;let C;try{let w=a[0],k=a[1];if(m&&O&&u&&typeof Request!="undefined"&&w instanceof Request&&(k==null?void 0:k.body)===void 0&&w.body){let F=String((D=k==null?void 0:k.method)!=null?D:w.method).toUpperCase(),_=(M=w.headers.get("content-type"))!=null?M:"";f(w.url,F)&&Ce(_)&&(C=w.clone())}}catch(w){o.log("fetch observation failed",w)}let S,T=Date.now();try{S=Reflect.apply(c,this,a)}catch(w){throw ce(C),w}let x,i;try{if(m&&O){let w=a[0],k=a[1],F=typeof Request!="undefined"&&w instanceof Request,_=String((Z=k==null?void 0:k.method)!=null?Z:F?w.method:"GET").toUpperCase(),X=F?w.url:w,V=f(X,_);V&&(x={requestId:ve(),method:_,url:V.url,path:V.path,startedAt:T},i=(ee=k==null?void 0:k.signal)!=null?ee:F?w.signal:void 0,u&&typeof(k==null?void 0:k.body)=="string"&&(x.requestBody=d(k.body,{direction:"request",transport:"fetch",method:_,url:V.url,path:V.path},l)))}}catch(w){o.log("fetch observation failed",w)}if(!x)return ce(C),S;let I=x;L({requestId:I.requestId,transport:"fetch",method:I.method,url:I.url,path:I.path,startedAt:I.startedAt,requestBody:I.requestBody});let N=C?Re(C,o):void 0;return S.then(w=>{var F;let k;try{if(m&&O&&q){let _=(F=w.headers.get("content-type"))!=null?F:"";Ce(_)&&w.body&&(k=w.clone())}}catch{}j(I,w,k,N)},w=>{try{if(!m||!O)return;let k=(i==null?void 0:i.aborted)===!0||(w==null?void 0:w.name)==="AbortError"||typeof DOMException!="undefined"&&w instanceof DOMException&&w.code===DOMException.ABORT_ERR;R({requestId:I.requestId,transport:"fetch",method:I.method,url:I.url,path:I.path,status:0,ok:!1,outcome:k?"abort":"error",durationMs:Date.now()-I.startedAt})}catch(k){o.log("fetch failure observation failed",k)}}),S}}.fetch;return K(H,c),p.writable!==!0?(o.log("fetch capture unavailable: fetch is not writable"),null):(Object.defineProperty(s,"fetch",{...p,value:H}),O=!0,()=>{O=!1,Y(s,"fetch",H,p,o)})},P=[];if(y.includes("xhr")){let s=g();s&&P.push(s)}if(y.includes("fetch")){let s=b();s&&P.push(s)}return P.length===0?B():(m=!0,{mode:"standard",disconnect:()=>{m=!1;for(let s of P.splice(0))s()}})}function ke(e){let t=e.onNavigate;if(typeof t!="function")throw new TypeError("captureNavigation requires an onNavigate callback");let n=W(e.logger),r,o,y,l,A,u;try{if(r=window,o=r==null?void 0:r.history,!r||!o)return n.log("navigation capture unavailable: window/history missing"),B();if(A=xe(o,"pushState"),u=xe(o,"replaceState"),!A||!u)return n.log("navigation capture unavailable: history method descriptors missing"),B();if(y=A.descriptor.value,l=u.descriptor.value,typeof y!="function"||typeof l!="function")return n.log("navigation capture unavailable: history methods missing"),B();if(typeof r.addEventListener!="function"||typeof r.removeEventListener!="function")return n.log("navigation capture unavailable: window event methods missing"),B()}catch(h){return n.log("navigation capture unavailable: history inspection failed",h),B()}if(U(y)||U(l))return n.log("navigation capture unavailable: an equivalent capture is already active"),B();let q=!1,m=()=>({path:r.location.pathname,search:r.location.search,hash:r.location.hash}),R;try{R=m()}catch(h){return n.log("navigation capture unavailable: location inspection failed",h),B()}let L=z(n,"navigation",h=>{if(q)return t(h)}),d=h=>{if(q)try{let E=m();if(E.path===R.path&&E.search===R.search&&E.hash===R.hash)return;R=E,L({...E,source:h})}catch(E){n.log("navigation observation failed",E)}},f={pushState(...h){let E=Reflect.apply(y,this,h);return d("push"),E}}.pushState,g={replaceState(...h){let E=Reflect.apply(l,this,h);return d("replace"),E}}.replaceState;K(f,y),K(g,l);let b=()=>d("pop"),P=()=>d("hash");try{if(Ie(A,f),Ie(u,g),o.pushState!==f||o.replaceState!==g)throw new Error("history method replacement did not take effect");r.addEventListener("popstate",b),r.addEventListener("hashchange",P),q=!0}catch(h){return q=!1,ae(r,"popstate",b,n),ae(r,"hashchange",P,n),ie(u,g,n),ie(A,f,n),n.log("navigation capture unavailable: history methods are not writable",h),t=()=>{},L=()=>{},n=W(),B()}return{mode:"standard",disconnect:()=>{q=!1,t=()=>{},ae(r,"popstate",b,n),ae(r,"hashchange",P,n),ie(A,f,n),ie(u,g,n),L=()=>{},n=W()}}}function xe(e,t){let n=e;for(;n;){let r=Object.getOwnPropertyDescriptor(n,t);if(r)return!("value"in r)||typeof r.value!="function"?null:{owner:n,key:t,descriptor:r};n=Object.getPrototypeOf(n)}return null}function Ie(e,t){if(e.descriptor.writable!==!0)throw new TypeError(`${e.key} is not writable`);let n=Object.getOwnPropertyDescriptor(e.owner,e.key);if(!de(n,e.descriptor))throw new Error(`${e.key} changed during installation`);Object.defineProperty(e.owner,e.key,{...e.descriptor,value:t})}function ie(e,t,n){Y(e.owner,e.key,t,e.descriptor,n,`navigation ${e.key}`)}function ae(e,t,n,r){try{e.removeEventListener(t,n)}catch(o){r.log(`navigation ${t} listener removal skipped`,o)}}function Ae(e){let t=e.composedPath();return t.length>0?t:e.target?[e.target]:[]}var qe="1.2.0";var $e=["valueMissing","typeMismatch","patternMismatch","tooShort","tooLong","rangeUnderflow","rangeOverflow","stepMismatch","badInput","customError"];function le(e){return $e.find(t=>e.validity[t])}function Oe(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 r=t.getComputedStyle(n);if(n.hasAttribute("hidden")||r.display==="none"||r.visibility==="hidden"||r.visibility==="collapse"||r.opacity==="0")return!1}return!0}function Se(e){var j,H;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],r=(j=e.maxObservationMs)!=null?j:1e4;if(!n.length||!Number.isFinite(r)||r<=0)throw new TypeError("captureInputValidation requires fields and a positive maxObservationMs");let o={mode:"unavailable",disconnect(){},beginAttempt:()=>{},requestStarted(){},refresh(){}},y=(H=t==null?void 0:t.ownerDocument)==null?void 0:H.defaultView;if(!y||!n.every(a=>a.form===t))return o;let l=!0,A=0,u,q=!1,m,R,L,d,f=[],g=()=>t.isConnected&&n.every(a=>a.isConnected&&a.form===t),b=()=>{try{let a=e.readValidation();if(a&&["clear","pending","unknown"].includes(a.status)||(a==null?void 0:a.status)==="invalid"&&typeof a.code=="string"&&["constraint","application"].includes(a.source))return a}catch{}return{status:"unknown"}},P=a=>a.status==="invalid"?JSON.stringify([a.code,a.fieldIndex]):void 0,h=()=>{u=void 0,clearTimeout(R),clearTimeout(L),R=L=void 0},E=()=>{R=void 0;let a=u;if(!l||!(a!=null&&a.confirmed))return;if(!g()){h();return}let C=a.nativeInvalid?(()=>{for(let[T,x]of n.entries()){let i=le(x);if(i)return{status:"invalid",source:"constraint",code:i,fieldIndex:T}}return{status:"clear"}})():b();if(C.status==="clear"){a.serverBaseline=void 0;return}if(C.status!=="invalid"||C.source==="application"&&a.serverBaseline===P(C))return;let S={attemptId:a.id,startedAt:a.startedAt,timestamp:Date.now(),code:C.code,...C.fieldIndex===void 0?{}:{fieldIndex:C.fieldIndex}};h(),q=!1;try{Promise.resolve(e.onError(S)).catch(()=>{})}catch{}},v=()=>{!l||!u||R!==void 0||(R=setTimeout(E,0))},s=a=>{if(!l||!g())return;h();let C=q?P(b()):void 0;return u={id:++A,startedAt:Date.now(),confirmed:a,nativeInvalid:!1,serverBaseline:C},L=setTimeout(h,r),v(),u.id},p=()=>{m===void 0&&(m=s(!1),d=setTimeout(()=>{u&&u.id===m&&!u.confirmed&&h(),m=void 0},0))},c=(a,C,S)=>{a.addEventListener(C,S,!0),f.push(()=>a.removeEventListener(C,S,!0))},O={mode:"standard",beginAttempt:()=>s(!0),refresh:v,requestStarted(a={}){l&&(a.attemptId!==void 0&&a.attemptId!==(u==null?void 0:u.id)||u&&a.timestamp!==void 0&&a.timestamp<u.startedAt||(h(),q=!0))},disconnect(){if(l){l=!1,h(),clearTimeout(d);for(let a of f.splice(0))a()}}};try{let a=S=>{var i;let T=S.target,x=(i=T==null?void 0:T.closest)==null?void 0:i.call(T,"button,input");(x==null?void 0:x.form)===t&&!x.disabled&&["submit","image"].includes(x.type)&&p()};c(t.ownerDocument,"click",a),c(t,"click",a),c(t,"keydown",S=>{let T=S;T.key==="Enter"&&!T.isComposing&&!T.defaultPrevented&&n.includes(T.target)&&p()}),c(t,"submit",()=>{(u==null?void 0:u.id)===m&&u?(u.confirmed=!0,v()):s(!0),m=void 0}),c(t,"invalid",S=>{!u||!n.includes(S.target)||(u.confirmed=!0,u.nativeInvalid=!0,v())}),c(t,"input",S=>{n.includes(S.target)&&h()});let C=new y.MutationObserver(v);C.observe(t,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),f.push(()=>C.disconnect())}catch{return O.disconnect(),o}return O}var G=require("@corbado/observe");0&&(module.exports={VERSION,captureFederatedIdentity,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 R,b as P,c as D,d as L,e as H,f as _,g as $,h as Q}from"./chunk-GWLL2VST.mjs";import"./chunk-JR557W27.mjs";import{sanitizeCreationOptions as Y,sanitizeCreationResponse as Z,sanitizeRequestOptions as G,sanitizeAssertionResponse as ee}from"@corbado/observe";var U=e=>({get:e("get"),create:e("create")}),T;function q(e){if(T)return[...T.subscribers].some(n=>n.channel===e.channel)?{attached:!1,reason:"an equivalent capture is already active"}:B(T,e);let t=X(e);return typeof t=="string"?{attached:!1,reason:t}:(T=t,B(t,e))}function B(e,t){e.subscribers.add(t);let n=!0;return{attached:!0,surface:e.surface,unsubscribe:()=>{n&&(n=!1,e.subscribers.delete(t),!(e.subscribers.size>0)&&(e.active=!1,e.detach(),T===e&&(T=void 0)))}}}function X(e){let t=typeof navigator=="undefined"?void 0:navigator,n=t==null?void 0:t.credentials;if(!t||!n)return"navigator.credentials missing";let o=n,b=U(i=>o[i]);if(typeof b.get!="function"||typeof b.create!="function")return"credentials methods missing";if(P(b.get)||P(b.create))return"an equivalent capture is already active";let I={surface:"methods",subscribers:new Set,active:!1,detach:()=>{}},m=(...i)=>I.subscribers.forEach(l=>l.logger.log(...i)),O=(i,l,s)=>{let u={invoke(...C){let h=C[0];if(!I.active||s!=null&&s()||!S(h))return l(this,C);let E=l(this,C),d=[];for(let p of[...I.subscribers])try{let c=p.onCall(i,h);c&&d.push([p,c])}catch(c){p.logger.log("credentials observation failed",c)}if(d.length===0)return E;let f=p=>{for(let[c,F]of d)try{p(F)}catch(W){c.logger.log("credentials observation failed",W)}};return Promise.resolve(E).then(p=>(f(c=>c.completed(p)),p),p=>{throw f(c=>c.failed(p)),p})}}.invoke;return D(u,{name:i,length:0})},a=i=>{var u;let l=O(i,(C,h)=>Reflect.apply(b[i],C,h)),s=Object.getOwnPropertyDescriptor(n,i);if(s&&(!("value"in s)||s.writable!==!0))return null;try{o[i]=l}catch{return null}if(((u=Object.getOwnPropertyDescriptor(n,i))==null?void 0:u.value)!==l){try{o[i]=b[i]}catch{}return null}return()=>{o[i]===l&&(s?o[i]=s.value:delete o[i])}},g=()=>{let i=U(()=>new WeakMap),l=(E,d)=>{let f=i[E].get(d);if(f)return f;let p=O(E,(c,F)=>Reflect.apply(d,n,F),()=>{try{let c=o[E];return c!==d&&c!==p}catch(c){return m("suppress check failed; ceremony unreported",c),!0}});return i[E].set(d,p),p},s=E=>{let d=Object.getOwnPropertyDescriptor(n,E);return d?d.configurable===!0||!("value"in d)||d.writable===!0:!0},u=new WeakMap,C=new Proxy(n,{get(E,d){let f=Reflect.get(n,d,n);if((d==="get"||d==="create")&&s(d))return typeof f!="function"||P(f)?f:l(d,f);if(typeof f!="function"||!s(d)||d==="constructor")return f;let p=u.get(f);if(p)return p;let c=f.bind(n);return u.set(f,c),c},set(E,d,f){return Reflect.set(n,d,f,n)}}),h=Object.getOwnPropertyDescriptor(t,"credentials");if(h&&h.configurable!==!0)return null;try{Object.defineProperty(t,"credentials",{value:C,writable:!0,enumerable:!0,configurable:!0})}catch{return null}return t.credentials!==C?null:()=>{t.credentials===C&&(h?Object.defineProperty(t,"credentials",h):delete t.credentials)}},v=(i,l)=>(I.surface=i,I.detach=l,I.active=!0,I),y=a("get"),A=y?a("create"):null;if(y&&A)return v("methods",()=>{y(),A()});if(y==null||y(),e.attach==="container"){let i=g();if(i)return v("container",i)}return"credentials methods cannot be patched safely"}function S(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function N(){let e=navigator.userActivation;return typeof(e==null?void 0:e.isActive)=="boolean"?e.isActive:void 0}function j(e){return e===void 0?"optional":e==="silent"||e==="optional"||e==="conditional"||e==="required"?e:"unknown"}function K(e){return e instanceof DOMException?e.name:"UnknownError"}function te(e){var O;let t=e.onEvent;if(typeof t!="function")throw new TypeError("captureWebAuthn requires an onEvent callback");let n=R(e.logger),o=!0,b=0,I=H(n,"webauthn",t),m=q({channel:"webauthn",attach:(O=e.attach)!=null?O:"methods",logger:n,onCall(a,g){if(!o||!S(g.publicKey))return;let v=g.publicKey,y=`wa-${++b}`,A=S(g.signal)?g.signal:void 0,i=ne(a,g,v),l=u=>{o&&I({...i,ceremonyId:y,...u()})},s=()=>(A==null?void 0:A.aborted)===!0?{aborted:!0}:{};return l(()=>({phase:"started",userActivation:N(),...i.kind==="authentication"?{requestOptionsJson:G(v)}:{creationOptionsJson:Y(v,e.identifierProjectors)}})),{completed:u=>l(()=>({phase:"completed",credentialJson:a==="create"?Z(u,e.identifierProjectors):ee(u,e.identifierProjectors),...s()})),failed:u=>l(()=>({phase:"failed",error:u,errorName:K(u),...s()}))}}});return m.attached?(m.surface==="container"&&n.log("webauthn capture attached at the credentials container"),{mode:"standard",surface:m.surface,disconnect:()=>{o=!1,m.unsubscribe()}}):(n.log(`webauthn capture unavailable: ${m.reason}`),{...L(),surface:"none"})}function ne(e,t,n){let o=j(t.mediation);if(e==="create")return{kind:"registration",mediation:o};let b=n;return{kind:"authentication",mediation:o,uiMode:re(t.uiMode),credentialSet:Array.isArray(b.allowCredentials)&&b.allowCredentials.length>0?"allowlisted":"discoverable"}}function re(e){return e===void 0?"default":e==="immediate"?"immediate":"unknown"}function ie(e){var O;let t=e.onEvent;if(typeof t!="function")throw new TypeError("captureFederatedIdentity requires an onEvent callback");let n=R(e.logger),o=!0,b=0,I=H(n,"federated identity",t),m=q({channel:"federated-identity",attach:(O=e.attach)!=null?O:"methods",logger:n,onCall(a,g){let v=g.identity;if(!o||a!=="get"||!S(v))return;let y=`fi-${++b}`,A=S(g.signal)?g.signal:void 0,i=v,l=s=>{o&&I(s)};return l({phase:"started",requestId:y,providers:oe(i.providers),context:ae(i.context),mode:de(i.mode),mediation:j(g.mediation),userActivation:N()}),{completed:s=>{if(s===null){l({phase:"failed",requestId:y,errorName:"NoCredential"});return}let u=s;l({phase:"completed",requestId:y,...typeof u.configURL=="string"?{configURL:u.configURL}:{},...typeof u.isAutoSelected=="boolean"?{isAutoSelected:u.isAutoSelected}:{}})},failed:s=>{let u=K(s),C=u==="IdentityCredentialError"?se(s):void 0;l({phase:"failed",requestId:y,errorName:u,...C!==void 0?{code:C}:{},...(A==null?void 0:A.aborted)===!0?{aborted:!0}:{}})}}}});return m.attached?{mode:"standard",surface:m.surface,disconnect:()=>{o=!1,m.unsubscribe()}}:(n.log(`federated identity capture unavailable: ${m.reason}`),{...L(),surface:"none"})}function oe(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!S(n))continue;let{configURL:o,clientId:b}=n;typeof o=="string"&&t.push(typeof b=="string"?{configURL:o,clientId:b}:{configURL:o})}return t}function ae(e){return e===void 0?"signin":e==="signin"||e==="signup"||e==="use"||e==="continue"?e:"unknown"}function de(e){return e===void 0?"passive":e==="passive"||e==="active"?e:"unknown"}function se(e){let{error:t,code:n}=e;return typeof t=="string"&&t!==""?t:typeof n=="string"&&n!==""?n:void 0}function ue(e){let t=e.composedPath();return t.length>0?t:e.target?[e.target]:[]}var ce=["valueMissing","typeMismatch","patternMismatch","tooShort","tooLong","rangeUnderflow","rangeOverflow","stepMismatch","badInput","customError"];function J(e){return ce.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 o=t.getComputedStyle(n);if(n.hasAttribute("hidden")||o.display==="none"||o.visibility==="hidden"||o.visibility==="collapse"||o.opacity==="0")return!1}return!0}function fe(e){var W,z;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],o=(W=e.maxObservationMs)!=null?W:1e4;if(!n.length||!Number.isFinite(o)||o<=0)throw new TypeError("captureInputValidation requires fields and a positive maxObservationMs");let b={mode:"unavailable",disconnect(){},beginAttempt:()=>{},requestStarted(){},refresh(){}},I=(z=t==null?void 0:t.ownerDocument)==null?void 0:z.defaultView;if(!I||!n.every(r=>r.form===t))return b;let m=!0,O=0,a,g=!1,v,y,A,i,l=[],s=()=>t.isConnected&&n.every(r=>r.isConnected&&r.form===t),u=()=>{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=()=>{a=void 0,clearTimeout(y),clearTimeout(A),y=A=void 0},E=()=>{y=void 0;let r=a;if(!m||!(r!=null&&r.confirmed))return;if(!s()){h();return}let w=r.nativeInvalid?(()=>{for(let[x,M]of n.entries()){let V=J(M);if(V)return{status:"invalid",source:"constraint",code:V,fieldIndex:x}}return{status:"clear"}})():u();if(w.status==="clear"){r.serverBaseline=void 0;return}if(w.status!=="invalid"||w.source==="application"&&r.serverBaseline===C(w))return;let k={attemptId:r.id,startedAt:r.startedAt,timestamp:Date.now(),code:w.code,...w.fieldIndex===void 0?{}:{fieldIndex:w.fieldIndex}};h(),g=!1;try{Promise.resolve(e.onError(k)).catch(()=>{})}catch{}},d=()=>{!m||!a||y!==void 0||(y=setTimeout(E,0))},f=r=>{if(!m||!s())return;h();let w=g?C(u()):void 0;return a={id:++O,startedAt:Date.now(),confirmed:r,nativeInvalid:!1,serverBaseline:w},A=setTimeout(h,o),d(),a.id},p=()=>{v===void 0&&(v=f(!1),i=setTimeout(()=>{a&&a.id===v&&!a.confirmed&&h(),v=void 0},0))},c=(r,w,k)=>{r.addEventListener(w,k,!0),l.push(()=>r.removeEventListener(w,k,!0))},F={mode:"standard",beginAttempt:()=>f(!0),refresh:d,requestStarted(r={}){m&&(r.attemptId!==void 0&&r.attemptId!==(a==null?void 0:a.id)||a&&r.timestamp!==void 0&&r.timestamp<a.startedAt||(h(),g=!0))},disconnect(){if(m){m=!1,h(),clearTimeout(i);for(let r of l.splice(0))r()}}};try{let r=k=>{var V;let x=k.target,M=(V=x==null?void 0:x.closest)==null?void 0:V.call(x,"button,input");(M==null?void 0:M.form)===t&&!M.disabled&&["submit","image"].includes(M.type)&&p()};c(t.ownerDocument,"click",r),c(t,"click",r),c(t,"keydown",k=>{let x=k;x.key==="Enter"&&!x.isComposing&&!x.defaultPrevented&&n.includes(x.target)&&p()}),c(t,"submit",()=>{(a==null?void 0:a.id)===v&&a?(a.confirmed=!0,d()):f(!0),v=void 0}),c(t,"invalid",k=>{!a||!n.includes(k.target)||(a.confirmed=!0,a.nativeInvalid=!0,d())}),c(t,"input",k=>{n.includes(k.target)&&h()});let w=new I.MutationObserver(d);w.observe(t,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),l.push(()=>w.disconnect())}catch{return F.disconnect(),b}return F}import{sanitizeCreationOptions as We,sanitizeCreationResponse as Re,sanitizeRequestOptions as Pe,sanitizeAssertionResponse as Le}from"@corbado/observe";export{Q as VERSION,ie as captureFederatedIdentity,fe as captureInputValidation,$ as captureNavigation,_ as captureNetwork,te as captureWebAuthn,ue as composedPath,J as inputValidationCode,le as isValidationMessageVisible,Le as sanitizeAssertionResponse,We as sanitizeCreationOptions,Re as sanitizeCreationResponse,Pe as sanitizeRequestOptions};
@@ -0,0 +1,38 @@
1
+ import { P as ProbeConfig } from '../guards-BmrxoYBR.mjs';
2
+ export { E as applyGuards, F as createProbeTaint } from '../guards-BmrxoYBR.mjs';
3
+ import '../types-lamU1Fd3.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-Bwsr1zMi.js';
2
+ export { E as applyGuards, F as createProbeTaint } from '../guards-Bwsr1zMi.js';
3
+ import '../types-lamU1Fd3.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 };