@corbado/autocapture 0.6.0 → 0.7.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/README.md +11 -0
- package/dist/index.d.mts +55 -1
- package/dist/index.d.ts +55 -1
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -202,3 +202,14 @@ runtime. The current real-browser suite covers current
|
|
|
202
202
|
Chromium, Firefox, and WebKit, with password-manager simulation and virtual WebAuthn in Chromium.
|
|
203
203
|
That is not yet evidence for old iOS, Android WebView, legacy Edge, or arbitrary polyfills; expanding
|
|
204
204
|
the declared browser floor and test matrix is an open release decision.
|
|
205
|
+
|
|
206
|
+
## Input validation
|
|
207
|
+
|
|
208
|
+
`captureInputValidation()` observes one logical operation's fields and reports at most one local
|
|
209
|
+
validation error per submission attempt. Supply a validation-state reader and feed matching request
|
|
210
|
+
starts from your existing network capture. Native constraints, custom/auto-submit entry points,
|
|
211
|
+
multi-input groups, repeated submissions, server-error suppression, and cleanup are supported.
|
|
212
|
+
It does not activate automatically or collect field values/message text.
|
|
213
|
+
|
|
214
|
+
See [the API and evidence contract](src/input-validation.contract.md), including the limits of
|
|
215
|
+
asynchronous DOM inference and the `beginAttempt()`, `requestStarted()`, and `refresh()` methods.
|
package/dist/index.d.mts
CHANGED
|
@@ -313,6 +313,60 @@ declare function composedPath(event: Event): readonly EventTarget[];
|
|
|
313
313
|
/** Version identifier embedded in the current build. */
|
|
314
314
|
declare const VERSION: string;
|
|
315
315
|
|
|
316
|
+
/** Application UI state, read without copying field values or message text. */
|
|
317
|
+
type InputValidationState = {
|
|
318
|
+
status: "clear" | "pending" | "unknown";
|
|
319
|
+
} | {
|
|
320
|
+
status: "invalid";
|
|
321
|
+
/** A stable constraint/rule name, never a rendered message or field value. */
|
|
322
|
+
code: string;
|
|
323
|
+
/** Native constraint evidence can distinguish a new local error from a stale server error. */
|
|
324
|
+
source: "constraint" | "application";
|
|
325
|
+
/** Index into `fields` for operations owning multiple inputs. */
|
|
326
|
+
fieldIndex?: number;
|
|
327
|
+
};
|
|
328
|
+
type InputValidationError = {
|
|
329
|
+
attemptId: number;
|
|
330
|
+
startedAt: number;
|
|
331
|
+
timestamp: number;
|
|
332
|
+
code: string;
|
|
333
|
+
fieldIndex?: number;
|
|
334
|
+
};
|
|
335
|
+
type InputValidationCaptureOptions = {
|
|
336
|
+
form: HTMLFormElement;
|
|
337
|
+
/** One logical operation's inputs; do not include unrelated fields on the same form. */
|
|
338
|
+
fields: readonly HTMLInputElement[];
|
|
339
|
+
/**
|
|
340
|
+
* Read the application's settled validation UI. Return pending during asynchronous validation,
|
|
341
|
+
* and unknown when local rejection cannot be established. A bare aria-invalid flag is insufficient.
|
|
342
|
+
*/
|
|
343
|
+
readValidation: () => InputValidationState;
|
|
344
|
+
onError: (event: InputValidationError) => void;
|
|
345
|
+
/** Cleanup deadline for unresolved attempts. Expiration NEVER emits a validation error. Default 10s. */
|
|
346
|
+
maxObservationMs?: number;
|
|
347
|
+
};
|
|
348
|
+
type InputValidationCaptureHandle = CaptureHandle & {
|
|
349
|
+
/** Custom/auto-submit path; call before the application validates. Returns the attempt ID. */
|
|
350
|
+
beginAttempt(): number | undefined;
|
|
351
|
+
/** Feed only this operation's submission request, at request START, regardless of its eventual result. */
|
|
352
|
+
requestStarted(request?: {
|
|
353
|
+
timestamp?: number;
|
|
354
|
+
attemptId?: number;
|
|
355
|
+
}): void;
|
|
356
|
+
/** Re-read after an application validation signal that is not represented by a DOM mutation. */
|
|
357
|
+
refresh(): void;
|
|
358
|
+
};
|
|
359
|
+
/** Reads native validity flags without invoking checkValidity/reportValidity or accessing the value. */
|
|
360
|
+
declare function inputValidationCode(input: HTMLInputElement): string | undefined;
|
|
361
|
+
/** Rendered visibility, including hidden ancestors and opacity; does not require viewport intersection. */
|
|
362
|
+
declare function isValidationMessageVisible(element: Element | null): boolean;
|
|
363
|
+
/**
|
|
364
|
+
* Observes submission attempts for one input-backed operation. Never prevents submission, mutates
|
|
365
|
+
* validation, or installs a network interceptor. One error at most per attempt, even with several
|
|
366
|
+
* inputs or repeated DOM mutations. See input-validation.contract.md for the evidence boundary.
|
|
367
|
+
*/
|
|
368
|
+
declare function captureInputValidation(options: InputValidationCaptureOptions): InputValidationCaptureHandle;
|
|
369
|
+
|
|
316
370
|
/** Sanitizes publicKey creation options (native values, JSON object, or JSON string). */
|
|
317
371
|
declare function sanitizeCreationOptions(value: unknown): string | undefined;
|
|
318
372
|
/** Sanitizes a registration credential; keeps attestation material but removes PRF results. */
|
|
@@ -322,4 +376,4 @@ declare function sanitizeRequestOptions(value: unknown): string | undefined;
|
|
|
322
376
|
/** Sanitizes an authentication credential; removes its login signature and PRF results. */
|
|
323
377
|
declare function sanitizeAssertionResponse(value: unknown): string | undefined;
|
|
324
378
|
|
|
325
|
-
export { type CaptureHandle, type HttpExchange, type HttpRequestStarted, 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, captureNavigation, captureNetwork, captureWebAuthn, composedPath, sanitizeAssertionResponse, sanitizeCreationOptions, sanitizeCreationResponse, sanitizeRequestOptions };
|
|
379
|
+
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, sanitizeAssertionResponse, sanitizeCreationOptions, sanitizeCreationResponse, sanitizeRequestOptions };
|
package/dist/index.d.ts
CHANGED
|
@@ -313,6 +313,60 @@ declare function composedPath(event: Event): readonly EventTarget[];
|
|
|
313
313
|
/** Version identifier embedded in the current build. */
|
|
314
314
|
declare const VERSION: string;
|
|
315
315
|
|
|
316
|
+
/** Application UI state, read without copying field values or message text. */
|
|
317
|
+
type InputValidationState = {
|
|
318
|
+
status: "clear" | "pending" | "unknown";
|
|
319
|
+
} | {
|
|
320
|
+
status: "invalid";
|
|
321
|
+
/** A stable constraint/rule name, never a rendered message or field value. */
|
|
322
|
+
code: string;
|
|
323
|
+
/** Native constraint evidence can distinguish a new local error from a stale server error. */
|
|
324
|
+
source: "constraint" | "application";
|
|
325
|
+
/** Index into `fields` for operations owning multiple inputs. */
|
|
326
|
+
fieldIndex?: number;
|
|
327
|
+
};
|
|
328
|
+
type InputValidationError = {
|
|
329
|
+
attemptId: number;
|
|
330
|
+
startedAt: number;
|
|
331
|
+
timestamp: number;
|
|
332
|
+
code: string;
|
|
333
|
+
fieldIndex?: number;
|
|
334
|
+
};
|
|
335
|
+
type InputValidationCaptureOptions = {
|
|
336
|
+
form: HTMLFormElement;
|
|
337
|
+
/** One logical operation's inputs; do not include unrelated fields on the same form. */
|
|
338
|
+
fields: readonly HTMLInputElement[];
|
|
339
|
+
/**
|
|
340
|
+
* Read the application's settled validation UI. Return pending during asynchronous validation,
|
|
341
|
+
* and unknown when local rejection cannot be established. A bare aria-invalid flag is insufficient.
|
|
342
|
+
*/
|
|
343
|
+
readValidation: () => InputValidationState;
|
|
344
|
+
onError: (event: InputValidationError) => void;
|
|
345
|
+
/** Cleanup deadline for unresolved attempts. Expiration NEVER emits a validation error. Default 10s. */
|
|
346
|
+
maxObservationMs?: number;
|
|
347
|
+
};
|
|
348
|
+
type InputValidationCaptureHandle = CaptureHandle & {
|
|
349
|
+
/** Custom/auto-submit path; call before the application validates. Returns the attempt ID. */
|
|
350
|
+
beginAttempt(): number | undefined;
|
|
351
|
+
/** Feed only this operation's submission request, at request START, regardless of its eventual result. */
|
|
352
|
+
requestStarted(request?: {
|
|
353
|
+
timestamp?: number;
|
|
354
|
+
attemptId?: number;
|
|
355
|
+
}): void;
|
|
356
|
+
/** Re-read after an application validation signal that is not represented by a DOM mutation. */
|
|
357
|
+
refresh(): void;
|
|
358
|
+
};
|
|
359
|
+
/** Reads native validity flags without invoking checkValidity/reportValidity or accessing the value. */
|
|
360
|
+
declare function inputValidationCode(input: HTMLInputElement): string | undefined;
|
|
361
|
+
/** Rendered visibility, including hidden ancestors and opacity; does not require viewport intersection. */
|
|
362
|
+
declare function isValidationMessageVisible(element: Element | null): boolean;
|
|
363
|
+
/**
|
|
364
|
+
* Observes submission attempts for one input-backed operation. Never prevents submission, mutates
|
|
365
|
+
* validation, or installs a network interceptor. One error at most per attempt, even with several
|
|
366
|
+
* inputs or repeated DOM mutations. See input-validation.contract.md for the evidence boundary.
|
|
367
|
+
*/
|
|
368
|
+
declare function captureInputValidation(options: InputValidationCaptureOptions): InputValidationCaptureHandle;
|
|
369
|
+
|
|
316
370
|
/** Sanitizes publicKey creation options (native values, JSON object, or JSON string). */
|
|
317
371
|
declare function sanitizeCreationOptions(value: unknown): string | undefined;
|
|
318
372
|
/** Sanitizes a registration credential; keeps attestation material but removes PRF results. */
|
|
@@ -322,4 +376,4 @@ declare function sanitizeRequestOptions(value: unknown): string | undefined;
|
|
|
322
376
|
/** Sanitizes an authentication credential; removes its login signature and PRF results. */
|
|
323
377
|
declare function sanitizeAssertionResponse(value: unknown): string | undefined;
|
|
324
378
|
|
|
325
|
-
export { type CaptureHandle, type HttpExchange, type HttpRequestStarted, 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, captureNavigation, captureNetwork, captureWebAuthn, composedPath, sanitizeAssertionResponse, sanitizeCreationOptions, sanitizeCreationResponse, sanitizeRequestOptions };
|
|
379
|
+
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, sanitizeAssertionResponse, sanitizeCreationOptions, sanitizeCreationResponse, sanitizeRequestOptions };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var ae=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var ke=Object.getOwnPropertyNames;var xe=Object.prototype.hasOwnProperty;var Pe=(e,t)=>{for(var n in t)ae(e,n,{get:t[n],enumerable:!0})},Ee=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ke(t))!xe.call(e,r)&&r!==n&&ae(e,r,{get:()=>t[r],enumerable:!(o=Ae(t,r))||o.enumerable});return e};var Se=e=>Ee(ae({},"__esModule",{value:!0}),e);var Ue={};Pe(Ue,{VERSION:()=>Ce,captureNavigation:()=>Re,captureNetwork:()=>ve,captureWebAuthn:()=>pe,composedPath:()=>Oe,sanitizeAssertionResponse:()=>ee,sanitizeCreationOptions:()=>Y,sanitizeCreationResponse:()=>Q,sanitizeRequestOptions:()=>Z});module.exports=Se(Ue);var Be={creationOptions:["/user/name","/user/displayName"],creationResponse:["/clientExtensionResults/prf/results"],requestOptions:[],assertionResponse:["/response/signature","/clientExtensionResults/prf/results"]};function Y(e){return te(e,"creationOptions")}function Q(e){return te(e,"creationResponse")}function Z(e){return te(e,"requestOptions")}function ee(e){return te(e,"assertionResponse")}function te(e,t){try{let n=typeof e=="string"?JSON.parse(e):e;if(!Ne(n))return;let o=new Set(Be[t]),r=new Set,u=(i,y,m=0)=>{if(!o.has(y)){if(i===null||typeof i=="string"||typeof i=="boolean")return i;if(typeof i=="number")return Number.isFinite(i)?i:null;if(typeof i=="object"){if(i instanceof ArrayBuffer||ArrayBuffer.isView(i))return je(i);if(m>64||r.has(i))throw new TypeError("Invalid telemetry payload");r.add(i);try{if(Array.isArray(i))return i.map((P,C)=>u(P,`${y}/${C}`,m+1));let j=Object.create(null);for(let P in i){let C=`${y}/${P.replace(/~/g,"~0").replace(/\//g,"~1")}`;if(o.has(C)||P==="toJSON")continue;let S=u(i[P],C,m+1);S!==void 0&&(j[P]=S)}let O=i,x=(P,C)=>{if(j[C]!==void 0||typeof O[P]!="function")return;let S=`${y}/${C}`,B=u(Reflect.apply(O[P],i,[]),S,m+1);B!==void 0&&(j[C]=B)};return y===""&&(t==="creationResponse"||t==="assertionResponse")&&x("getClientExtensionResults","clientExtensionResults"),y==="/response"&&t==="creationResponse"&&(x("getTransports","transports"),x("getAuthenticatorData","authenticatorData"),x("getPublicKey","publicKey"),x("getPublicKeyAlgorithm","publicKeyAlgorithm")),j}finally{r.delete(i)}}}};return JSON.stringify(u(n,""))}catch{return}}function Ne(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e)}function je(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n="";for(let o of t)n+=String.fromCharCode(o);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var De={log:()=>{}};function K(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 de=Symbol.for("corbado.autocapture.installed");function W(e){try{return typeof e=="function"&&Object.prototype.hasOwnProperty.call(e,de)}catch{return!1}}function F(e,t){var o,r;let n=t;try{Object.defineProperty(e,de,{value:t,configurable:!0})}catch{}try{Object.defineProperty(e,"name",{value:(o=n.name)!=null?o:"",configurable:!0})}catch{}try{Object.defineProperty(e,"length",{value:(r=n.length)!=null?r:0,configurable:!0})}catch{}return e}function T(){return{mode:"unavailable",disconnect:()=>{}}}function ie(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 J(e,t,n,o,r,u=String(t)){try{let i=Object.getOwnPropertyDescriptor(e,t);ie(i,{...o,value:n})&&Object.defineProperty(e,t,o)}catch(i){r.log(`${u} restoration skipped`,i)}}function X(e,t,n){let o=K(e);return r=>{try{let u=n(r);if(u&&(typeof u=="object"||typeof u=="function"))try{Promise.resolve(u).catch(i=>o.log(`${t} listener failed`,i))}catch(i){o.log(`${t} listener failed`,i)}}catch(u){o.log(`${t} listener failed`,u)}}}var le=e=>({get:e("get"),create:e("create")});function pe(e){let t=e.onEvent;if(typeof t!="function")throw new TypeError("captureWebAuthn requires an onEvent callback");let n=K(e.logger),o=d=>(n.log(`webauthn capture unavailable: ${d}`),{...T(),surface:"none"}),r=typeof navigator=="undefined"?void 0:navigator,u=r==null?void 0:r.credentials;if(!r||!u)return o("navigator.credentials missing");let i=u,y=le(d=>i[d]);if(typeof y.get!="function"||typeof y.create!="function")return o("credentials methods missing");if(W(y.get)||W(y.create))return o("an equivalent capture is already active");let m=!1,j=0,O=X(n,"webauthn",t),x=(d,g,b)=>{let _={invoke(...c){let l=c[0];if(!m||b!=null&&b()||!se(l)||!se(l.publicKey))return g(this,c);let h=l.publicKey,s=`wa-${++j}`,R=g(this,c),q=se(l.signal)?l.signal:void 0,f=Le(d,l,h),A=E=>{m&&O({...f,ceremonyId:s,...E()})},D=()=>(q==null?void 0:q.aborted)===!0?{aborted:!0}:{};return A(()=>({phase:"started",userActivation:Me(r),...f.kind==="authentication"?{requestOptionsJson:Z(h)}:{creationOptionsJson:Y(h)}})),Promise.resolve(R).then(E=>(A(()=>({phase:"completed",credentialJson:d==="create"?Q(E):ee(E),...D()})),E),E=>{throw A(()=>({phase:"failed",error:E,errorName:Ie(E),...D()})),E})}}.invoke;return F(_,{name:d,length:0})},P=d=>{var _;let g=x(d,(c,l)=>Reflect.apply(y[d],c,l)),b=Object.getOwnPropertyDescriptor(u,d);if(b&&(!("value"in b)||b.writable!==!0))return null;try{i[d]=g}catch{return null}if(((_=Object.getOwnPropertyDescriptor(u,d))==null?void 0:_.value)!==g){try{i[d]=y[d]}catch{}return null}return()=>{i[d]===g&&(b?i[d]=b.value:delete i[d])}},C=()=>{let d=le(()=>new WeakMap),g=(h,s)=>{let R=d[h].get(s);if(R)return R;let q=x(h,(f,A)=>Reflect.apply(s,u,A),()=>{try{let f=i[h];return f!==s&&f!==q}catch(f){return n.log("suppress check failed; ceremony unreported",f),!0}});return d[h].set(s,q),q},b=h=>{let s=Object.getOwnPropertyDescriptor(u,h);return s?s.configurable===!0||!("value"in s)||s.writable===!0:!0},_=new WeakMap,c=new Proxy(u,{get(h,s){let R=Reflect.get(u,s,u);if((s==="get"||s==="create")&&b(s))return typeof R!="function"||W(R)?R:g(s,R);if(typeof R!="function"||!b(s)||s==="constructor")return R;let q=_.get(R);if(q)return q;let f=R.bind(u);return _.set(R,f),f},set(h,s,R){return Reflect.set(u,s,R,u)}}),l=Object.getOwnPropertyDescriptor(r,"credentials");if(l&&l.configurable!==!0)return null;try{Object.defineProperty(r,"credentials",{value:c,writable:!0,enumerable:!0,configurable:!0})}catch{return null}return r.credentials!==c?null:()=>{r.credentials===c&&(l?Object.defineProperty(r,"credentials",l):delete r.credentials)}},S=(d,g)=>(m=!0,{mode:"standard",surface:d,disconnect:()=>{m=!1,g()}}),B=P("get"),$=B?P("create"):null;if(B&&$)return S("methods",()=>{B(),$()});if(B==null||B(),e.attach==="container"){let d=C();if(d)return n.log("webauthn capture attached at the credentials container"),S("container",d)}return o("credentials methods cannot be patched safely")}function Le(e,t,n){let o=Te(t.mediation);if(e==="create")return{kind:"registration",mediation:o};let r=n;return{kind:"authentication",mediation:o,uiMode:He(t.uiMode),credentialSet:Array.isArray(r.allowCredentials)&&r.allowCredentials.length>0?"allowlisted":"discoverable"}}function Te(e){return e===void 0?"optional":e==="silent"||e==="optional"||e==="conditional"||e==="required"?e:"unknown"}function He(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 se(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function Ie(e){return e instanceof DOMException?e.name:"UnknownError"}var fe=0;function he(){return fe+=1,`network-${fe}`}function We(e,t){let n=e.responseType;if(n===""||n==="text")return t(e.responseText);if(n==="json"){let o=e.response;return o==null?void 0:t(o)}}var _e=500,ye=Symbol("body-read-timeout");function ge(e){return/event-stream|octet-stream/i.test(e)?!1:/json|text|urlencoded/i.test(e)}async function be(e,t){let n=e.body;if(!n)return;let o=n.getReader(),r;try{let u=new Promise(m=>{r=setTimeout(()=>m(ye),_e)}),i=new TextDecoder,y=[];for(;;){let m=await Promise.race([o.read(),u]);if(m===ye){t.log("body omitted: read timed out"),o.cancel().catch(()=>{});return}if(m.done)break;y.push(i.decode(m.value,{stream:!0}))}return y.push(i.decode()),y.join("")}catch{o.cancel().catch(()=>{});return}finally{r!==void 0&&clearTimeout(r)}}function ue(e){var t;(t=e==null?void 0:e.body)==null||t.cancel().catch(()=>{})}function ve(e){var g,b,_;let{onExchange:t,onRequest:n,match:o}=e;if(typeof t!="function"||typeof o!="function")throw new TypeError("captureNetwork requires onExchange and match callbacks");let r=K(e.logger),u=(g=e.transports)!=null?g:["xhr","fetch"],i=(b=e.bodyCapture)==null?void 0:b.request,y=(_=e.bodyCapture)==null?void 0:_.response,m=typeof i=="function",j=typeof y=="function",O=!1,x=X(r,"network",c=>{if(O)return t(c)}),P=X(r,"network request",c=>{if(O)return n==null?void 0:n(c)}),C=(c,l,h)=>{if(typeof h=="function")try{return h(c,l)}catch(s){r.log("body projection failed",s);return}},S=(c,l)=>{try{let h=typeof document!="undefined"?document.baseURI:void 0,s=new URL(String(c),h);return o(s,l)===!0?{url:s.href,path:s.pathname}:void 0}catch{return}},B=()=>{if(typeof XMLHttpRequest=="undefined")return r.log("xhr capture unavailable: XMLHttpRequest missing"),null;let c=XMLHttpRequest.prototype,l=Object.getOwnPropertyDescriptor(c,"open"),h=Object.getOwnPropertyDescriptor(c,"send");if(!l||!("value"in l)||typeof l.value!="function"||!h||!("value"in h)||typeof h.value!="function")return r.log("xhr capture unavailable: XMLHttpRequest methods missing"),null;let s=l.value,R=h.value;if(W(s)||W(R))return r.log("xhr capture unavailable: an equivalent capture is already active"),null;let q=new WeakMap,f=new Set,A=!1,D={open(...k){var v;let a=Reflect.apply(s,this,k);if(!O||!A)return a;try{let L=q.get(this);L&&(L.reported=!0,(v=L.cleanupListeners)==null||v.call(L));let H=String(k[0]).toUpperCase(),N=S(k[1],H);N?q.set(this,{method:H,url:N.url,path:N.path,reported:!1}):q.delete(this)}catch(L){r.log("xhr open observation failed",L)}return a}}.open,E={send(...k){let a=O&&A?q.get(this):void 0;if(!a||a.reported||a.cleanupListeners)return Reflect.apply(R,this,k);let v=()=>{},L=!1;try{a.requestId=he();let N={direction:"request",transport:"xhr",method:a.method,url:a.url,path:a.path};a.requestBody=m&&typeof k[0]=="string"?C(k[0],N,i):void 0;let V=()=>{a.outcome===void 0&&(a.outcome="abort")},G=()=>{a.outcome===void 0&&(a.outcome="timeout")},p=()=>{a.outcome===void 0&&(a.outcome="error")},w=()=>{var z;v();try{if(!O||!A||a.reported||!a.requestId)return;a.reported=!0;let I={direction:"response",transport:"xhr",method:a.method,url:a.url,path:a.path},oe=this.status,ce={requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,status:oe,ok:oe>=200&&oe<300,outcome:(z=a.outcome)!=null?z:"load",durationMs:a.startedAt!==void 0?Date.now()-a.startedAt:void 0,responseUrl:this.responseURL||void 0,requestBody:a.requestBody,responseBody:j?We(this,qe=>C(qe,I,y)):void 0};a.requestEmitted?x(ce):a.pendingExchange=ce}catch(I){r.log("xhr exchange observation failed",I)}finally{q.get(this)===a&&q.delete(this)}},M=()=>{try{this.readyState===XMLHttpRequest.DONE&&this.status!==0&&w()}catch(z){r.log("xhr ready-state observation failed",z)}},U=()=>w();v=()=>{for(let[z,I]of[["readystatechange",M],["abort",V],["timeout",G],["error",p],["loadend",U]])this.removeEventListener(z,I);a.cleanupListeners===v&&(a.cleanupListeners=void 0),f.delete(v)},this.addEventListener("readystatechange",M),this.addEventListener("abort",V),this.addEventListener("timeout",G),this.addEventListener("error",p),this.addEventListener("loadend",U),a.cleanupListeners=v,f.add(v),a.startedAt=Date.now(),L=!0}catch(N){r.log("xhr send observation failed",N),v()}let H;try{H=Reflect.apply(R,this,k)}catch(N){throw v(),N}if(L&&a.requestId!==void 0&&a.startedAt!==void 0){a.requestEmitted=!0,P({requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,startedAt:a.startedAt,requestBody:a.requestBody});let N=a.pendingExchange;a.pendingExchange=void 0,N&&x(N)}return H}}.send;return F(D,s),F(E,R),l.writable!==!0||h.writable!==!0?(r.log("xhr capture unavailable: XMLHttpRequest methods are not writable"),null):(Object.defineProperty(c,"open",{...l,value:D}),Object.defineProperty(c,"send",{...h,value:E}),A=!0,()=>{A=!1;for(let k of[...f])k();J(c,"open",D,l,r),J(c,"send",E,h,r)})},$=()=>{let c=globalThis,l=Object.getOwnPropertyDescriptor(c,"fetch");if(!l||!("value"in l))return r.log("fetch capture unavailable: fetch is not an own data property"),null;let h=l.value;if(typeof h!="function")return r.log("fetch capture unavailable: fetch missing"),null;if(W(h))return r.log("fetch capture unavailable: an equivalent capture is already active"),null;let s=!1,R=async(f,A,D,E)=>{try{if(!O||!s){ue(D);return}let[k,a]=await Promise.all([E!=null?E:Promise.resolve(void 0),D?be(D,r):Promise.resolve(void 0)]);if(!O||!s)return;let v={direction:"request",transport:"fetch",method:f.method,url:f.url,path:f.path},L={...v,direction:"response"},H=f.requestBody;H===void 0&&k!==void 0&&(H=C(k,v,i));let N=a!==void 0?C(a,L,y):void 0;x({requestId:f.requestId,transport:"fetch",method:f.method,url:f.url,path:f.path,status:A.status,ok:A.ok,outcome:"load",durationMs:Date.now()-f.startedAt,responseUrl:A.url||void 0,requestBody:H,responseBody:N})}catch(k){r.log("fetch exchange observation failed",k)}},q={fetch(...f){var H,N,V,G;let A;try{let p=f[0],w=f[1];if(O&&s&&m&&typeof Request!="undefined"&&p instanceof Request&&(w==null?void 0:w.body)===void 0&&p.body){let M=String((H=w==null?void 0:w.method)!=null?H:p.method).toUpperCase(),U=(N=p.headers.get("content-type"))!=null?N:"";S(p.url,M)&&ge(U)&&(A=p.clone())}}catch(p){r.log("fetch observation failed",p)}let D,E=Date.now();try{D=Reflect.apply(h,this,f)}catch(p){throw ue(A),p}let k,a;try{if(O&&s){let p=f[0],w=f[1],M=typeof Request!="undefined"&&p instanceof Request,U=String((V=w==null?void 0:w.method)!=null?V:M?p.method:"GET").toUpperCase(),z=M?p.url:p,I=S(z,U);I&&(k={requestId:he(),method:U,url:I.url,path:I.path,startedAt:E},a=(G=w==null?void 0:w.signal)!=null?G:M?p.signal:void 0,m&&typeof(w==null?void 0:w.body)=="string"&&(k.requestBody=C(w.body,{direction:"request",transport:"fetch",method:U,url:I.url,path:I.path},i)))}}catch(p){r.log("fetch observation failed",p)}if(!k)return ue(A),D;let v=k;P({requestId:v.requestId,transport:"fetch",method:v.method,url:v.url,path:v.path,startedAt:v.startedAt,requestBody:v.requestBody});let L=A?be(A,r):void 0;return D.then(p=>{var M;let w;try{if(O&&s&&j){let U=(M=p.headers.get("content-type"))!=null?M:"";ge(U)&&p.body&&(w=p.clone())}}catch{}R(v,p,w,L)},p=>{try{if(!O||!s)return;let w=(a==null?void 0:a.aborted)===!0||(p==null?void 0:p.name)==="AbortError"||typeof DOMException!="undefined"&&p instanceof DOMException&&p.code===DOMException.ABORT_ERR;x({requestId:v.requestId,transport:"fetch",method:v.method,url:v.url,path:v.path,status:0,ok:!1,outcome:w?"abort":"error",durationMs:Date.now()-v.startedAt})}catch(w){r.log("fetch failure observation failed",w)}}),D}}.fetch;return F(q,h),l.writable!==!0?(r.log("fetch capture unavailable: fetch is not writable"),null):(Object.defineProperty(c,"fetch",{...l,value:q}),s=!0,()=>{s=!1,J(c,"fetch",q,l,r)})},d=[];if(u.includes("xhr")){let c=B();c&&d.push(c)}if(u.includes("fetch")){let c=$();c&&d.push(c)}return d.length===0?T():(O=!0,{mode:"standard",disconnect:()=>{O=!1;for(let c of d.splice(0))c()}})}function Re(e){let t=e.onNavigate;if(typeof t!="function")throw new TypeError("captureNavigation requires an onNavigate callback");let n=K(e.logger),o,r,u,i,y,m;try{if(o=window,r=o==null?void 0:o.history,!o||!r)return n.log("navigation capture unavailable: window/history missing"),T();if(y=we(r,"pushState"),m=we(r,"replaceState"),!y||!m)return n.log("navigation capture unavailable: history method descriptors missing"),T();if(u=y.descriptor.value,i=m.descriptor.value,typeof u!="function"||typeof i!="function")return n.log("navigation capture unavailable: history methods missing"),T();if(typeof o.addEventListener!="function"||typeof o.removeEventListener!="function")return n.log("navigation capture unavailable: window event methods missing"),T()}catch(g){return n.log("navigation capture unavailable: history inspection failed",g),T()}if(W(u)||W(i))return n.log("navigation capture unavailable: an equivalent capture is already active"),T();let j=!1,O=()=>({path:o.location.pathname,search:o.location.search,hash:o.location.hash}),x;try{x=O()}catch(g){return n.log("navigation capture unavailable: location inspection failed",g),T()}let P=X(n,"navigation",g=>{if(j)return t(g)}),C=g=>{if(j)try{let b=O();if(b.path===x.path&&b.search===x.search&&b.hash===x.hash)return;x=b,P({...b,source:g})}catch(b){n.log("navigation observation failed",b)}},S={pushState(...g){let b=Reflect.apply(u,this,g);return C("push"),b}}.pushState,B={replaceState(...g){let b=Reflect.apply(i,this,g);return C("replace"),b}}.replaceState;F(S,u),F(B,i);let $=()=>C("pop"),d=()=>C("hash");try{if(me(y,S),me(m,B),r.pushState!==S||r.replaceState!==B)throw new Error("history method replacement did not take effect");o.addEventListener("popstate",$),o.addEventListener("hashchange",d),j=!0}catch(g){return j=!1,re(o,"popstate",$,n),re(o,"hashchange",d,n),ne(m,B,n),ne(y,S,n),n.log("navigation capture unavailable: history methods are not writable",g),t=()=>{},P=()=>{},n=K(),T()}return{mode:"standard",disconnect:()=>{j=!1,t=()=>{},re(o,"popstate",$,n),re(o,"hashchange",d,n),ne(y,S,n),ne(m,B,n),P=()=>{},n=K()}}}function we(e,t){let n=e;for(;n;){let o=Object.getOwnPropertyDescriptor(n,t);if(o)return!("value"in o)||typeof o.value!="function"?null:{owner:n,key:t,descriptor:o};n=Object.getPrototypeOf(n)}return null}function me(e,t){if(e.descriptor.writable!==!0)throw new TypeError(`${e.key} is not writable`);let n=Object.getOwnPropertyDescriptor(e.owner,e.key);if(!ie(n,e.descriptor))throw new Error(`${e.key} changed during installation`);Object.defineProperty(e.owner,e.key,{...e.descriptor,value:t})}function ne(e,t,n){J(e.owner,e.key,t,e.descriptor,n,`navigation ${e.key}`)}function re(e,t,n,o){try{e.removeEventListener(t,n)}catch(r){o.log(`navigation ${t} listener removal skipped`,r)}}function Oe(e){let t=e.composedPath();return t.length>0?t:e.target?[e.target]:[]}var Ce="0.6.0";0&&(module.exports={VERSION,captureNavigation,captureNetwork,captureWebAuthn,composedPath,sanitizeAssertionResponse,sanitizeCreationOptions,sanitizeCreationResponse,sanitizeRequestOptions});
|
|
1
|
+
"use strict";var ie=Object.defineProperty;var ke=Object.getOwnPropertyDescriptor;var Se=Object.getOwnPropertyNames;var Pe=Object.prototype.hasOwnProperty;var Ie=(e,t)=>{for(var n in t)ie(e,n,{get:t[n],enumerable:!0})},Te=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Se(t))!Pe.call(e,o)&&o!==n&&ie(e,o,{get:()=>t[o],enumerable:!(i=ke(t,o))||i.enumerable});return e};var Be=e=>Te(ie({},"__esModule",{value:!0}),e);var $e={};Ie($e,{VERSION:()=>Ae,captureInputValidation:()=>xe,captureNavigation:()=>Ce,captureNetwork:()=>ve,captureWebAuthn:()=>fe,composedPath:()=>Oe,inputValidationCode:()=>ce,isValidationMessageVisible:()=>Ee,sanitizeAssertionResponse:()=>ee,sanitizeCreationOptions:()=>Y,sanitizeCreationResponse:()=>Q,sanitizeRequestOptions:()=>Z});module.exports=Be($e);var Le={creationOptions:["/user/name","/user/displayName"],creationResponse:["/clientExtensionResults/prf/results"],requestOptions:[],assertionResponse:["/response/signature","/clientExtensionResults/prf/results"]};function Y(e){return te(e,"creationOptions")}function Q(e){return te(e,"creationResponse")}function Z(e){return te(e,"requestOptions")}function ee(e){return te(e,"assertionResponse")}function te(e,t){try{let n=typeof e=="string"?JSON.parse(e):e;if(!Ne(n))return;let i=new Set(Le[t]),o=new Set,d=(s,v,u=0)=>{if(!i.has(v)){if(s===null||typeof s=="string"||typeof s=="boolean")return s;if(typeof s=="number")return Number.isFinite(s)?s:null;if(typeof s=="object"){if(s instanceof ArrayBuffer||ArrayBuffer.isView(s))return De(s);if(u>64||o.has(s))throw new TypeError("Invalid telemetry payload");o.add(s);try{if(Array.isArray(s))return s.map((P,k)=>d(P,`${v}/${k}`,u+1));let B=Object.create(null);for(let P in s){let k=`${v}/${P.replace(/~/g,"~0").replace(/\//g,"~1")}`;if(i.has(k)||P==="toJSON")continue;let I=d(s[P],k,u+1);I!==void 0&&(B[P]=I)}let R=s,q=(P,k)=>{if(B[k]!==void 0||typeof R[P]!="function")return;let I=`${v}/${k}`,T=d(Reflect.apply(R[P],s,[]),I,u+1);T!==void 0&&(B[k]=T)};return v===""&&(t==="creationResponse"||t==="assertionResponse")&&q("getClientExtensionResults","clientExtensionResults"),v==="/response"&&t==="creationResponse"&&(q("getTransports","transports"),q("getAuthenticatorData","authenticatorData"),q("getPublicKey","publicKey"),q("getPublicKeyAlgorithm","publicKeyAlgorithm")),B}finally{o.delete(s)}}}};return JSON.stringify(d(n,""))}catch{return}}function Ne(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e)}function De(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n="";for(let i of t)n+=String.fromCharCode(i);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var Me={log:()=>{}};function K(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{}}}:Me}var le=Symbol.for("corbado.autocapture.installed");function _(e){try{return typeof e=="function"&&Object.prototype.hasOwnProperty.call(e,le)}catch{return!1}}function F(e,t){var i,o;let n=t;try{Object.defineProperty(e,le,{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 M(){return{mode:"unavailable",disconnect:()=>{}}}function ae(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 X(e,t,n,i,o,d=String(t)){try{let s=Object.getOwnPropertyDescriptor(e,t);ae(s,{...i,value:n})&&Object.defineProperty(e,t,i)}catch(s){o.log(`${d} restoration skipped`,s)}}function z(e,t,n){let i=K(e);return o=>{try{let d=n(o);if(d&&(typeof d=="object"||typeof d=="function"))try{Promise.resolve(d).catch(s=>i.log(`${t} listener failed`,s))}catch(s){i.log(`${t} listener failed`,s)}}catch(d){i.log(`${t} listener failed`,d)}}}var pe=e=>({get:e("get"),create:e("create")});function fe(e){let t=e.onEvent;if(typeof t!="function")throw new TypeError("captureWebAuthn requires an onEvent callback");let n=K(e.logger),i=p=>(n.log(`webauthn capture unavailable: ${p}`),{...M(),surface:"none"}),o=typeof navigator=="undefined"?void 0:navigator,d=o==null?void 0:o.credentials;if(!o||!d)return i("navigator.credentials missing");let s=d,v=pe(p=>s[p]);if(typeof v.get!="function"||typeof v.create!="function")return i("credentials methods missing");if(_(v.get)||_(v.create))return i("an equivalent capture is already active");let u=!1,B=0,R=z(n,"webauthn",t),q=(p,y,w)=>{let N={invoke(...l){let g=l[0];if(!u||w!=null&&w()||!se(g)||!se(g.publicKey))return y(this,l);let f=g.publicKey,c=`wa-${++B}`,x=y(this,l),S=se(g.signal)?g.signal:void 0,r=He(p,g,f),h=b=>{u&&R({...r,ceremonyId:c,...b()})},C=()=>(S==null?void 0:S.aborted)===!0?{aborted:!0}:{};return h(()=>({phase:"started",userActivation:We(o),...r.kind==="authentication"?{requestOptionsJson:Z(f)}:{creationOptionsJson:Y(f)}})),Promise.resolve(x).then(b=>(h(()=>({phase:"completed",credentialJson:p==="create"?Q(b):ee(b),...C()})),b),b=>{throw h(()=>({phase:"failed",error:b,errorName:_e(b),...C()})),b})}}.invoke;return F(N,{name:p,length:0})},P=p=>{var N;let y=q(p,(l,g)=>Reflect.apply(v[p],l,g)),w=Object.getOwnPropertyDescriptor(d,p);if(w&&(!("value"in w)||w.writable!==!0))return null;try{s[p]=y}catch{return null}if(((N=Object.getOwnPropertyDescriptor(d,p))==null?void 0:N.value)!==y){try{s[p]=v[p]}catch{}return null}return()=>{s[p]===y&&(w?s[p]=w.value:delete s[p])}},k=()=>{let p=pe(()=>new WeakMap),y=(f,c)=>{let x=p[f].get(c);if(x)return x;let S=q(f,(r,h)=>Reflect.apply(c,d,h),()=>{try{let r=s[f];return r!==c&&r!==S}catch(r){return n.log("suppress check failed; ceremony unreported",r),!0}});return p[f].set(c,S),S},w=f=>{let c=Object.getOwnPropertyDescriptor(d,f);return c?c.configurable===!0||!("value"in c)||c.writable===!0:!0},N=new WeakMap,l=new Proxy(d,{get(f,c){let x=Reflect.get(d,c,d);if((c==="get"||c==="create")&&w(c))return typeof x!="function"||_(x)?x:y(c,x);if(typeof x!="function"||!w(c)||c==="constructor")return x;let S=N.get(x);if(S)return S;let r=x.bind(d);return N.set(x,r),r},set(f,c,x){return Reflect.set(d,c,x,d)}}),g=Object.getOwnPropertyDescriptor(o,"credentials");if(g&&g.configurable!==!0)return null;try{Object.defineProperty(o,"credentials",{value:l,writable:!0,enumerable:!0,configurable:!0})}catch{return null}return o.credentials!==l?null:()=>{o.credentials===l&&(g?Object.defineProperty(o,"credentials",g):delete o.credentials)}},I=(p,y)=>(u=!0,{mode:"standard",surface:p,disconnect:()=>{u=!1,y()}}),T=P("get"),j=T?P("create"):null;if(T&&j)return I("methods",()=>{T(),j()});if(T==null||T(),e.attach==="container"){let p=k();if(p)return n.log("webauthn capture attached at the credentials container"),I("container",p)}return i("credentials methods cannot be patched safely")}function He(e,t,n){let i=je(t.mediation);if(e==="create")return{kind:"registration",mediation:i};let o=n;return{kind:"authentication",mediation:i,uiMode:Ve(t.uiMode),credentialSet:Array.isArray(o.allowCredentials)&&o.allowCredentials.length>0?"allowlisted":"discoverable"}}function je(e){return e===void 0?"optional":e==="silent"||e==="optional"||e==="conditional"||e==="required"?e:"unknown"}function Ve(e){return e===void 0?"default":e==="immediate"?"immediate":"unknown"}function We(e){let t=e.userActivation;return typeof(t==null?void 0:t.isActive)=="boolean"?t.isActive:void 0}function se(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function _e(e){return e instanceof DOMException?e.name:"UnknownError"}var he=0;function ye(){return he+=1,`network-${he}`}function Ue(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 Ke=500,ge=Symbol("body-read-timeout");function be(e){return/event-stream|octet-stream/i.test(e)?!1:/json|text|urlencoded/i.test(e)}async function me(e,t){let n=e.body;if(!n)return;let i=n.getReader(),o;try{let d=new Promise(u=>{o=setTimeout(()=>u(ge),Ke)}),s=new TextDecoder,v=[];for(;;){let u=await Promise.race([i.read(),d]);if(u===ge){t.log("body omitted: read timed out"),i.cancel().catch(()=>{});return}if(u.done)break;v.push(s.decode(u.value,{stream:!0}))}return v.push(s.decode()),v.join("")}catch{i.cancel().catch(()=>{});return}finally{o!==void 0&&clearTimeout(o)}}function ue(e){var t;(t=e==null?void 0:e.body)==null||t.cancel().catch(()=>{})}function ve(e){var y,w,N;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=K(e.logger),d=(y=e.transports)!=null?y:["xhr","fetch"],s=(w=e.bodyCapture)==null?void 0:w.request,v=(N=e.bodyCapture)==null?void 0:N.response,u=typeof s=="function",B=typeof v=="function",R=!1,q=z(o,"network",l=>{if(R)return t(l)}),P=z(o,"network request",l=>{if(R)return n==null?void 0:n(l)}),k=(l,g,f)=>{if(typeof f=="function")try{return f(l,g)}catch(c){o.log("body projection failed",c);return}},I=(l,g)=>{try{let f=typeof document!="undefined"?document.baseURI:void 0,c=new URL(String(l),f);return i(c,g)===!0?{url:c.href,path:c.pathname}:void 0}catch{return}},T=()=>{if(typeof XMLHttpRequest=="undefined")return o.log("xhr capture unavailable: XMLHttpRequest missing"),null;let l=XMLHttpRequest.prototype,g=Object.getOwnPropertyDescriptor(l,"open"),f=Object.getOwnPropertyDescriptor(l,"send");if(!g||!("value"in g)||typeof g.value!="function"||!f||!("value"in f)||typeof f.value!="function")return o.log("xhr capture unavailable: XMLHttpRequest methods missing"),null;let c=g.value,x=f.value;if(_(c)||_(x))return o.log("xhr capture unavailable: an equivalent capture is already active"),null;let S=new WeakMap,r=new Set,h=!1,C={open(...O){var A;let a=Reflect.apply(c,this,O);if(!R||!h)return a;try{let D=S.get(this);D&&(D.reported=!0,(A=D.cleanupListeners)==null||A.call(D));let H=String(O[0]).toUpperCase(),L=I(O[1],H);L?S.set(this,{method:H,url:L.url,path:L.path,reported:!1}):S.delete(this)}catch(D){o.log("xhr open observation failed",D)}return a}}.open,b={send(...O){let a=R&&h?S.get(this):void 0;if(!a||a.reported||a.cleanupListeners)return Reflect.apply(x,this,O);let A=()=>{},D=!1;try{a.requestId=ye();let L={direction:"request",transport:"xhr",method:a.method,url:a.url,path:a.path};a.requestBody=u&&typeof O[0]=="string"?k(O[0],L,s):void 0;let J=()=>{a.outcome===void 0&&(a.outcome="abort")},G=()=>{a.outcome===void 0&&(a.outcome="timeout")},m=()=>{a.outcome===void 0&&(a.outcome="error")},E=()=>{var $;A();try{if(!R||!h||a.reported||!a.requestId)return;a.reported=!0;let W={direction:"response",transport:"xhr",method:a.method,url:a.url,path:a.path},oe=this.status,de={requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,status:oe,ok:oe>=200&&oe<300,outcome:($=a.outcome)!=null?$:"load",durationMs:a.startedAt!==void 0?Date.now()-a.startedAt:void 0,responseUrl:this.responseURL||void 0,requestBody:a.requestBody,responseBody:B?Ue(this,qe=>k(qe,W,v)):void 0};a.requestEmitted?q(de):a.pendingExchange=de}catch(W){o.log("xhr exchange observation failed",W)}finally{S.get(this)===a&&S.delete(this)}},V=()=>{try{this.readyState===XMLHttpRequest.DONE&&this.status!==0&&E()}catch($){o.log("xhr ready-state observation failed",$)}},U=()=>E();A=()=>{for(let[$,W]of[["readystatechange",V],["abort",J],["timeout",G],["error",m],["loadend",U]])this.removeEventListener($,W);a.cleanupListeners===A&&(a.cleanupListeners=void 0),r.delete(A)},this.addEventListener("readystatechange",V),this.addEventListener("abort",J),this.addEventListener("timeout",G),this.addEventListener("error",m),this.addEventListener("loadend",U),a.cleanupListeners=A,r.add(A),a.startedAt=Date.now(),D=!0}catch(L){o.log("xhr send observation failed",L),A()}let H;try{H=Reflect.apply(x,this,O)}catch(L){throw A(),L}if(D&&a.requestId!==void 0&&a.startedAt!==void 0){a.requestEmitted=!0,P({requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,startedAt:a.startedAt,requestBody:a.requestBody});let L=a.pendingExchange;a.pendingExchange=void 0,L&&q(L)}return H}}.send;return F(C,c),F(b,x),g.writable!==!0||f.writable!==!0?(o.log("xhr capture unavailable: XMLHttpRequest methods are not writable"),null):(Object.defineProperty(l,"open",{...g,value:C}),Object.defineProperty(l,"send",{...f,value:b}),h=!0,()=>{h=!1;for(let O of[...r])O();X(l,"open",C,g,o),X(l,"send",b,f,o)})},j=()=>{let l=globalThis,g=Object.getOwnPropertyDescriptor(l,"fetch");if(!g||!("value"in g))return o.log("fetch capture unavailable: fetch is not an own data property"),null;let f=g.value;if(typeof f!="function")return o.log("fetch capture unavailable: fetch missing"),null;if(_(f))return o.log("fetch capture unavailable: an equivalent capture is already active"),null;let c=!1,x=async(r,h,C,b)=>{try{if(!R||!c){ue(C);return}let[O,a]=await Promise.all([b!=null?b:Promise.resolve(void 0),C?me(C,o):Promise.resolve(void 0)]);if(!R||!c)return;let A={direction:"request",transport:"fetch",method:r.method,url:r.url,path:r.path},D={...A,direction:"response"},H=r.requestBody;H===void 0&&O!==void 0&&(H=k(O,A,s));let L=a!==void 0?k(a,D,v):void 0;q({requestId:r.requestId,transport:"fetch",method:r.method,url:r.url,path:r.path,status:h.status,ok:h.ok,outcome:"load",durationMs:Date.now()-r.startedAt,responseUrl:h.url||void 0,requestBody:H,responseBody:L})}catch(O){o.log("fetch exchange observation failed",O)}},S={fetch(...r){var H,L,J,G;let h;try{let m=r[0],E=r[1];if(R&&c&&u&&typeof Request!="undefined"&&m instanceof Request&&(E==null?void 0:E.body)===void 0&&m.body){let V=String((H=E==null?void 0:E.method)!=null?H:m.method).toUpperCase(),U=(L=m.headers.get("content-type"))!=null?L:"";I(m.url,V)&&be(U)&&(h=m.clone())}}catch(m){o.log("fetch observation failed",m)}let C,b=Date.now();try{C=Reflect.apply(f,this,r)}catch(m){throw ue(h),m}let O,a;try{if(R&&c){let m=r[0],E=r[1],V=typeof Request!="undefined"&&m instanceof Request,U=String((J=E==null?void 0:E.method)!=null?J:V?m.method:"GET").toUpperCase(),$=V?m.url:m,W=I($,U);W&&(O={requestId:ye(),method:U,url:W.url,path:W.path,startedAt:b},a=(G=E==null?void 0:E.signal)!=null?G:V?m.signal:void 0,u&&typeof(E==null?void 0:E.body)=="string"&&(O.requestBody=k(E.body,{direction:"request",transport:"fetch",method:U,url:W.url,path:W.path},s)))}}catch(m){o.log("fetch observation failed",m)}if(!O)return ue(h),C;let A=O;P({requestId:A.requestId,transport:"fetch",method:A.method,url:A.url,path:A.path,startedAt:A.startedAt,requestBody:A.requestBody});let D=h?me(h,o):void 0;return C.then(m=>{var V;let E;try{if(R&&c&&B){let U=(V=m.headers.get("content-type"))!=null?V:"";be(U)&&m.body&&(E=m.clone())}}catch{}x(A,m,E,D)},m=>{try{if(!R||!c)return;let E=(a==null?void 0:a.aborted)===!0||(m==null?void 0:m.name)==="AbortError"||typeof DOMException!="undefined"&&m instanceof DOMException&&m.code===DOMException.ABORT_ERR;q({requestId:A.requestId,transport:"fetch",method:A.method,url:A.url,path:A.path,status:0,ok:!1,outcome:E?"abort":"error",durationMs:Date.now()-A.startedAt})}catch(E){o.log("fetch failure observation failed",E)}}),C}}.fetch;return F(S,f),g.writable!==!0?(o.log("fetch capture unavailable: fetch is not writable"),null):(Object.defineProperty(l,"fetch",{...g,value:S}),c=!0,()=>{c=!1,X(l,"fetch",S,g,o)})},p=[];if(d.includes("xhr")){let l=T();l&&p.push(l)}if(d.includes("fetch")){let l=j();l&&p.push(l)}return p.length===0?M():(R=!0,{mode:"standard",disconnect:()=>{R=!1;for(let l of p.splice(0))l()}})}function Ce(e){let t=e.onNavigate;if(typeof t!="function")throw new TypeError("captureNavigation requires an onNavigate callback");let n=K(e.logger),i,o,d,s,v,u;try{if(i=window,o=i==null?void 0:i.history,!i||!o)return n.log("navigation capture unavailable: window/history missing"),M();if(v=we(o,"pushState"),u=we(o,"replaceState"),!v||!u)return n.log("navigation capture unavailable: history method descriptors missing"),M();if(d=v.descriptor.value,s=u.descriptor.value,typeof d!="function"||typeof s!="function")return n.log("navigation capture unavailable: history methods missing"),M();if(typeof i.addEventListener!="function"||typeof i.removeEventListener!="function")return n.log("navigation capture unavailable: window event methods missing"),M()}catch(y){return n.log("navigation capture unavailable: history inspection failed",y),M()}if(_(d)||_(s))return n.log("navigation capture unavailable: an equivalent capture is already active"),M();let B=!1,R=()=>({path:i.location.pathname,search:i.location.search,hash:i.location.hash}),q;try{q=R()}catch(y){return n.log("navigation capture unavailable: location inspection failed",y),M()}let P=z(n,"navigation",y=>{if(B)return t(y)}),k=y=>{if(B)try{let w=R();if(w.path===q.path&&w.search===q.search&&w.hash===q.hash)return;q=w,P({...w,source:y})}catch(w){n.log("navigation observation failed",w)}},I={pushState(...y){let w=Reflect.apply(d,this,y);return k("push"),w}}.pushState,T={replaceState(...y){let w=Reflect.apply(s,this,y);return k("replace"),w}}.replaceState;F(I,d),F(T,s);let j=()=>k("pop"),p=()=>k("hash");try{if(Re(v,I),Re(u,T),o.pushState!==I||o.replaceState!==T)throw new Error("history method replacement did not take effect");i.addEventListener("popstate",j),i.addEventListener("hashchange",p),B=!0}catch(y){return B=!1,re(i,"popstate",j,n),re(i,"hashchange",p,n),ne(u,T,n),ne(v,I,n),n.log("navigation capture unavailable: history methods are not writable",y),t=()=>{},P=()=>{},n=K(),M()}return{mode:"standard",disconnect:()=>{B=!1,t=()=>{},re(i,"popstate",j,n),re(i,"hashchange",p,n),ne(v,I,n),ne(u,T,n),P=()=>{},n=K()}}}function we(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 Re(e,t){if(e.descriptor.writable!==!0)throw new TypeError(`${e.key} is not writable`);let n=Object.getOwnPropertyDescriptor(e.owner,e.key);if(!ae(n,e.descriptor))throw new Error(`${e.key} changed during installation`);Object.defineProperty(e.owner,e.key,{...e.descriptor,value:t})}function ne(e,t,n){X(e.owner,e.key,t,e.descriptor,n,`navigation ${e.key}`)}function re(e,t,n,i){try{e.removeEventListener(t,n)}catch(o){i.log(`navigation ${t} listener removal skipped`,o)}}function Oe(e){let t=e.composedPath();return t.length>0?t:e.target?[e.target]:[]}var Ae="0.7.0";var Fe=["valueMissing","typeMismatch","patternMismatch","tooShort","tooLong","rangeUnderflow","rangeOverflow","stepMismatch","badInput","customError"];function ce(e){return Fe.find(t=>e.validity[t])}function Ee(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 xe(e){var x,S;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=(x=e.maxObservationMs)!=null?x: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(){}},d=(S=t==null?void 0:t.ownerDocument)==null?void 0:S.defaultView;if(!d||!n.every(r=>r.form===t))return o;let s=!0,v=0,u,B=!1,R,q,P,k,I=[],T=()=>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"}},p=r=>r.status==="invalid"?JSON.stringify([r.code,r.fieldIndex]):void 0,y=()=>{u=void 0,clearTimeout(q),clearTimeout(P),q=P=void 0},w=()=>{q=void 0;let r=u;if(!s||!(r!=null&&r.confirmed))return;if(!T()){y();return}let h=r.nativeInvalid?(()=>{for(let[b,O]of n.entries()){let a=ce(O);if(a)return{status:"invalid",source:"constraint",code:a,fieldIndex:b}}return{status:"clear"}})():j();if(h.status==="clear"){r.serverBaseline=void 0;return}if(h.status!=="invalid"||h.source==="application"&&r.serverBaseline===p(h))return;let C={attemptId:r.id,startedAt:r.startedAt,timestamp:Date.now(),code:h.code,...h.fieldIndex===void 0?{}:{fieldIndex:h.fieldIndex}};y(),B=!1;try{Promise.resolve(e.onError(C)).catch(()=>{})}catch{}},N=()=>{!s||!u||q!==void 0||(q=setTimeout(w,0))},l=r=>{if(!s||!T())return;y();let h=B?p(j()):void 0;return u={id:++v,startedAt:Date.now(),confirmed:r,nativeInvalid:!1,serverBaseline:h},P=setTimeout(y,i),N(),u.id},g=()=>{R===void 0&&(R=l(!1),k=setTimeout(()=>{u&&u.id===R&&!u.confirmed&&y(),R=void 0},0))},f=(r,h,C)=>{r.addEventListener(h,C,!0),I.push(()=>r.removeEventListener(h,C,!0))},c={mode:"standard",beginAttempt:()=>l(!0),refresh:N,requestStarted(r={}){s&&(r.attemptId!==void 0&&r.attemptId!==(u==null?void 0:u.id)||u&&r.timestamp!==void 0&&r.timestamp<u.startedAt||(y(),B=!0))},disconnect(){if(s){s=!1,y(),clearTimeout(k);for(let r of I.splice(0))r()}}};try{let r=C=>{var a;let b=C.target,O=(a=b==null?void 0:b.closest)==null?void 0:a.call(b,"button,input");(O==null?void 0:O.form)===t&&!O.disabled&&["submit","image"].includes(O.type)&&g()};f(t.ownerDocument,"click",r),f(t,"click",r),f(t,"keydown",C=>{let b=C;b.key==="Enter"&&!b.isComposing&&!b.defaultPrevented&&n.includes(b.target)&&g()}),f(t,"submit",()=>{(u==null?void 0:u.id)===R&&u?(u.confirmed=!0,N()):l(!0),R=void 0}),f(t,"invalid",C=>{!u||!n.includes(C.target)||(u.confirmed=!0,u.nativeInvalid=!0,N())}),f(t,"input",C=>{n.includes(C.target)&&y()});let h=new d.MutationObserver(N);h.observe(t,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),I.push(()=>h.disconnect())}catch{return c.disconnect(),o}return c}0&&(module.exports={VERSION,captureInputValidation,captureNavigation,captureNetwork,captureWebAuthn,composedPath,inputValidationCode,isValidationMessageVisible,sanitizeAssertionResponse,sanitizeCreationOptions,sanitizeCreationResponse,sanitizeRequestOptions});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var we={creationOptions:["/user/name","/user/displayName"],creationResponse:["/clientExtensionResults/prf/results"],requestOptions:[],assertionResponse:["/response/signature","/clientExtensionResults/prf/results"]};function te(e){return Y(e,"creationOptions")}function ne(e){return Y(e,"creationResponse")}function re(e){return Y(e,"requestOptions")}function oe(e){return Y(e,"assertionResponse")}function Y(e,n){try{let t=typeof e=="string"?JSON.parse(e):e;if(!me(t))return;let o=new Set(we[n]),r=new Set,u=(i,y,m=0)=>{if(!o.has(y)){if(i===null||typeof i=="string"||typeof i=="boolean")return i;if(typeof i=="number")return Number.isFinite(i)?i:null;if(typeof i=="object"){if(i instanceof ArrayBuffer||ArrayBuffer.isView(i))return Re(i);if(m>64||r.has(i))throw new TypeError("Invalid telemetry payload");r.add(i);try{if(Array.isArray(i))return i.map((P,C)=>u(P,`${y}/${C}`,m+1));let j=Object.create(null);for(let P in i){let C=`${y}/${P.replace(/~/g,"~0").replace(/\//g,"~1")}`;if(o.has(C)||P==="toJSON")continue;let S=u(i[P],C,m+1);S!==void 0&&(j[P]=S)}let O=i,x=(P,C)=>{if(j[C]!==void 0||typeof O[P]!="function")return;let S=`${y}/${C}`,B=u(Reflect.apply(O[P],i,[]),S,m+1);B!==void 0&&(j[C]=B)};return y===""&&(n==="creationResponse"||n==="assertionResponse")&&x("getClientExtensionResults","clientExtensionResults"),y==="/response"&&n==="creationResponse"&&(x("getTransports","transports"),x("getAuthenticatorData","authenticatorData"),x("getPublicKey","publicKey"),x("getPublicKeyAlgorithm","publicKeyAlgorithm")),j}finally{r.delete(i)}}}};return JSON.stringify(u(t,""))}catch{return}}function me(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e)}function Re(e){let n=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),t="";for(let o of n)t+=String.fromCharCode(o);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var Oe={log:()=>{}};function K(e){return e?{log:(...n)=>{try{let t=e.log(...n);if(t&&(typeof t=="object"||typeof t=="function"))try{Promise.resolve(t).catch(()=>{})}catch{}}catch{}}}:Oe}var ce=Symbol.for("corbado.autocapture.installed");function W(e){try{return typeof e=="function"&&Object.prototype.hasOwnProperty.call(e,ce)}catch{return!1}}function F(e,n){var o,r;let t=n;try{Object.defineProperty(e,ce,{value:n,configurable:!0})}catch{}try{Object.defineProperty(e,"name",{value:(o=t.name)!=null?o:"",configurable:!0})}catch{}try{Object.defineProperty(e,"length",{value:(r=t.length)!=null?r:0,configurable:!0})}catch{}return e}function T(){return{mode:"unavailable",disconnect:()=>{}}}function ae(e,n){return!!e&&"value"in e&&"value"in n&&e.value===n.value&&e.writable===n.writable&&e.enumerable===n.enumerable&&e.configurable===n.configurable}function J(e,n,t,o,r,u=String(n)){try{let i=Object.getOwnPropertyDescriptor(e,n);ae(i,{...o,value:t})&&Object.defineProperty(e,n,o)}catch(i){r.log(`${u} restoration skipped`,i)}}function X(e,n,t){let o=K(e);return r=>{try{let u=t(r);if(u&&(typeof u=="object"||typeof u=="function"))try{Promise.resolve(u).catch(i=>o.log(`${n} listener failed`,i))}catch(i){o.log(`${n} listener failed`,i)}}catch(u){o.log(`${n} listener failed`,u)}}}var de=e=>({get:e("get"),create:e("create")});function Ce(e){let n=e.onEvent;if(typeof n!="function")throw new TypeError("captureWebAuthn requires an onEvent callback");let t=K(e.logger),o=d=>(t.log(`webauthn capture unavailable: ${d}`),{...T(),surface:"none"}),r=typeof navigator=="undefined"?void 0:navigator,u=r==null?void 0:r.credentials;if(!r||!u)return o("navigator.credentials missing");let i=u,y=de(d=>i[d]);if(typeof y.get!="function"||typeof y.create!="function")return o("credentials methods missing");if(W(y.get)||W(y.create))return o("an equivalent capture is already active");let m=!1,j=0,O=X(t,"webauthn",n),x=(d,g,b)=>{let _={invoke(...c){let l=c[0];if(!m||b!=null&&b()||!ie(l)||!ie(l.publicKey))return g(this,c);let h=l.publicKey,s=`wa-${++j}`,R=g(this,c),q=ie(l.signal)?l.signal:void 0,f=qe(d,l,h),A=E=>{m&&O({...f,ceremonyId:s,...E()})},D=()=>(q==null?void 0:q.aborted)===!0?{aborted:!0}:{};return A(()=>({phase:"started",userActivation:xe(r),...f.kind==="authentication"?{requestOptionsJson:re(h)}:{creationOptionsJson:te(h)}})),Promise.resolve(R).then(E=>(A(()=>({phase:"completed",credentialJson:d==="create"?ne(E):oe(E),...D()})),E),E=>{throw A(()=>({phase:"failed",error:E,errorName:Pe(E),...D()})),E})}}.invoke;return F(_,{name:d,length:0})},P=d=>{var _;let g=x(d,(c,l)=>Reflect.apply(y[d],c,l)),b=Object.getOwnPropertyDescriptor(u,d);if(b&&(!("value"in b)||b.writable!==!0))return null;try{i[d]=g}catch{return null}if(((_=Object.getOwnPropertyDescriptor(u,d))==null?void 0:_.value)!==g){try{i[d]=y[d]}catch{}return null}return()=>{i[d]===g&&(b?i[d]=b.value:delete i[d])}},C=()=>{let d=de(()=>new WeakMap),g=(h,s)=>{let R=d[h].get(s);if(R)return R;let q=x(h,(f,A)=>Reflect.apply(s,u,A),()=>{try{let f=i[h];return f!==s&&f!==q}catch(f){return t.log("suppress check failed; ceremony unreported",f),!0}});return d[h].set(s,q),q},b=h=>{let s=Object.getOwnPropertyDescriptor(u,h);return s?s.configurable===!0||!("value"in s)||s.writable===!0:!0},_=new WeakMap,c=new Proxy(u,{get(h,s){let R=Reflect.get(u,s,u);if((s==="get"||s==="create")&&b(s))return typeof R!="function"||W(R)?R:g(s,R);if(typeof R!="function"||!b(s)||s==="constructor")return R;let q=_.get(R);if(q)return q;let f=R.bind(u);return _.set(R,f),f},set(h,s,R){return Reflect.set(u,s,R,u)}}),l=Object.getOwnPropertyDescriptor(r,"credentials");if(l&&l.configurable!==!0)return null;try{Object.defineProperty(r,"credentials",{value:c,writable:!0,enumerable:!0,configurable:!0})}catch{return null}return r.credentials!==c?null:()=>{r.credentials===c&&(l?Object.defineProperty(r,"credentials",l):delete r.credentials)}},S=(d,g)=>(m=!0,{mode:"standard",surface:d,disconnect:()=>{m=!1,g()}}),B=P("get"),$=B?P("create"):null;if(B&&$)return S("methods",()=>{B(),$()});if(B==null||B(),e.attach==="container"){let d=C();if(d)return t.log("webauthn capture attached at the credentials container"),S("container",d)}return o("credentials methods cannot be patched safely")}function qe(e,n,t){let o=Ae(n.mediation);if(e==="create")return{kind:"registration",mediation:o};let r=t;return{kind:"authentication",mediation:o,uiMode:ke(n.uiMode),credentialSet:Array.isArray(r.allowCredentials)&&r.allowCredentials.length>0?"allowlisted":"discoverable"}}function Ae(e){return e===void 0?"optional":e==="silent"||e==="optional"||e==="conditional"||e==="required"?e:"unknown"}function ke(e){return e===void 0?"default":e==="immediate"?"immediate":"unknown"}function xe(e){let n=e.userActivation;return typeof(n==null?void 0:n.isActive)=="boolean"?n.isActive:void 0}function ie(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function Pe(e){return e instanceof DOMException?e.name:"UnknownError"}var le=0;function pe(){return le+=1,`network-${le}`}function Ee(e,n){let t=e.responseType;if(t===""||t==="text")return n(e.responseText);if(t==="json"){let o=e.response;return o==null?void 0:n(o)}}var Se=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,n){let t=e.body;if(!t)return;let o=t.getReader(),r;try{let u=new Promise(m=>{r=setTimeout(()=>m(fe),Se)}),i=new TextDecoder,y=[];for(;;){let m=await Promise.race([o.read(),u]);if(m===fe){n.log("body omitted: read timed out"),o.cancel().catch(()=>{});return}if(m.done)break;y.push(i.decode(m.value,{stream:!0}))}return y.push(i.decode()),y.join("")}catch{o.cancel().catch(()=>{});return}finally{r!==void 0&&clearTimeout(r)}}function se(e){var n;(n=e==null?void 0:e.body)==null||n.cancel().catch(()=>{})}function Be(e){var g,b,_;let{onExchange:n,onRequest:t,match:o}=e;if(typeof n!="function"||typeof o!="function")throw new TypeError("captureNetwork requires onExchange and match callbacks");let r=K(e.logger),u=(g=e.transports)!=null?g:["xhr","fetch"],i=(b=e.bodyCapture)==null?void 0:b.request,y=(_=e.bodyCapture)==null?void 0:_.response,m=typeof i=="function",j=typeof y=="function",O=!1,x=X(r,"network",c=>{if(O)return n(c)}),P=X(r,"network request",c=>{if(O)return t==null?void 0:t(c)}),C=(c,l,h)=>{if(typeof h=="function")try{return h(c,l)}catch(s){r.log("body projection failed",s);return}},S=(c,l)=>{try{let h=typeof document!="undefined"?document.baseURI:void 0,s=new URL(String(c),h);return o(s,l)===!0?{url:s.href,path:s.pathname}:void 0}catch{return}},B=()=>{if(typeof XMLHttpRequest=="undefined")return r.log("xhr capture unavailable: XMLHttpRequest missing"),null;let c=XMLHttpRequest.prototype,l=Object.getOwnPropertyDescriptor(c,"open"),h=Object.getOwnPropertyDescriptor(c,"send");if(!l||!("value"in l)||typeof l.value!="function"||!h||!("value"in h)||typeof h.value!="function")return r.log("xhr capture unavailable: XMLHttpRequest methods missing"),null;let s=l.value,R=h.value;if(W(s)||W(R))return r.log("xhr capture unavailable: an equivalent capture is already active"),null;let q=new WeakMap,f=new Set,A=!1,D={open(...k){var v;let a=Reflect.apply(s,this,k);if(!O||!A)return a;try{let L=q.get(this);L&&(L.reported=!0,(v=L.cleanupListeners)==null||v.call(L));let H=String(k[0]).toUpperCase(),N=S(k[1],H);N?q.set(this,{method:H,url:N.url,path:N.path,reported:!1}):q.delete(this)}catch(L){r.log("xhr open observation failed",L)}return a}}.open,E={send(...k){let a=O&&A?q.get(this):void 0;if(!a||a.reported||a.cleanupListeners)return Reflect.apply(R,this,k);let v=()=>{},L=!1;try{a.requestId=pe();let N={direction:"request",transport:"xhr",method:a.method,url:a.url,path:a.path};a.requestBody=m&&typeof k[0]=="string"?C(k[0],N,i):void 0;let V=()=>{a.outcome===void 0&&(a.outcome="abort")},G=()=>{a.outcome===void 0&&(a.outcome="timeout")},p=()=>{a.outcome===void 0&&(a.outcome="error")},w=()=>{var z;v();try{if(!O||!A||a.reported||!a.requestId)return;a.reported=!0;let I={direction:"response",transport:"xhr",method:a.method,url:a.url,path:a.path},ee=this.status,ue={requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,status:ee,ok:ee>=200&&ee<300,outcome:(z=a.outcome)!=null?z:"load",durationMs:a.startedAt!==void 0?Date.now()-a.startedAt:void 0,responseUrl:this.responseURL||void 0,requestBody:a.requestBody,responseBody:j?Ee(this,ve=>C(ve,I,y)):void 0};a.requestEmitted?x(ue):a.pendingExchange=ue}catch(I){r.log("xhr exchange observation failed",I)}finally{q.get(this)===a&&q.delete(this)}},M=()=>{try{this.readyState===XMLHttpRequest.DONE&&this.status!==0&&w()}catch(z){r.log("xhr ready-state observation failed",z)}},U=()=>w();v=()=>{for(let[z,I]of[["readystatechange",M],["abort",V],["timeout",G],["error",p],["loadend",U]])this.removeEventListener(z,I);a.cleanupListeners===v&&(a.cleanupListeners=void 0),f.delete(v)},this.addEventListener("readystatechange",M),this.addEventListener("abort",V),this.addEventListener("timeout",G),this.addEventListener("error",p),this.addEventListener("loadend",U),a.cleanupListeners=v,f.add(v),a.startedAt=Date.now(),L=!0}catch(N){r.log("xhr send observation failed",N),v()}let H;try{H=Reflect.apply(R,this,k)}catch(N){throw v(),N}if(L&&a.requestId!==void 0&&a.startedAt!==void 0){a.requestEmitted=!0,P({requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,startedAt:a.startedAt,requestBody:a.requestBody});let N=a.pendingExchange;a.pendingExchange=void 0,N&&x(N)}return H}}.send;return F(D,s),F(E,R),l.writable!==!0||h.writable!==!0?(r.log("xhr capture unavailable: XMLHttpRequest methods are not writable"),null):(Object.defineProperty(c,"open",{...l,value:D}),Object.defineProperty(c,"send",{...h,value:E}),A=!0,()=>{A=!1;for(let k of[...f])k();J(c,"open",D,l,r),J(c,"send",E,h,r)})},$=()=>{let c=globalThis,l=Object.getOwnPropertyDescriptor(c,"fetch");if(!l||!("value"in l))return r.log("fetch capture unavailable: fetch is not an own data property"),null;let h=l.value;if(typeof h!="function")return r.log("fetch capture unavailable: fetch missing"),null;if(W(h))return r.log("fetch capture unavailable: an equivalent capture is already active"),null;let s=!1,R=async(f,A,D,E)=>{try{if(!O||!s){se(D);return}let[k,a]=await Promise.all([E!=null?E:Promise.resolve(void 0),D?ye(D,r):Promise.resolve(void 0)]);if(!O||!s)return;let v={direction:"request",transport:"fetch",method:f.method,url:f.url,path:f.path},L={...v,direction:"response"},H=f.requestBody;H===void 0&&k!==void 0&&(H=C(k,v,i));let N=a!==void 0?C(a,L,y):void 0;x({requestId:f.requestId,transport:"fetch",method:f.method,url:f.url,path:f.path,status:A.status,ok:A.ok,outcome:"load",durationMs:Date.now()-f.startedAt,responseUrl:A.url||void 0,requestBody:H,responseBody:N})}catch(k){r.log("fetch exchange observation failed",k)}},q={fetch(...f){var H,N,V,G;let A;try{let p=f[0],w=f[1];if(O&&s&&m&&typeof Request!="undefined"&&p instanceof Request&&(w==null?void 0:w.body)===void 0&&p.body){let M=String((H=w==null?void 0:w.method)!=null?H:p.method).toUpperCase(),U=(N=p.headers.get("content-type"))!=null?N:"";S(p.url,M)&&he(U)&&(A=p.clone())}}catch(p){r.log("fetch observation failed",p)}let D,E=Date.now();try{D=Reflect.apply(h,this,f)}catch(p){throw se(A),p}let k,a;try{if(O&&s){let p=f[0],w=f[1],M=typeof Request!="undefined"&&p instanceof Request,U=String((V=w==null?void 0:w.method)!=null?V:M?p.method:"GET").toUpperCase(),z=M?p.url:p,I=S(z,U);I&&(k={requestId:pe(),method:U,url:I.url,path:I.path,startedAt:E},a=(G=w==null?void 0:w.signal)!=null?G:M?p.signal:void 0,m&&typeof(w==null?void 0:w.body)=="string"&&(k.requestBody=C(w.body,{direction:"request",transport:"fetch",method:U,url:I.url,path:I.path},i)))}}catch(p){r.log("fetch observation failed",p)}if(!k)return se(A),D;let v=k;P({requestId:v.requestId,transport:"fetch",method:v.method,url:v.url,path:v.path,startedAt:v.startedAt,requestBody:v.requestBody});let L=A?ye(A,r):void 0;return D.then(p=>{var M;let w;try{if(O&&s&&j){let U=(M=p.headers.get("content-type"))!=null?M:"";he(U)&&p.body&&(w=p.clone())}}catch{}R(v,p,w,L)},p=>{try{if(!O||!s)return;let w=(a==null?void 0:a.aborted)===!0||(p==null?void 0:p.name)==="AbortError"||typeof DOMException!="undefined"&&p instanceof DOMException&&p.code===DOMException.ABORT_ERR;x({requestId:v.requestId,transport:"fetch",method:v.method,url:v.url,path:v.path,status:0,ok:!1,outcome:w?"abort":"error",durationMs:Date.now()-v.startedAt})}catch(w){r.log("fetch failure observation failed",w)}}),D}}.fetch;return F(q,h),l.writable!==!0?(r.log("fetch capture unavailable: fetch is not writable"),null):(Object.defineProperty(c,"fetch",{...l,value:q}),s=!0,()=>{s=!1,J(c,"fetch",q,l,r)})},d=[];if(u.includes("xhr")){let c=B();c&&d.push(c)}if(u.includes("fetch")){let c=$();c&&d.push(c)}return d.length===0?T():(O=!0,{mode:"standard",disconnect:()=>{O=!1;for(let c of d.splice(0))c()}})}function Ne(e){let n=e.onNavigate;if(typeof n!="function")throw new TypeError("captureNavigation requires an onNavigate callback");let t=K(e.logger),o,r,u,i,y,m;try{if(o=window,r=o==null?void 0:o.history,!o||!r)return t.log("navigation capture unavailable: window/history missing"),T();if(y=ge(r,"pushState"),m=ge(r,"replaceState"),!y||!m)return t.log("navigation capture unavailable: history method descriptors missing"),T();if(u=y.descriptor.value,i=m.descriptor.value,typeof u!="function"||typeof i!="function")return t.log("navigation capture unavailable: history methods missing"),T();if(typeof o.addEventListener!="function"||typeof o.removeEventListener!="function")return t.log("navigation capture unavailable: window event methods missing"),T()}catch(g){return t.log("navigation capture unavailable: history inspection failed",g),T()}if(W(u)||W(i))return t.log("navigation capture unavailable: an equivalent capture is already active"),T();let j=!1,O=()=>({path:o.location.pathname,search:o.location.search,hash:o.location.hash}),x;try{x=O()}catch(g){return t.log("navigation capture unavailable: location inspection failed",g),T()}let P=X(t,"navigation",g=>{if(j)return n(g)}),C=g=>{if(j)try{let b=O();if(b.path===x.path&&b.search===x.search&&b.hash===x.hash)return;x=b,P({...b,source:g})}catch(b){t.log("navigation observation failed",b)}},S={pushState(...g){let b=Reflect.apply(u,this,g);return C("push"),b}}.pushState,B={replaceState(...g){let b=Reflect.apply(i,this,g);return C("replace"),b}}.replaceState;F(S,u),F(B,i);let $=()=>C("pop"),d=()=>C("hash");try{if(be(y,S),be(m,B),r.pushState!==S||r.replaceState!==B)throw new Error("history method replacement did not take effect");o.addEventListener("popstate",$),o.addEventListener("hashchange",d),j=!0}catch(g){return j=!1,Z(o,"popstate",$,t),Z(o,"hashchange",d,t),Q(m,B,t),Q(y,S,t),t.log("navigation capture unavailable: history methods are not writable",g),n=()=>{},P=()=>{},t=K(),T()}return{mode:"standard",disconnect:()=>{j=!1,n=()=>{},Z(o,"popstate",$,t),Z(o,"hashchange",d,t),Q(y,S,t),Q(m,B,t),P=()=>{},t=K()}}}function ge(e,n){let t=e;for(;t;){let o=Object.getOwnPropertyDescriptor(t,n);if(o)return!("value"in o)||typeof o.value!="function"?null:{owner:t,key:n,descriptor:o};t=Object.getPrototypeOf(t)}return null}function be(e,n){if(e.descriptor.writable!==!0)throw new TypeError(`${e.key} is not writable`);let t=Object.getOwnPropertyDescriptor(e.owner,e.key);if(!ae(t,e.descriptor))throw new Error(`${e.key} changed during installation`);Object.defineProperty(e.owner,e.key,{...e.descriptor,value:n})}function Q(e,n,t){J(e.owner,e.key,n,e.descriptor,t,`navigation ${e.key}`)}function Z(e,n,t,o){try{e.removeEventListener(n,t)}catch(r){o.log(`navigation ${n} listener removal skipped`,r)}}function je(e){let n=e.composedPath();return n.length>0?n:e.target?[e.target]:[]}var De="0.6.0";export{De as VERSION,Ne as captureNavigation,Be as captureNetwork,Ce as captureWebAuthn,je as composedPath,oe as sanitizeAssertionResponse,te as sanitizeCreationOptions,ne as sanitizeCreationResponse,re as sanitizeRequestOptions};
|
|
1
|
+
var we={creationOptions:["/user/name","/user/displayName"],creationResponse:["/clientExtensionResults/prf/results"],requestOptions:[],assertionResponse:["/response/signature","/clientExtensionResults/prf/results"]};function te(e){return Y(e,"creationOptions")}function ne(e){return Y(e,"creationResponse")}function re(e){return Y(e,"requestOptions")}function oe(e){return Y(e,"assertionResponse")}function Y(e,t){try{let n=typeof e=="string"?JSON.parse(e):e;if(!Re(n))return;let o=new Set(we[t]),i=new Set,d=(s,v,u=0)=>{if(!o.has(v)){if(s===null||typeof s=="string"||typeof s=="boolean")return s;if(typeof s=="number")return Number.isFinite(s)?s:null;if(typeof s=="object"){if(s instanceof ArrayBuffer||ArrayBuffer.isView(s))return Ce(s);if(u>64||i.has(s))throw new TypeError("Invalid telemetry payload");i.add(s);try{if(Array.isArray(s))return s.map((P,k)=>d(P,`${v}/${k}`,u+1));let B=Object.create(null);for(let P in s){let k=`${v}/${P.replace(/~/g,"~0").replace(/\//g,"~1")}`;if(o.has(k)||P==="toJSON")continue;let I=d(s[P],k,u+1);I!==void 0&&(B[P]=I)}let R=s,q=(P,k)=>{if(B[k]!==void 0||typeof R[P]!="function")return;let I=`${v}/${k}`,T=d(Reflect.apply(R[P],s,[]),I,u+1);T!==void 0&&(B[k]=T)};return v===""&&(t==="creationResponse"||t==="assertionResponse")&&q("getClientExtensionResults","clientExtensionResults"),v==="/response"&&t==="creationResponse"&&(q("getTransports","transports"),q("getAuthenticatorData","authenticatorData"),q("getPublicKey","publicKey"),q("getPublicKeyAlgorithm","publicKeyAlgorithm")),B}finally{i.delete(s)}}}};return JSON.stringify(d(n,""))}catch{return}}function Re(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e)}function Ce(e){let t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n="";for(let o of t)n+=String.fromCharCode(o);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}var Oe={log:()=>{}};function K(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{}}}:Oe}var ce=Symbol.for("corbado.autocapture.installed");function _(e){try{return typeof e=="function"&&Object.prototype.hasOwnProperty.call(e,ce)}catch{return!1}}function F(e,t){var o,i;let n=t;try{Object.defineProperty(e,ce,{value:t,configurable:!0})}catch{}try{Object.defineProperty(e,"name",{value:(o=n.name)!=null?o:"",configurable:!0})}catch{}try{Object.defineProperty(e,"length",{value:(i=n.length)!=null?i:0,configurable:!0})}catch{}return e}function M(){return{mode:"unavailable",disconnect:()=>{}}}function ie(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 X(e,t,n,o,i,d=String(t)){try{let s=Object.getOwnPropertyDescriptor(e,t);ie(s,{...o,value:n})&&Object.defineProperty(e,t,o)}catch(s){i.log(`${d} restoration skipped`,s)}}function z(e,t,n){let o=K(e);return i=>{try{let d=n(i);if(d&&(typeof d=="object"||typeof d=="function"))try{Promise.resolve(d).catch(s=>o.log(`${t} listener failed`,s))}catch(s){o.log(`${t} listener failed`,s)}}catch(d){o.log(`${t} listener failed`,d)}}}var de=e=>({get:e("get"),create:e("create")});function Ae(e){let t=e.onEvent;if(typeof t!="function")throw new TypeError("captureWebAuthn requires an onEvent callback");let n=K(e.logger),o=p=>(n.log(`webauthn capture unavailable: ${p}`),{...M(),surface:"none"}),i=typeof navigator=="undefined"?void 0:navigator,d=i==null?void 0:i.credentials;if(!i||!d)return o("navigator.credentials missing");let s=d,v=de(p=>s[p]);if(typeof v.get!="function"||typeof v.create!="function")return o("credentials methods missing");if(_(v.get)||_(v.create))return o("an equivalent capture is already active");let u=!1,B=0,R=z(n,"webauthn",t),q=(p,y,w)=>{let N={invoke(...l){let g=l[0];if(!u||w!=null&&w()||!ae(g)||!ae(g.publicKey))return y(this,l);let f=g.publicKey,c=`wa-${++B}`,x=y(this,l),S=ae(g.signal)?g.signal:void 0,r=Ee(p,g,f),h=b=>{u&&R({...r,ceremonyId:c,...b()})},C=()=>(S==null?void 0:S.aborted)===!0?{aborted:!0}:{};return h(()=>({phase:"started",userActivation:ke(i),...r.kind==="authentication"?{requestOptionsJson:re(f)}:{creationOptionsJson:te(f)}})),Promise.resolve(x).then(b=>(h(()=>({phase:"completed",credentialJson:p==="create"?ne(b):oe(b),...C()})),b),b=>{throw h(()=>({phase:"failed",error:b,errorName:Se(b),...C()})),b})}}.invoke;return F(N,{name:p,length:0})},P=p=>{var N;let y=q(p,(l,g)=>Reflect.apply(v[p],l,g)),w=Object.getOwnPropertyDescriptor(d,p);if(w&&(!("value"in w)||w.writable!==!0))return null;try{s[p]=y}catch{return null}if(((N=Object.getOwnPropertyDescriptor(d,p))==null?void 0:N.value)!==y){try{s[p]=v[p]}catch{}return null}return()=>{s[p]===y&&(w?s[p]=w.value:delete s[p])}},k=()=>{let p=de(()=>new WeakMap),y=(f,c)=>{let x=p[f].get(c);if(x)return x;let S=q(f,(r,h)=>Reflect.apply(c,d,h),()=>{try{let r=s[f];return r!==c&&r!==S}catch(r){return n.log("suppress check failed; ceremony unreported",r),!0}});return p[f].set(c,S),S},w=f=>{let c=Object.getOwnPropertyDescriptor(d,f);return c?c.configurable===!0||!("value"in c)||c.writable===!0:!0},N=new WeakMap,l=new Proxy(d,{get(f,c){let x=Reflect.get(d,c,d);if((c==="get"||c==="create")&&w(c))return typeof x!="function"||_(x)?x:y(c,x);if(typeof x!="function"||!w(c)||c==="constructor")return x;let S=N.get(x);if(S)return S;let r=x.bind(d);return N.set(x,r),r},set(f,c,x){return Reflect.set(d,c,x,d)}}),g=Object.getOwnPropertyDescriptor(i,"credentials");if(g&&g.configurable!==!0)return null;try{Object.defineProperty(i,"credentials",{value:l,writable:!0,enumerable:!0,configurable:!0})}catch{return null}return i.credentials!==l?null:()=>{i.credentials===l&&(g?Object.defineProperty(i,"credentials",g):delete i.credentials)}},I=(p,y)=>(u=!0,{mode:"standard",surface:p,disconnect:()=>{u=!1,y()}}),T=P("get"),j=T?P("create"):null;if(T&&j)return I("methods",()=>{T(),j()});if(T==null||T(),e.attach==="container"){let p=k();if(p)return n.log("webauthn capture attached at the credentials container"),I("container",p)}return o("credentials methods cannot be patched safely")}function Ee(e,t,n){let o=xe(t.mediation);if(e==="create")return{kind:"registration",mediation:o};let i=n;return{kind:"authentication",mediation:o,uiMode:qe(t.uiMode),credentialSet:Array.isArray(i.allowCredentials)&&i.allowCredentials.length>0?"allowlisted":"discoverable"}}function xe(e){return e===void 0?"optional":e==="silent"||e==="optional"||e==="conditional"||e==="required"?e:"unknown"}function qe(e){return e===void 0?"default":e==="immediate"?"immediate":"unknown"}function ke(e){let t=e.userActivation;return typeof(t==null?void 0:t.isActive)=="boolean"?t.isActive:void 0}function ae(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function Se(e){return e instanceof DOMException?e.name:"UnknownError"}var le=0;function pe(){return le+=1,`network-${le}`}function Pe(e,t){let n=e.responseType;if(n===""||n==="text")return t(e.responseText);if(n==="json"){let o=e.response;return o==null?void 0:t(o)}}var Ie=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 o=n.getReader(),i;try{let d=new Promise(u=>{i=setTimeout(()=>u(fe),Ie)}),s=new TextDecoder,v=[];for(;;){let u=await Promise.race([o.read(),d]);if(u===fe){t.log("body omitted: read timed out"),o.cancel().catch(()=>{});return}if(u.done)break;v.push(s.decode(u.value,{stream:!0}))}return v.push(s.decode()),v.join("")}catch{o.cancel().catch(()=>{});return}finally{i!==void 0&&clearTimeout(i)}}function se(e){var t;(t=e==null?void 0:e.body)==null||t.cancel().catch(()=>{})}function Te(e){var y,w,N;let{onExchange:t,onRequest:n,match:o}=e;if(typeof t!="function"||typeof o!="function")throw new TypeError("captureNetwork requires onExchange and match callbacks");let i=K(e.logger),d=(y=e.transports)!=null?y:["xhr","fetch"],s=(w=e.bodyCapture)==null?void 0:w.request,v=(N=e.bodyCapture)==null?void 0:N.response,u=typeof s=="function",B=typeof v=="function",R=!1,q=z(i,"network",l=>{if(R)return t(l)}),P=z(i,"network request",l=>{if(R)return n==null?void 0:n(l)}),k=(l,g,f)=>{if(typeof f=="function")try{return f(l,g)}catch(c){i.log("body projection failed",c);return}},I=(l,g)=>{try{let f=typeof document!="undefined"?document.baseURI:void 0,c=new URL(String(l),f);return o(c,g)===!0?{url:c.href,path:c.pathname}:void 0}catch{return}},T=()=>{if(typeof XMLHttpRequest=="undefined")return i.log("xhr capture unavailable: XMLHttpRequest missing"),null;let l=XMLHttpRequest.prototype,g=Object.getOwnPropertyDescriptor(l,"open"),f=Object.getOwnPropertyDescriptor(l,"send");if(!g||!("value"in g)||typeof g.value!="function"||!f||!("value"in f)||typeof f.value!="function")return i.log("xhr capture unavailable: XMLHttpRequest methods missing"),null;let c=g.value,x=f.value;if(_(c)||_(x))return i.log("xhr capture unavailable: an equivalent capture is already active"),null;let S=new WeakMap,r=new Set,h=!1,C={open(...O){var A;let a=Reflect.apply(c,this,O);if(!R||!h)return a;try{let D=S.get(this);D&&(D.reported=!0,(A=D.cleanupListeners)==null||A.call(D));let H=String(O[0]).toUpperCase(),L=I(O[1],H);L?S.set(this,{method:H,url:L.url,path:L.path,reported:!1}):S.delete(this)}catch(D){i.log("xhr open observation failed",D)}return a}}.open,b={send(...O){let a=R&&h?S.get(this):void 0;if(!a||a.reported||a.cleanupListeners)return Reflect.apply(x,this,O);let A=()=>{},D=!1;try{a.requestId=pe();let L={direction:"request",transport:"xhr",method:a.method,url:a.url,path:a.path};a.requestBody=u&&typeof O[0]=="string"?k(O[0],L,s):void 0;let J=()=>{a.outcome===void 0&&(a.outcome="abort")},G=()=>{a.outcome===void 0&&(a.outcome="timeout")},m=()=>{a.outcome===void 0&&(a.outcome="error")},E=()=>{var $;A();try{if(!R||!h||a.reported||!a.requestId)return;a.reported=!0;let W={direction:"response",transport:"xhr",method:a.method,url:a.url,path:a.path},ee=this.status,ue={requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,status:ee,ok:ee>=200&&ee<300,outcome:($=a.outcome)!=null?$:"load",durationMs:a.startedAt!==void 0?Date.now()-a.startedAt:void 0,responseUrl:this.responseURL||void 0,requestBody:a.requestBody,responseBody:B?Pe(this,ve=>k(ve,W,v)):void 0};a.requestEmitted?q(ue):a.pendingExchange=ue}catch(W){i.log("xhr exchange observation failed",W)}finally{S.get(this)===a&&S.delete(this)}},V=()=>{try{this.readyState===XMLHttpRequest.DONE&&this.status!==0&&E()}catch($){i.log("xhr ready-state observation failed",$)}},U=()=>E();A=()=>{for(let[$,W]of[["readystatechange",V],["abort",J],["timeout",G],["error",m],["loadend",U]])this.removeEventListener($,W);a.cleanupListeners===A&&(a.cleanupListeners=void 0),r.delete(A)},this.addEventListener("readystatechange",V),this.addEventListener("abort",J),this.addEventListener("timeout",G),this.addEventListener("error",m),this.addEventListener("loadend",U),a.cleanupListeners=A,r.add(A),a.startedAt=Date.now(),D=!0}catch(L){i.log("xhr send observation failed",L),A()}let H;try{H=Reflect.apply(x,this,O)}catch(L){throw A(),L}if(D&&a.requestId!==void 0&&a.startedAt!==void 0){a.requestEmitted=!0,P({requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,startedAt:a.startedAt,requestBody:a.requestBody});let L=a.pendingExchange;a.pendingExchange=void 0,L&&q(L)}return H}}.send;return F(C,c),F(b,x),g.writable!==!0||f.writable!==!0?(i.log("xhr capture unavailable: XMLHttpRequest methods are not writable"),null):(Object.defineProperty(l,"open",{...g,value:C}),Object.defineProperty(l,"send",{...f,value:b}),h=!0,()=>{h=!1;for(let O of[...r])O();X(l,"open",C,g,i),X(l,"send",b,f,i)})},j=()=>{let l=globalThis,g=Object.getOwnPropertyDescriptor(l,"fetch");if(!g||!("value"in g))return i.log("fetch capture unavailable: fetch is not an own data property"),null;let f=g.value;if(typeof f!="function")return i.log("fetch capture unavailable: fetch missing"),null;if(_(f))return i.log("fetch capture unavailable: an equivalent capture is already active"),null;let c=!1,x=async(r,h,C,b)=>{try{if(!R||!c){se(C);return}let[O,a]=await Promise.all([b!=null?b:Promise.resolve(void 0),C?ye(C,i):Promise.resolve(void 0)]);if(!R||!c)return;let A={direction:"request",transport:"fetch",method:r.method,url:r.url,path:r.path},D={...A,direction:"response"},H=r.requestBody;H===void 0&&O!==void 0&&(H=k(O,A,s));let L=a!==void 0?k(a,D,v):void 0;q({requestId:r.requestId,transport:"fetch",method:r.method,url:r.url,path:r.path,status:h.status,ok:h.ok,outcome:"load",durationMs:Date.now()-r.startedAt,responseUrl:h.url||void 0,requestBody:H,responseBody:L})}catch(O){i.log("fetch exchange observation failed",O)}},S={fetch(...r){var H,L,J,G;let h;try{let m=r[0],E=r[1];if(R&&c&&u&&typeof Request!="undefined"&&m instanceof Request&&(E==null?void 0:E.body)===void 0&&m.body){let V=String((H=E==null?void 0:E.method)!=null?H:m.method).toUpperCase(),U=(L=m.headers.get("content-type"))!=null?L:"";I(m.url,V)&&he(U)&&(h=m.clone())}}catch(m){i.log("fetch observation failed",m)}let C,b=Date.now();try{C=Reflect.apply(f,this,r)}catch(m){throw se(h),m}let O,a;try{if(R&&c){let m=r[0],E=r[1],V=typeof Request!="undefined"&&m instanceof Request,U=String((J=E==null?void 0:E.method)!=null?J:V?m.method:"GET").toUpperCase(),$=V?m.url:m,W=I($,U);W&&(O={requestId:pe(),method:U,url:W.url,path:W.path,startedAt:b},a=(G=E==null?void 0:E.signal)!=null?G:V?m.signal:void 0,u&&typeof(E==null?void 0:E.body)=="string"&&(O.requestBody=k(E.body,{direction:"request",transport:"fetch",method:U,url:W.url,path:W.path},s)))}}catch(m){i.log("fetch observation failed",m)}if(!O)return se(h),C;let A=O;P({requestId:A.requestId,transport:"fetch",method:A.method,url:A.url,path:A.path,startedAt:A.startedAt,requestBody:A.requestBody});let D=h?ye(h,i):void 0;return C.then(m=>{var V;let E;try{if(R&&c&&B){let U=(V=m.headers.get("content-type"))!=null?V:"";he(U)&&m.body&&(E=m.clone())}}catch{}x(A,m,E,D)},m=>{try{if(!R||!c)return;let E=(a==null?void 0:a.aborted)===!0||(m==null?void 0:m.name)==="AbortError"||typeof DOMException!="undefined"&&m instanceof DOMException&&m.code===DOMException.ABORT_ERR;q({requestId:A.requestId,transport:"fetch",method:A.method,url:A.url,path:A.path,status:0,ok:!1,outcome:E?"abort":"error",durationMs:Date.now()-A.startedAt})}catch(E){i.log("fetch failure observation failed",E)}}),C}}.fetch;return F(S,f),g.writable!==!0?(i.log("fetch capture unavailable: fetch is not writable"),null):(Object.defineProperty(l,"fetch",{...g,value:S}),c=!0,()=>{c=!1,X(l,"fetch",S,g,i)})},p=[];if(d.includes("xhr")){let l=T();l&&p.push(l)}if(d.includes("fetch")){let l=j();l&&p.push(l)}return p.length===0?M():(R=!0,{mode:"standard",disconnect:()=>{R=!1;for(let l of p.splice(0))l()}})}function Be(e){let t=e.onNavigate;if(typeof t!="function")throw new TypeError("captureNavigation requires an onNavigate callback");let n=K(e.logger),o,i,d,s,v,u;try{if(o=window,i=o==null?void 0:o.history,!o||!i)return n.log("navigation capture unavailable: window/history missing"),M();if(v=ge(i,"pushState"),u=ge(i,"replaceState"),!v||!u)return n.log("navigation capture unavailable: history method descriptors missing"),M();if(d=v.descriptor.value,s=u.descriptor.value,typeof d!="function"||typeof s!="function")return n.log("navigation capture unavailable: history methods missing"),M();if(typeof o.addEventListener!="function"||typeof o.removeEventListener!="function")return n.log("navigation capture unavailable: window event methods missing"),M()}catch(y){return n.log("navigation capture unavailable: history inspection failed",y),M()}if(_(d)||_(s))return n.log("navigation capture unavailable: an equivalent capture is already active"),M();let B=!1,R=()=>({path:o.location.pathname,search:o.location.search,hash:o.location.hash}),q;try{q=R()}catch(y){return n.log("navigation capture unavailable: location inspection failed",y),M()}let P=z(n,"navigation",y=>{if(B)return t(y)}),k=y=>{if(B)try{let w=R();if(w.path===q.path&&w.search===q.search&&w.hash===q.hash)return;q=w,P({...w,source:y})}catch(w){n.log("navigation observation failed",w)}},I={pushState(...y){let w=Reflect.apply(d,this,y);return k("push"),w}}.pushState,T={replaceState(...y){let w=Reflect.apply(s,this,y);return k("replace"),w}}.replaceState;F(I,d),F(T,s);let j=()=>k("pop"),p=()=>k("hash");try{if(be(v,I),be(u,T),i.pushState!==I||i.replaceState!==T)throw new Error("history method replacement did not take effect");o.addEventListener("popstate",j),o.addEventListener("hashchange",p),B=!0}catch(y){return B=!1,Z(o,"popstate",j,n),Z(o,"hashchange",p,n),Q(u,T,n),Q(v,I,n),n.log("navigation capture unavailable: history methods are not writable",y),t=()=>{},P=()=>{},n=K(),M()}return{mode:"standard",disconnect:()=>{B=!1,t=()=>{},Z(o,"popstate",j,n),Z(o,"hashchange",p,n),Q(v,I,n),Q(u,T,n),P=()=>{},n=K()}}}function ge(e,t){let n=e;for(;n;){let o=Object.getOwnPropertyDescriptor(n,t);if(o)return!("value"in o)||typeof o.value!="function"?null:{owner:n,key:t,descriptor:o};n=Object.getPrototypeOf(n)}return null}function be(e,t){if(e.descriptor.writable!==!0)throw new TypeError(`${e.key} is not writable`);let n=Object.getOwnPropertyDescriptor(e.owner,e.key);if(!ie(n,e.descriptor))throw new Error(`${e.key} changed during installation`);Object.defineProperty(e.owner,e.key,{...e.descriptor,value:t})}function Q(e,t,n){X(e.owner,e.key,t,e.descriptor,n,`navigation ${e.key}`)}function Z(e,t,n,o){try{e.removeEventListener(t,n)}catch(i){o.log(`navigation ${t} listener removal skipped`,i)}}function Le(e){let t=e.composedPath();return t.length>0?t:e.target?[e.target]:[]}var Ne="0.7.0";var De=["valueMissing","typeMismatch","patternMismatch","tooShort","tooLong","rangeUnderflow","rangeOverflow","stepMismatch","badInput","customError"];function me(e){return De.find(t=>e.validity[t])}function Me(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 He(e){var x,S;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=(x=e.maxObservationMs)!=null?x:1e4;if(!n.length||!Number.isFinite(o)||o<=0)throw new TypeError("captureInputValidation requires fields and a positive maxObservationMs");let i={mode:"unavailable",disconnect(){},beginAttempt:()=>{},requestStarted(){},refresh(){}},d=(S=t==null?void 0:t.ownerDocument)==null?void 0:S.defaultView;if(!d||!n.every(r=>r.form===t))return i;let s=!0,v=0,u,B=!1,R,q,P,k,I=[],T=()=>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"}},p=r=>r.status==="invalid"?JSON.stringify([r.code,r.fieldIndex]):void 0,y=()=>{u=void 0,clearTimeout(q),clearTimeout(P),q=P=void 0},w=()=>{q=void 0;let r=u;if(!s||!(r!=null&&r.confirmed))return;if(!T()){y();return}let h=r.nativeInvalid?(()=>{for(let[b,O]of n.entries()){let a=me(O);if(a)return{status:"invalid",source:"constraint",code:a,fieldIndex:b}}return{status:"clear"}})():j();if(h.status==="clear"){r.serverBaseline=void 0;return}if(h.status!=="invalid"||h.source==="application"&&r.serverBaseline===p(h))return;let C={attemptId:r.id,startedAt:r.startedAt,timestamp:Date.now(),code:h.code,...h.fieldIndex===void 0?{}:{fieldIndex:h.fieldIndex}};y(),B=!1;try{Promise.resolve(e.onError(C)).catch(()=>{})}catch{}},N=()=>{!s||!u||q!==void 0||(q=setTimeout(w,0))},l=r=>{if(!s||!T())return;y();let h=B?p(j()):void 0;return u={id:++v,startedAt:Date.now(),confirmed:r,nativeInvalid:!1,serverBaseline:h},P=setTimeout(y,o),N(),u.id},g=()=>{R===void 0&&(R=l(!1),k=setTimeout(()=>{u&&u.id===R&&!u.confirmed&&y(),R=void 0},0))},f=(r,h,C)=>{r.addEventListener(h,C,!0),I.push(()=>r.removeEventListener(h,C,!0))},c={mode:"standard",beginAttempt:()=>l(!0),refresh:N,requestStarted(r={}){s&&(r.attemptId!==void 0&&r.attemptId!==(u==null?void 0:u.id)||u&&r.timestamp!==void 0&&r.timestamp<u.startedAt||(y(),B=!0))},disconnect(){if(s){s=!1,y(),clearTimeout(k);for(let r of I.splice(0))r()}}};try{let r=C=>{var a;let b=C.target,O=(a=b==null?void 0:b.closest)==null?void 0:a.call(b,"button,input");(O==null?void 0:O.form)===t&&!O.disabled&&["submit","image"].includes(O.type)&&g()};f(t.ownerDocument,"click",r),f(t,"click",r),f(t,"keydown",C=>{let b=C;b.key==="Enter"&&!b.isComposing&&!b.defaultPrevented&&n.includes(b.target)&&g()}),f(t,"submit",()=>{(u==null?void 0:u.id)===R&&u?(u.confirmed=!0,N()):l(!0),R=void 0}),f(t,"invalid",C=>{!u||!n.includes(C.target)||(u.confirmed=!0,u.nativeInvalid=!0,N())}),f(t,"input",C=>{n.includes(C.target)&&y()});let h=new d.MutationObserver(N);h.observe(t,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),I.push(()=>h.disconnect())}catch{return c.disconnect(),i}return c}export{Ne as VERSION,He as captureInputValidation,Be as captureNavigation,Te as captureNetwork,Ae as captureWebAuthn,Le as composedPath,me as inputValidationCode,Me as isValidationMessageVisible,oe as sanitizeAssertionResponse,te as sanitizeCreationOptions,ne as sanitizeCreationResponse,re as sanitizeRequestOptions};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@corbado/autocapture",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "Observer-style capture helpers for WebAuthn ceremonies, selected network exchanges, in-app navigation, and composed event paths.",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|