@corbado/autocapture 0.6.0 → 0.8.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 +26 -5
- package/dist/index.d.mts +56 -9
- package/dist/index.d.ts +56 -9
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +7 -2
package/README.md
CHANGED
|
@@ -20,13 +20,13 @@ The package observes three kinds of signal:
|
|
|
20
20
|
|
|
21
21
|
It also exposes `composedPath()` for selector matching across visible shadow-DOM boundaries.
|
|
22
22
|
|
|
23
|
-
It
|
|
24
|
-
|
|
23
|
+
It uses `@corbado/observe` as a required runtime peer, ships TypeScript type definitions, and targets
|
|
24
|
+
ES2019 for its own bundle. The host application must also support the Observe SDK.
|
|
25
25
|
|
|
26
26
|
## Installation
|
|
27
27
|
|
|
28
28
|
```sh
|
|
29
|
-
npm install @corbado/autocapture
|
|
29
|
+
npm install @corbado/autocapture @corbado/observe@^0.16.0
|
|
30
30
|
```
|
|
31
31
|
|
|
32
32
|
## Usage
|
|
@@ -148,13 +148,15 @@ Navigation events likewise contain the raw `search` and `hash`. OAuth responses,
|
|
|
148
148
|
links, and application routes can put secrets or PII there; no navigation redaction policy is
|
|
149
149
|
currently applied.
|
|
150
150
|
|
|
151
|
-
WebAuthn interception and network fallbacks share four exported
|
|
151
|
+
WebAuthn interception and network fallbacks share four helpers exported by `@corbado/observe`
|
|
152
|
+
(and re-exported here for compatibility):
|
|
152
153
|
`sanitizeCreationOptions`, `sanitizeCreationResponse`, `sanitizeRequestOptions`, and
|
|
153
154
|
`sanitizeAssertionResponse`. Each accepts the relevant native browser object, a JSON object, or a
|
|
154
155
|
JSON string, and returns JSON text or `undefined` on malformed/unserializable input. Pass the
|
|
155
156
|
`publicKey` options or credential itself, not an application-specific request envelope.
|
|
156
157
|
|
|
157
|
-
|
|
158
|
+
Import these helpers directly from `@corbado/observe` for new integrations. The blacklist lives
|
|
159
|
+
only in Observe’s `src/utils/webauthn-payloads.ts`:
|
|
158
160
|
|
|
159
161
|
| Payload | Removed paths |
|
|
160
162
|
| --- | --- |
|
|
@@ -202,3 +204,22 @@ runtime. The current real-browser suite covers current
|
|
|
202
204
|
Chromium, Firefox, and WebKit, with password-manager simulation and virtual WebAuthn in Chromium.
|
|
203
205
|
That is not yet evidence for old iOS, Android WebView, legacy Edge, or arbitrary polyfills; expanding
|
|
204
206
|
the declared browser floor and test matrix is an open release decision.
|
|
207
|
+
|
|
208
|
+
## Input validation
|
|
209
|
+
|
|
210
|
+
`captureInputValidation()` observes one logical operation's fields and reports at most one local
|
|
211
|
+
validation error per submission attempt. Supply a validation-state reader and feed matching request
|
|
212
|
+
starts from your existing network capture. Native constraints, custom/auto-submit entry points,
|
|
213
|
+
multi-input groups, repeated submissions, server-error suppression, and cleanup are supported.
|
|
214
|
+
It does not activate automatically or collect field values/message text.
|
|
215
|
+
|
|
216
|
+
See [the API and evidence contract](src/input-validation.contract.md), including the limits of
|
|
217
|
+
asynchronous DOM inference and the `beginAttempt()`, `requestStarted()`, and `refresh()` methods.
|
|
218
|
+
|
|
219
|
+
## Local development
|
|
220
|
+
|
|
221
|
+
Run `pnpm --filter @corbado/autocapture... build` from the workspace root before linting or
|
|
222
|
+
running unit tests. The workspace development dependency supplies the required Observe peer;
|
|
223
|
+
Observe stays external in the published bundles. `pnpm test:e2e` builds both packages.
|
|
224
|
+
|
|
225
|
+
Release Observe 0.16.0 before autocapture 0.8.0 so the required peer is available on npm.
|
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
export { sanitizeAssertionResponse, sanitizeCreationOptions, sanitizeCreationResponse, sanitizeRequestOptions } from '@corbado/observe';
|
|
2
|
+
|
|
1
3
|
/** Receives optional diagnostics. Capture functions remain silent when no logger is provided. */
|
|
2
4
|
type Logger = {
|
|
3
5
|
/** Records a non-fatal diagnostic message. */
|
|
@@ -313,13 +315,58 @@ declare function composedPath(event: Event): readonly EventTarget[];
|
|
|
313
315
|
/** Version identifier embedded in the current build. */
|
|
314
316
|
declare const VERSION: string;
|
|
315
317
|
|
|
316
|
-
/**
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
318
|
+
/** Application UI state, read without copying field values or message text. */
|
|
319
|
+
type InputValidationState = {
|
|
320
|
+
status: "clear" | "pending" | "unknown";
|
|
321
|
+
} | {
|
|
322
|
+
status: "invalid";
|
|
323
|
+
/** A stable constraint/rule name, never a rendered message or field value. */
|
|
324
|
+
code: string;
|
|
325
|
+
/** Native constraint evidence can distinguish a new local error from a stale server error. */
|
|
326
|
+
source: "constraint" | "application";
|
|
327
|
+
/** Index into `fields` for operations owning multiple inputs. */
|
|
328
|
+
fieldIndex?: number;
|
|
329
|
+
};
|
|
330
|
+
type InputValidationError = {
|
|
331
|
+
attemptId: number;
|
|
332
|
+
startedAt: number;
|
|
333
|
+
timestamp: number;
|
|
334
|
+
code: string;
|
|
335
|
+
fieldIndex?: number;
|
|
336
|
+
};
|
|
337
|
+
type InputValidationCaptureOptions = {
|
|
338
|
+
form: HTMLFormElement;
|
|
339
|
+
/** One logical operation's inputs; do not include unrelated fields on the same form. */
|
|
340
|
+
fields: readonly HTMLInputElement[];
|
|
341
|
+
/**
|
|
342
|
+
* Read the application's settled validation UI. Return pending during asynchronous validation,
|
|
343
|
+
* and unknown when local rejection cannot be established. A bare aria-invalid flag is insufficient.
|
|
344
|
+
*/
|
|
345
|
+
readValidation: () => InputValidationState;
|
|
346
|
+
onError: (event: InputValidationError) => void;
|
|
347
|
+
/** Cleanup deadline for unresolved attempts. Expiration NEVER emits a validation error. Default 10s. */
|
|
348
|
+
maxObservationMs?: number;
|
|
349
|
+
};
|
|
350
|
+
type InputValidationCaptureHandle = CaptureHandle & {
|
|
351
|
+
/** Custom/auto-submit path; call before the application validates. Returns the attempt ID. */
|
|
352
|
+
beginAttempt(): number | undefined;
|
|
353
|
+
/** Feed only this operation's submission request, at request START, regardless of its eventual result. */
|
|
354
|
+
requestStarted(request?: {
|
|
355
|
+
timestamp?: number;
|
|
356
|
+
attemptId?: number;
|
|
357
|
+
}): void;
|
|
358
|
+
/** Re-read after an application validation signal that is not represented by a DOM mutation. */
|
|
359
|
+
refresh(): void;
|
|
360
|
+
};
|
|
361
|
+
/** Reads native validity flags without invoking checkValidity/reportValidity or accessing the value. */
|
|
362
|
+
declare function inputValidationCode(input: HTMLInputElement): string | undefined;
|
|
363
|
+
/** Rendered visibility, including hidden ancestors and opacity; does not require viewport intersection. */
|
|
364
|
+
declare function isValidationMessageVisible(element: Element | null): boolean;
|
|
365
|
+
/**
|
|
366
|
+
* Observes submission attempts for one input-backed operation. Never prevents submission, mutates
|
|
367
|
+
* validation, or installs a network interceptor. One error at most per attempt, even with several
|
|
368
|
+
* inputs or repeated DOM mutations. See input-validation.contract.md for the evidence boundary.
|
|
369
|
+
*/
|
|
370
|
+
declare function captureInputValidation(options: InputValidationCaptureOptions): InputValidationCaptureHandle;
|
|
324
371
|
|
|
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,
|
|
372
|
+
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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
export { sanitizeAssertionResponse, sanitizeCreationOptions, sanitizeCreationResponse, sanitizeRequestOptions } from '@corbado/observe';
|
|
2
|
+
|
|
1
3
|
/** Receives optional diagnostics. Capture functions remain silent when no logger is provided. */
|
|
2
4
|
type Logger = {
|
|
3
5
|
/** Records a non-fatal diagnostic message. */
|
|
@@ -313,13 +315,58 @@ declare function composedPath(event: Event): readonly EventTarget[];
|
|
|
313
315
|
/** Version identifier embedded in the current build. */
|
|
314
316
|
declare const VERSION: string;
|
|
315
317
|
|
|
316
|
-
/**
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
318
|
+
/** Application UI state, read without copying field values or message text. */
|
|
319
|
+
type InputValidationState = {
|
|
320
|
+
status: "clear" | "pending" | "unknown";
|
|
321
|
+
} | {
|
|
322
|
+
status: "invalid";
|
|
323
|
+
/** A stable constraint/rule name, never a rendered message or field value. */
|
|
324
|
+
code: string;
|
|
325
|
+
/** Native constraint evidence can distinguish a new local error from a stale server error. */
|
|
326
|
+
source: "constraint" | "application";
|
|
327
|
+
/** Index into `fields` for operations owning multiple inputs. */
|
|
328
|
+
fieldIndex?: number;
|
|
329
|
+
};
|
|
330
|
+
type InputValidationError = {
|
|
331
|
+
attemptId: number;
|
|
332
|
+
startedAt: number;
|
|
333
|
+
timestamp: number;
|
|
334
|
+
code: string;
|
|
335
|
+
fieldIndex?: number;
|
|
336
|
+
};
|
|
337
|
+
type InputValidationCaptureOptions = {
|
|
338
|
+
form: HTMLFormElement;
|
|
339
|
+
/** One logical operation's inputs; do not include unrelated fields on the same form. */
|
|
340
|
+
fields: readonly HTMLInputElement[];
|
|
341
|
+
/**
|
|
342
|
+
* Read the application's settled validation UI. Return pending during asynchronous validation,
|
|
343
|
+
* and unknown when local rejection cannot be established. A bare aria-invalid flag is insufficient.
|
|
344
|
+
*/
|
|
345
|
+
readValidation: () => InputValidationState;
|
|
346
|
+
onError: (event: InputValidationError) => void;
|
|
347
|
+
/** Cleanup deadline for unresolved attempts. Expiration NEVER emits a validation error. Default 10s. */
|
|
348
|
+
maxObservationMs?: number;
|
|
349
|
+
};
|
|
350
|
+
type InputValidationCaptureHandle = CaptureHandle & {
|
|
351
|
+
/** Custom/auto-submit path; call before the application validates. Returns the attempt ID. */
|
|
352
|
+
beginAttempt(): number | undefined;
|
|
353
|
+
/** Feed only this operation's submission request, at request START, regardless of its eventual result. */
|
|
354
|
+
requestStarted(request?: {
|
|
355
|
+
timestamp?: number;
|
|
356
|
+
attemptId?: number;
|
|
357
|
+
}): void;
|
|
358
|
+
/** Re-read after an application validation signal that is not represented by a DOM mutation. */
|
|
359
|
+
refresh(): void;
|
|
360
|
+
};
|
|
361
|
+
/** Reads native validity flags without invoking checkValidity/reportValidity or accessing the value. */
|
|
362
|
+
declare function inputValidationCode(input: HTMLInputElement): string | undefined;
|
|
363
|
+
/** Rendered visibility, including hidden ancestors and opacity; does not require viewport intersection. */
|
|
364
|
+
declare function isValidationMessageVisible(element: Element | null): boolean;
|
|
365
|
+
/**
|
|
366
|
+
* Observes submission attempts for one input-backed operation. Never prevents submission, mutates
|
|
367
|
+
* validation, or installs a network interceptor. One error at most per attempt, even with several
|
|
368
|
+
* inputs or repeated DOM mutations. See input-validation.contract.md for the evidence boundary.
|
|
369
|
+
*/
|
|
370
|
+
declare function captureInputValidation(options: InputValidationCaptureOptions): InputValidationCaptureHandle;
|
|
324
371
|
|
|
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,
|
|
372
|
+
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 };
|
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 ne=Object.defineProperty;var Oe=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var Ae=Object.prototype.hasOwnProperty;var ke=(e,t)=>{for(var n in t)ne(e,n,{get:t[n],enumerable:!0})},Ie=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of xe(t))!Ae.call(e,o)&&o!==n&&ne(e,o,{get:()=>t[o],enumerable:!(i=Oe(t,o))||i.enumerable});return e};var Pe=e=>Ie(ne({},"__esModule",{value:!0}),e);var Ve={};ke(Ve,{VERSION:()=>Re,captureInputValidation:()=>Ee,captureNavigation:()=>be,captureNetwork:()=>ge,captureWebAuthn:()=>ce,composedPath:()=>we,inputValidationCode:()=>ae,isValidationMessageVisible:()=>Ce,sanitizeAssertionResponse:()=>$.sanitizeAssertionResponse,sanitizeCreationOptions:()=>$.sanitizeCreationOptions,sanitizeCreationResponse:()=>$.sanitizeCreationResponse,sanitizeRequestOptions:()=>$.sanitizeRequestOptions});module.exports=Pe(Ve);var z=require("@corbado/observe");var Se={log:()=>{}};function F(e){return e?{log:(...t)=>{try{let n=e.log(...t);if(n&&(typeof n=="object"||typeof n=="function"))try{Promise.resolve(n).catch(()=>{})}catch{}}catch{}}}:Se}var ue=Symbol.for("corbado.autocapture.installed");function _(e){try{return typeof e=="function"&&Object.prototype.hasOwnProperty.call(e,ue)}catch{return!1}}function K(e,t){var i,o;let n=t;try{Object.defineProperty(e,ue,{value:t,configurable:!0})}catch{}try{Object.defineProperty(e,"name",{value:(i=n.name)!=null?i:"",configurable:!0})}catch{}try{Object.defineProperty(e,"length",{value:(o=n.length)!=null?o:0,configurable:!0})}catch{}return e}function N(){return{mode:"unavailable",disconnect:()=>{}}}function re(e,t){return!!e&&"value"in e&&"value"in t&&e.value===t.value&&e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable}function G(e,t,n,i,o,y=String(t)){try{let f=Object.getOwnPropertyDescriptor(e,t);re(f,{...i,value:n})&&Object.defineProperty(e,t,i)}catch(f){o.log(`${y} restoration skipped`,f)}}function J(e,t,n){let i=F(e);return o=>{try{let y=n(o);if(y&&(typeof y=="object"||typeof y=="function"))try{Promise.resolve(y).catch(f=>i.log(`${t} listener failed`,f))}catch(f){i.log(`${t} listener failed`,f)}}catch(y){i.log(`${t} listener failed`,y)}}}var de=e=>({get:e("get"),create:e("create")});function ce(e){let t=e.onEvent;if(typeof t!="function")throw new TypeError("captureWebAuthn requires an onEvent callback");let n=F(e.logger),i=c=>(n.log(`webauthn capture unavailable: ${c}`),{...N(),surface:"none"}),o=typeof navigator=="undefined"?void 0:navigator,y=o==null?void 0:o.credentials;if(!o||!y)return i("navigator.credentials missing");let f=y,A=de(c=>f[c]);if(typeof A.get!="function"||typeof A.create!="function")return i("credentials methods missing");if(_(A.get)||_(A.create))return i("an equivalent capture is already active");let s=!1,B=0,O=J(n,"webauthn",t),k=(c,h,b)=>{let T={invoke(...d){let g=d[0];if(!s||b!=null&&b()||!oe(g)||!oe(g.publicKey))return h(this,d);let l=g.publicKey,u=`wa-${++B}`,q=h(this,d),x=oe(g.signal)?g.signal:void 0,r=Te(c,g,l),p=m=>{s&&O({...r,ceremonyId:u,...m()})},w=()=>(x==null?void 0:x.aborted)===!0?{aborted:!0}:{};return p(()=>({phase:"started",userActivation:Me(o),...r.kind==="authentication"?{requestOptionsJson:(0,z.sanitizeRequestOptions)(l)}:{creationOptionsJson:(0,z.sanitizeCreationOptions)(l)}})),Promise.resolve(q).then(m=>(p(()=>({phase:"completed",credentialJson:c==="create"?(0,z.sanitizeCreationResponse)(m):(0,z.sanitizeAssertionResponse)(m),...w()})),m),m=>{throw p(()=>({phase:"failed",error:m,errorName:De(m),...w()})),m})}}.invoke;return K(T,{name:c,length:0})},D=c=>{var T;let h=k(c,(d,g)=>Reflect.apply(A[c],d,g)),b=Object.getOwnPropertyDescriptor(y,c);if(b&&(!("value"in b)||b.writable!==!0))return null;try{f[c]=h}catch{return null}if(((T=Object.getOwnPropertyDescriptor(y,c))==null?void 0:T.value)!==h){try{f[c]=A[c]}catch{}return null}return()=>{f[c]===h&&(b?f[c]=b.value:delete f[c])}},L=()=>{let c=de(()=>new WeakMap),h=(l,u)=>{let q=c[l].get(u);if(q)return q;let x=k(l,(r,p)=>Reflect.apply(u,y,p),()=>{try{let r=f[l];return r!==u&&r!==x}catch(r){return n.log("suppress check failed; ceremony unreported",r),!0}});return c[l].set(u,x),x},b=l=>{let u=Object.getOwnPropertyDescriptor(y,l);return u?u.configurable===!0||!("value"in u)||u.writable===!0:!0},T=new WeakMap,d=new Proxy(y,{get(l,u){let q=Reflect.get(y,u,y);if((u==="get"||u==="create")&&b(u))return typeof q!="function"||_(q)?q:h(u,q);if(typeof q!="function"||!b(u)||u==="constructor")return q;let x=T.get(q);if(x)return x;let r=q.bind(y);return T.set(q,r),r},set(l,u,q){return Reflect.set(y,u,q,y)}}),g=Object.getOwnPropertyDescriptor(o,"credentials");if(g&&g.configurable!==!0)return null;try{Object.defineProperty(o,"credentials",{value:d,writable:!0,enumerable:!0,configurable:!0})}catch{return null}return o.credentials!==d?null:()=>{o.credentials===d&&(g?Object.defineProperty(o,"credentials",g):delete o.credentials)}},S=(c,h)=>(s=!0,{mode:"standard",surface:c,disconnect:()=>{s=!1,h()}}),I=D("get"),j=I?D("create"):null;if(I&&j)return S("methods",()=>{I(),j()});if(I==null||I(),e.attach==="container"){let c=L();if(c)return n.log("webauthn capture attached at the credentials container"),S("container",c)}return i("credentials methods cannot be patched safely")}function Te(e,t,n){let i=Le(t.mediation);if(e==="create")return{kind:"registration",mediation:i};let o=n;return{kind:"authentication",mediation:i,uiMode:Be(t.uiMode),credentialSet:Array.isArray(o.allowCredentials)&&o.allowCredentials.length>0?"allowlisted":"discoverable"}}function Le(e){return e===void 0?"optional":e==="silent"||e==="optional"||e==="conditional"||e==="required"?e:"unknown"}function Be(e){return e===void 0?"default":e==="immediate"?"immediate":"unknown"}function Me(e){let t=e.userActivation;return typeof(t==null?void 0:t.isActive)=="boolean"?t.isActive:void 0}function oe(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function De(e){return e instanceof DOMException?e.name:"UnknownError"}var le=0;function pe(){return le+=1,`network-${le}`}function Ne(e,t){let n=e.responseType;if(n===""||n==="text")return t(e.responseText);if(n==="json"){let i=e.response;return i==null?void 0:t(i)}}var He=500,fe=Symbol("body-read-timeout");function he(e){return/event-stream|octet-stream/i.test(e)?!1:/json|text|urlencoded/i.test(e)}async function ye(e,t){let n=e.body;if(!n)return;let i=n.getReader(),o;try{let y=new Promise(s=>{o=setTimeout(()=>s(fe),He)}),f=new TextDecoder,A=[];for(;;){let s=await Promise.race([i.read(),y]);if(s===fe){t.log("body omitted: read timed out"),i.cancel().catch(()=>{});return}if(s.done)break;A.push(f.decode(s.value,{stream:!0}))}return A.push(f.decode()),A.join("")}catch{i.cancel().catch(()=>{});return}finally{o!==void 0&&clearTimeout(o)}}function ie(e){var t;(t=e==null?void 0:e.body)==null||t.cancel().catch(()=>{})}function ge(e){var h,b,T;let{onExchange:t,onRequest:n,match:i}=e;if(typeof t!="function"||typeof i!="function")throw new TypeError("captureNetwork requires onExchange and match callbacks");let o=F(e.logger),y=(h=e.transports)!=null?h:["xhr","fetch"],f=(b=e.bodyCapture)==null?void 0:b.request,A=(T=e.bodyCapture)==null?void 0:T.response,s=typeof f=="function",B=typeof A=="function",O=!1,k=J(o,"network",d=>{if(O)return t(d)}),D=J(o,"network request",d=>{if(O)return n==null?void 0:n(d)}),L=(d,g,l)=>{if(typeof l=="function")try{return l(d,g)}catch(u){o.log("body projection failed",u);return}},S=(d,g)=>{try{let l=typeof document!="undefined"?document.baseURI:void 0,u=new URL(String(d),l);return i(u,g)===!0?{url:u.href,path:u.pathname}:void 0}catch{return}},I=()=>{if(typeof XMLHttpRequest=="undefined")return o.log("xhr capture unavailable: XMLHttpRequest missing"),null;let d=XMLHttpRequest.prototype,g=Object.getOwnPropertyDescriptor(d,"open"),l=Object.getOwnPropertyDescriptor(d,"send");if(!g||!("value"in g)||typeof g.value!="function"||!l||!("value"in l)||typeof l.value!="function")return o.log("xhr capture unavailable: XMLHttpRequest methods missing"),null;let u=g.value,q=l.value;if(_(u)||_(q))return o.log("xhr capture unavailable: an equivalent capture is already active"),null;let x=new WeakMap,r=new Set,p=!1,w={open(...R){var C;let a=Reflect.apply(u,this,R);if(!O||!p)return a;try{let M=x.get(this);M&&(M.reported=!0,(C=M.cleanupListeners)==null||C.call(M));let H=String(R[0]).toUpperCase(),P=S(R[1],H);P?x.set(this,{method:H,url:P.url,path:P.path,reported:!1}):x.delete(this)}catch(M){o.log("xhr open observation failed",M)}return a}}.open,m={send(...R){let a=O&&p?x.get(this):void 0;if(!a||a.reported||a.cleanupListeners)return Reflect.apply(q,this,R);let C=()=>{},M=!1;try{a.requestId=pe();let P={direction:"request",transport:"xhr",method:a.method,url:a.url,path:a.path};a.requestBody=s&&typeof R[0]=="string"?L(R[0],P,f):void 0;let Y=()=>{a.outcome===void 0&&(a.outcome="abort")},Q=()=>{a.outcome===void 0&&(a.outcome="timeout")},v=()=>{a.outcome===void 0&&(a.outcome="error")},E=()=>{var X;C();try{if(!O||!p||a.reported||!a.requestId)return;a.reported=!0;let W={direction:"response",transport:"xhr",method:a.method,url:a.url,path:a.path},te=this.status,se={requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,status:te,ok:te>=200&&te<300,outcome:(X=a.outcome)!=null?X:"load",durationMs:a.startedAt!==void 0?Date.now()-a.startedAt:void 0,responseUrl:this.responseURL||void 0,requestBody:a.requestBody,responseBody:B?Ne(this,qe=>L(qe,W,A)):void 0};a.requestEmitted?k(se):a.pendingExchange=se}catch(W){o.log("xhr exchange observation failed",W)}finally{x.get(this)===a&&x.delete(this)}},V=()=>{try{this.readyState===XMLHttpRequest.DONE&&this.status!==0&&E()}catch(X){o.log("xhr ready-state observation failed",X)}},U=()=>E();C=()=>{for(let[X,W]of[["readystatechange",V],["abort",Y],["timeout",Q],["error",v],["loadend",U]])this.removeEventListener(X,W);a.cleanupListeners===C&&(a.cleanupListeners=void 0),r.delete(C)},this.addEventListener("readystatechange",V),this.addEventListener("abort",Y),this.addEventListener("timeout",Q),this.addEventListener("error",v),this.addEventListener("loadend",U),a.cleanupListeners=C,r.add(C),a.startedAt=Date.now(),M=!0}catch(P){o.log("xhr send observation failed",P),C()}let H;try{H=Reflect.apply(q,this,R)}catch(P){throw C(),P}if(M&&a.requestId!==void 0&&a.startedAt!==void 0){a.requestEmitted=!0,D({requestId:a.requestId,transport:"xhr",method:a.method,url:a.url,path:a.path,startedAt:a.startedAt,requestBody:a.requestBody});let P=a.pendingExchange;a.pendingExchange=void 0,P&&k(P)}return H}}.send;return K(w,u),K(m,q),g.writable!==!0||l.writable!==!0?(o.log("xhr capture unavailable: XMLHttpRequest methods are not writable"),null):(Object.defineProperty(d,"open",{...g,value:w}),Object.defineProperty(d,"send",{...l,value:m}),p=!0,()=>{p=!1;for(let R of[...r])R();G(d,"open",w,g,o),G(d,"send",m,l,o)})},j=()=>{let d=globalThis,g=Object.getOwnPropertyDescriptor(d,"fetch");if(!g||!("value"in g))return o.log("fetch capture unavailable: fetch is not an own data property"),null;let l=g.value;if(typeof l!="function")return o.log("fetch capture unavailable: fetch missing"),null;if(_(l))return o.log("fetch capture unavailable: an equivalent capture is already active"),null;let u=!1,q=async(r,p,w,m)=>{try{if(!O||!u){ie(w);return}let[R,a]=await Promise.all([m!=null?m:Promise.resolve(void 0),w?ye(w,o):Promise.resolve(void 0)]);if(!O||!u)return;let C={direction:"request",transport:"fetch",method:r.method,url:r.url,path:r.path},M={...C,direction:"response"},H=r.requestBody;H===void 0&&R!==void 0&&(H=L(R,C,f));let P=a!==void 0?L(a,M,A):void 0;k({requestId:r.requestId,transport:"fetch",method:r.method,url:r.url,path:r.path,status:p.status,ok:p.ok,outcome:"load",durationMs:Date.now()-r.startedAt,responseUrl:p.url||void 0,requestBody:H,responseBody:P})}catch(R){o.log("fetch exchange observation failed",R)}},x={fetch(...r){var H,P,Y,Q;let p;try{let v=r[0],E=r[1];if(O&&u&&s&&typeof Request!="undefined"&&v instanceof Request&&(E==null?void 0:E.body)===void 0&&v.body){let V=String((H=E==null?void 0:E.method)!=null?H:v.method).toUpperCase(),U=(P=v.headers.get("content-type"))!=null?P:"";S(v.url,V)&&he(U)&&(p=v.clone())}}catch(v){o.log("fetch observation failed",v)}let w,m=Date.now();try{w=Reflect.apply(l,this,r)}catch(v){throw ie(p),v}let R,a;try{if(O&&u){let v=r[0],E=r[1],V=typeof Request!="undefined"&&v instanceof Request,U=String((Y=E==null?void 0:E.method)!=null?Y:V?v.method:"GET").toUpperCase(),X=V?v.url:v,W=S(X,U);W&&(R={requestId:pe(),method:U,url:W.url,path:W.path,startedAt:m},a=(Q=E==null?void 0:E.signal)!=null?Q:V?v.signal:void 0,s&&typeof(E==null?void 0:E.body)=="string"&&(R.requestBody=L(E.body,{direction:"request",transport:"fetch",method:U,url:W.url,path:W.path},f)))}}catch(v){o.log("fetch observation failed",v)}if(!R)return ie(p),w;let C=R;D({requestId:C.requestId,transport:"fetch",method:C.method,url:C.url,path:C.path,startedAt:C.startedAt,requestBody:C.requestBody});let M=p?ye(p,o):void 0;return w.then(v=>{var V;let E;try{if(O&&u&&B){let U=(V=v.headers.get("content-type"))!=null?V:"";he(U)&&v.body&&(E=v.clone())}}catch{}q(C,v,E,M)},v=>{try{if(!O||!u)return;let E=(a==null?void 0:a.aborted)===!0||(v==null?void 0:v.name)==="AbortError"||typeof DOMException!="undefined"&&v instanceof DOMException&&v.code===DOMException.ABORT_ERR;k({requestId:C.requestId,transport:"fetch",method:C.method,url:C.url,path:C.path,status:0,ok:!1,outcome:E?"abort":"error",durationMs:Date.now()-C.startedAt})}catch(E){o.log("fetch failure observation failed",E)}}),w}}.fetch;return K(x,l),g.writable!==!0?(o.log("fetch capture unavailable: fetch is not writable"),null):(Object.defineProperty(d,"fetch",{...g,value:x}),u=!0,()=>{u=!1,G(d,"fetch",x,g,o)})},c=[];if(y.includes("xhr")){let d=I();d&&c.push(d)}if(y.includes("fetch")){let d=j();d&&c.push(d)}return c.length===0?N():(O=!0,{mode:"standard",disconnect:()=>{O=!1;for(let d of c.splice(0))d()}})}function be(e){let t=e.onNavigate;if(typeof t!="function")throw new TypeError("captureNavigation requires an onNavigate callback");let n=F(e.logger),i,o,y,f,A,s;try{if(i=window,o=i==null?void 0:i.history,!i||!o)return n.log("navigation capture unavailable: window/history missing"),N();if(A=me(o,"pushState"),s=me(o,"replaceState"),!A||!s)return n.log("navigation capture unavailable: history method descriptors missing"),N();if(y=A.descriptor.value,f=s.descriptor.value,typeof y!="function"||typeof f!="function")return n.log("navigation capture unavailable: history methods missing"),N();if(typeof i.addEventListener!="function"||typeof i.removeEventListener!="function")return n.log("navigation capture unavailable: window event methods missing"),N()}catch(h){return n.log("navigation capture unavailable: history inspection failed",h),N()}if(_(y)||_(f))return n.log("navigation capture unavailable: an equivalent capture is already active"),N();let B=!1,O=()=>({path:i.location.pathname,search:i.location.search,hash:i.location.hash}),k;try{k=O()}catch(h){return n.log("navigation capture unavailable: location inspection failed",h),N()}let D=J(n,"navigation",h=>{if(B)return t(h)}),L=h=>{if(B)try{let b=O();if(b.path===k.path&&b.search===k.search&&b.hash===k.hash)return;k=b,D({...b,source:h})}catch(b){n.log("navigation observation failed",b)}},S={pushState(...h){let b=Reflect.apply(y,this,h);return L("push"),b}}.pushState,I={replaceState(...h){let b=Reflect.apply(f,this,h);return L("replace"),b}}.replaceState;K(S,y),K(I,f);let j=()=>L("pop"),c=()=>L("hash");try{if(ve(A,S),ve(s,I),o.pushState!==S||o.replaceState!==I)throw new Error("history method replacement did not take effect");i.addEventListener("popstate",j),i.addEventListener("hashchange",c),B=!0}catch(h){return B=!1,ee(i,"popstate",j,n),ee(i,"hashchange",c,n),Z(s,I,n),Z(A,S,n),n.log("navigation capture unavailable: history methods are not writable",h),t=()=>{},D=()=>{},n=F(),N()}return{mode:"standard",disconnect:()=>{B=!1,t=()=>{},ee(i,"popstate",j,n),ee(i,"hashchange",c,n),Z(A,S,n),Z(s,I,n),D=()=>{},n=F()}}}function me(e,t){let n=e;for(;n;){let i=Object.getOwnPropertyDescriptor(n,t);if(i)return!("value"in i)||typeof i.value!="function"?null:{owner:n,key:t,descriptor:i};n=Object.getPrototypeOf(n)}return null}function ve(e,t){if(e.descriptor.writable!==!0)throw new TypeError(`${e.key} is not writable`);let n=Object.getOwnPropertyDescriptor(e.owner,e.key);if(!re(n,e.descriptor))throw new Error(`${e.key} changed during installation`);Object.defineProperty(e.owner,e.key,{...e.descriptor,value:t})}function Z(e,t,n){G(e.owner,e.key,t,e.descriptor,n,`navigation ${e.key}`)}function ee(e,t,n,i){try{e.removeEventListener(t,n)}catch(o){i.log(`navigation ${t} listener removal skipped`,o)}}function we(e){let t=e.composedPath();return t.length>0?t:e.target?[e.target]:[]}var Re="0.8.0";var je=["valueMissing","typeMismatch","patternMismatch","tooShort","tooLong","rangeUnderflow","rangeOverflow","stepMismatch","badInput","customError"];function ae(e){return je.find(t=>e.validity[t])}function Ce(e){if(!(e!=null&&e.isConnected)||!e.getClientRects().length)return!1;let t=e.ownerDocument.defaultView;if(!t)return!1;for(let n=e;n;n=n.parentElement){let i=t.getComputedStyle(n);if(n.hasAttribute("hidden")||i.display==="none"||i.visibility==="hidden"||i.visibility==="collapse"||i.opacity==="0")return!1}return!0}function Ee(e){var q,x;if(typeof e.readValidation!="function"||typeof e.onError!="function")throw new TypeError("captureInputValidation requires readValidation and onError callbacks");let{form:t}=e,n=[...e.fields],i=(q=e.maxObservationMs)!=null?q:1e4;if(!n.length||!Number.isFinite(i)||i<=0)throw new TypeError("captureInputValidation requires fields and a positive maxObservationMs");let o={mode:"unavailable",disconnect(){},beginAttempt:()=>{},requestStarted(){},refresh(){}},y=(x=t==null?void 0:t.ownerDocument)==null?void 0:x.defaultView;if(!y||!n.every(r=>r.form===t))return o;let f=!0,A=0,s,B=!1,O,k,D,L,S=[],I=()=>t.isConnected&&n.every(r=>r.isConnected&&r.form===t),j=()=>{try{let r=e.readValidation();if(r&&["clear","pending","unknown"].includes(r.status)||(r==null?void 0:r.status)==="invalid"&&typeof r.code=="string"&&["constraint","application"].includes(r.source))return r}catch{}return{status:"unknown"}},c=r=>r.status==="invalid"?JSON.stringify([r.code,r.fieldIndex]):void 0,h=()=>{s=void 0,clearTimeout(k),clearTimeout(D),k=D=void 0},b=()=>{k=void 0;let r=s;if(!f||!(r!=null&&r.confirmed))return;if(!I()){h();return}let p=r.nativeInvalid?(()=>{for(let[m,R]of n.entries()){let a=ae(R);if(a)return{status:"invalid",source:"constraint",code:a,fieldIndex:m}}return{status:"clear"}})():j();if(p.status==="clear"){r.serverBaseline=void 0;return}if(p.status!=="invalid"||p.source==="application"&&r.serverBaseline===c(p))return;let w={attemptId:r.id,startedAt:r.startedAt,timestamp:Date.now(),code:p.code,...p.fieldIndex===void 0?{}:{fieldIndex:p.fieldIndex}};h(),B=!1;try{Promise.resolve(e.onError(w)).catch(()=>{})}catch{}},T=()=>{!f||!s||k!==void 0||(k=setTimeout(b,0))},d=r=>{if(!f||!I())return;h();let p=B?c(j()):void 0;return s={id:++A,startedAt:Date.now(),confirmed:r,nativeInvalid:!1,serverBaseline:p},D=setTimeout(h,i),T(),s.id},g=()=>{O===void 0&&(O=d(!1),L=setTimeout(()=>{s&&s.id===O&&!s.confirmed&&h(),O=void 0},0))},l=(r,p,w)=>{r.addEventListener(p,w,!0),S.push(()=>r.removeEventListener(p,w,!0))},u={mode:"standard",beginAttempt:()=>d(!0),refresh:T,requestStarted(r={}){f&&(r.attemptId!==void 0&&r.attemptId!==(s==null?void 0:s.id)||s&&r.timestamp!==void 0&&r.timestamp<s.startedAt||(h(),B=!0))},disconnect(){if(f){f=!1,h(),clearTimeout(L);for(let r of S.splice(0))r()}}};try{let r=w=>{var a;let m=w.target,R=(a=m==null?void 0:m.closest)==null?void 0:a.call(m,"button,input");(R==null?void 0:R.form)===t&&!R.disabled&&["submit","image"].includes(R.type)&&g()};l(t.ownerDocument,"click",r),l(t,"click",r),l(t,"keydown",w=>{let m=w;m.key==="Enter"&&!m.isComposing&&!m.defaultPrevented&&n.includes(m.target)&&g()}),l(t,"submit",()=>{(s==null?void 0:s.id)===O&&s?(s.confirmed=!0,T()):d(!0),O=void 0}),l(t,"invalid",w=>{!s||!n.includes(w.target)||(s.confirmed=!0,s.nativeInvalid=!0,T())}),l(t,"input",w=>{n.includes(w.target)&&h()});let p=new y.MutationObserver(T);p.observe(t,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),S.push(()=>p.disconnect())}catch{return u.disconnect(),o}return u}var $=require("@corbado/observe");0&&(module.exports={VERSION,captureInputValidation,captureNavigation,captureNetwork,captureWebAuthn,composedPath,inputValidationCode,isValidationMessageVisible,sanitizeAssertionResponse,sanitizeCreationOptions,sanitizeCreationResponse,sanitizeRequestOptions});
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
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
|
+
import{sanitizeCreationOptions as ge,sanitizeCreationResponse as me,sanitizeRequestOptions as ve,sanitizeAssertionResponse as be}from"@corbado/observe";var ye={log:()=>{}};function F(e){return e?{log:(...t)=>{try{let n=e.log(...t);if(n&&(typeof n=="object"||typeof n=="function"))try{Promise.resolve(n).catch(()=>{})}catch{}}catch{}}}:ye}var oe=Symbol.for("corbado.autocapture.installed");function _(e){try{return typeof e=="function"&&Object.prototype.hasOwnProperty.call(e,oe)}catch{return!1}}function K(e,t){var a,i;let n=t;try{Object.defineProperty(e,oe,{value:t,configurable:!0})}catch{}try{Object.defineProperty(e,"name",{value:(a=n.name)!=null?a:"",configurable:!0})}catch{}try{Object.defineProperty(e,"length",{value:(i=n.length)!=null?i:0,configurable:!0})}catch{}return e}function N(){return{mode:"unavailable",disconnect:()=>{}}}function ee(e,t){return!!e&&"value"in e&&"value"in t&&e.value===t.value&&e.writable===t.writable&&e.enumerable===t.enumerable&&e.configurable===t.configurable}function $(e,t,n,a,i,y=String(t)){try{let f=Object.getOwnPropertyDescriptor(e,t);ee(f,{...a,value:n})&&Object.defineProperty(e,t,a)}catch(f){i.log(`${y} restoration skipped`,f)}}function z(e,t,n){let a=F(e);return i=>{try{let y=n(i);if(y&&(typeof y=="object"||typeof y=="function"))try{Promise.resolve(y).catch(f=>a.log(`${t} listener failed`,f))}catch(f){a.log(`${t} listener failed`,f)}}catch(y){a.log(`${t} listener failed`,y)}}}var ie=e=>({get:e("get"),create:e("create")});function we(e){let t=e.onEvent;if(typeof t!="function")throw new TypeError("captureWebAuthn requires an onEvent callback");let n=F(e.logger),a=c=>(n.log(`webauthn capture unavailable: ${c}`),{...N(),surface:"none"}),i=typeof navigator=="undefined"?void 0:navigator,y=i==null?void 0:i.credentials;if(!i||!y)return a("navigator.credentials missing");let f=y,A=ie(c=>f[c]);if(typeof A.get!="function"||typeof A.create!="function")return a("credentials methods missing");if(_(A.get)||_(A.create))return a("an equivalent capture is already active");let s=!1,B=0,O=z(n,"webauthn",t),k=(c,h,b)=>{let T={invoke(...d){let g=d[0];if(!s||b!=null&&b()||!te(g)||!te(g.publicKey))return h(this,d);let l=g.publicKey,u=`wa-${++B}`,q=h(this,d),x=te(g.signal)?g.signal:void 0,r=Re(c,g,l),p=m=>{s&&O({...r,ceremonyId:u,...m()})},w=()=>(x==null?void 0:x.aborted)===!0?{aborted:!0}:{};return p(()=>({phase:"started",userActivation:qe(i),...r.kind==="authentication"?{requestOptionsJson:ve(l)}:{creationOptionsJson:ge(l)}})),Promise.resolve(q).then(m=>(p(()=>({phase:"completed",credentialJson:c==="create"?me(m):be(m),...w()})),m),m=>{throw p(()=>({phase:"failed",error:m,errorName:Oe(m),...w()})),m})}}.invoke;return K(T,{name:c,length:0})},D=c=>{var T;let h=k(c,(d,g)=>Reflect.apply(A[c],d,g)),b=Object.getOwnPropertyDescriptor(y,c);if(b&&(!("value"in b)||b.writable!==!0))return null;try{f[c]=h}catch{return null}if(((T=Object.getOwnPropertyDescriptor(y,c))==null?void 0:T.value)!==h){try{f[c]=A[c]}catch{}return null}return()=>{f[c]===h&&(b?f[c]=b.value:delete f[c])}},L=()=>{let c=ie(()=>new WeakMap),h=(l,u)=>{let q=c[l].get(u);if(q)return q;let x=k(l,(r,p)=>Reflect.apply(u,y,p),()=>{try{let r=f[l];return r!==u&&r!==x}catch(r){return n.log("suppress check failed; ceremony unreported",r),!0}});return c[l].set(u,x),x},b=l=>{let u=Object.getOwnPropertyDescriptor(y,l);return u?u.configurable===!0||!("value"in u)||u.writable===!0:!0},T=new WeakMap,d=new Proxy(y,{get(l,u){let q=Reflect.get(y,u,y);if((u==="get"||u==="create")&&b(u))return typeof q!="function"||_(q)?q:h(u,q);if(typeof q!="function"||!b(u)||u==="constructor")return q;let x=T.get(q);if(x)return x;let r=q.bind(y);return T.set(q,r),r},set(l,u,q){return Reflect.set(y,u,q,y)}}),g=Object.getOwnPropertyDescriptor(i,"credentials");if(g&&g.configurable!==!0)return null;try{Object.defineProperty(i,"credentials",{value:d,writable:!0,enumerable:!0,configurable:!0})}catch{return null}return i.credentials!==d?null:()=>{i.credentials===d&&(g?Object.defineProperty(i,"credentials",g):delete i.credentials)}},S=(c,h)=>(s=!0,{mode:"standard",surface:c,disconnect:()=>{s=!1,h()}}),I=D("get"),j=I?D("create"):null;if(I&&j)return S("methods",()=>{I(),j()});if(I==null||I(),e.attach==="container"){let c=L();if(c)return n.log("webauthn capture attached at the credentials container"),S("container",c)}return a("credentials methods cannot be patched safely")}function Re(e,t,n){let a=Ce(t.mediation);if(e==="create")return{kind:"registration",mediation:a};let i=n;return{kind:"authentication",mediation:a,uiMode:Ee(t.uiMode),credentialSet:Array.isArray(i.allowCredentials)&&i.allowCredentials.length>0?"allowlisted":"discoverable"}}function Ce(e){return e===void 0?"optional":e==="silent"||e==="optional"||e==="conditional"||e==="required"?e:"unknown"}function Ee(e){return e===void 0?"default":e==="immediate"?"immediate":"unknown"}function qe(e){let t=e.userActivation;return typeof(t==null?void 0:t.isActive)=="boolean"?t.isActive:void 0}function te(e){return e!==null&&(typeof e=="object"||typeof e=="function")}function Oe(e){return e instanceof DOMException?e.name:"UnknownError"}var ae=0;function se(){return ae+=1,`network-${ae}`}function xe(e,t){let n=e.responseType;if(n===""||n==="text")return t(e.responseText);if(n==="json"){let a=e.response;return a==null?void 0:t(a)}}var Ae=500,ue=Symbol("body-read-timeout");function de(e){return/event-stream|octet-stream/i.test(e)?!1:/json|text|urlencoded/i.test(e)}async function ce(e,t){let n=e.body;if(!n)return;let a=n.getReader(),i;try{let y=new Promise(s=>{i=setTimeout(()=>s(ue),Ae)}),f=new TextDecoder,A=[];for(;;){let s=await Promise.race([a.read(),y]);if(s===ue){t.log("body omitted: read timed out"),a.cancel().catch(()=>{});return}if(s.done)break;A.push(f.decode(s.value,{stream:!0}))}return A.push(f.decode()),A.join("")}catch{a.cancel().catch(()=>{});return}finally{i!==void 0&&clearTimeout(i)}}function ne(e){var t;(t=e==null?void 0:e.body)==null||t.cancel().catch(()=>{})}function ke(e){var h,b,T;let{onExchange:t,onRequest:n,match:a}=e;if(typeof t!="function"||typeof a!="function")throw new TypeError("captureNetwork requires onExchange and match callbacks");let i=F(e.logger),y=(h=e.transports)!=null?h:["xhr","fetch"],f=(b=e.bodyCapture)==null?void 0:b.request,A=(T=e.bodyCapture)==null?void 0:T.response,s=typeof f=="function",B=typeof A=="function",O=!1,k=z(i,"network",d=>{if(O)return t(d)}),D=z(i,"network request",d=>{if(O)return n==null?void 0:n(d)}),L=(d,g,l)=>{if(typeof l=="function")try{return l(d,g)}catch(u){i.log("body projection failed",u);return}},S=(d,g)=>{try{let l=typeof document!="undefined"?document.baseURI:void 0,u=new URL(String(d),l);return a(u,g)===!0?{url:u.href,path:u.pathname}:void 0}catch{return}},I=()=>{if(typeof XMLHttpRequest=="undefined")return i.log("xhr capture unavailable: XMLHttpRequest missing"),null;let d=XMLHttpRequest.prototype,g=Object.getOwnPropertyDescriptor(d,"open"),l=Object.getOwnPropertyDescriptor(d,"send");if(!g||!("value"in g)||typeof g.value!="function"||!l||!("value"in l)||typeof l.value!="function")return i.log("xhr capture unavailable: XMLHttpRequest methods missing"),null;let u=g.value,q=l.value;if(_(u)||_(q))return i.log("xhr capture unavailable: an equivalent capture is already active"),null;let x=new WeakMap,r=new Set,p=!1,w={open(...R){var C;let o=Reflect.apply(u,this,R);if(!O||!p)return o;try{let M=x.get(this);M&&(M.reported=!0,(C=M.cleanupListeners)==null||C.call(M));let H=String(R[0]).toUpperCase(),P=S(R[1],H);P?x.set(this,{method:H,url:P.url,path:P.path,reported:!1}):x.delete(this)}catch(M){i.log("xhr open observation failed",M)}return o}}.open,m={send(...R){let o=O&&p?x.get(this):void 0;if(!o||o.reported||o.cleanupListeners)return Reflect.apply(q,this,R);let C=()=>{},M=!1;try{o.requestId=se();let P={direction:"request",transport:"xhr",method:o.method,url:o.url,path:o.path};o.requestBody=s&&typeof R[0]=="string"?L(R[0],P,f):void 0;let J=()=>{o.outcome===void 0&&(o.outcome="abort")},G=()=>{o.outcome===void 0&&(o.outcome="timeout")},v=()=>{o.outcome===void 0&&(o.outcome="error")},E=()=>{var X;C();try{if(!O||!p||o.reported||!o.requestId)return;o.reported=!0;let W={direction:"response",transport:"xhr",method:o.method,url:o.url,path:o.path},Z=this.status,re={requestId:o.requestId,transport:"xhr",method:o.method,url:o.url,path:o.path,status:Z,ok:Z>=200&&Z<300,outcome:(X=o.outcome)!=null?X:"load",durationMs:o.startedAt!==void 0?Date.now()-o.startedAt:void 0,responseUrl:this.responseURL||void 0,requestBody:o.requestBody,responseBody:B?xe(this,he=>L(he,W,A)):void 0};o.requestEmitted?k(re):o.pendingExchange=re}catch(W){i.log("xhr exchange observation failed",W)}finally{x.get(this)===o&&x.delete(this)}},V=()=>{try{this.readyState===XMLHttpRequest.DONE&&this.status!==0&&E()}catch(X){i.log("xhr ready-state observation failed",X)}},U=()=>E();C=()=>{for(let[X,W]of[["readystatechange",V],["abort",J],["timeout",G],["error",v],["loadend",U]])this.removeEventListener(X,W);o.cleanupListeners===C&&(o.cleanupListeners=void 0),r.delete(C)},this.addEventListener("readystatechange",V),this.addEventListener("abort",J),this.addEventListener("timeout",G),this.addEventListener("error",v),this.addEventListener("loadend",U),o.cleanupListeners=C,r.add(C),o.startedAt=Date.now(),M=!0}catch(P){i.log("xhr send observation failed",P),C()}let H;try{H=Reflect.apply(q,this,R)}catch(P){throw C(),P}if(M&&o.requestId!==void 0&&o.startedAt!==void 0){o.requestEmitted=!0,D({requestId:o.requestId,transport:"xhr",method:o.method,url:o.url,path:o.path,startedAt:o.startedAt,requestBody:o.requestBody});let P=o.pendingExchange;o.pendingExchange=void 0,P&&k(P)}return H}}.send;return K(w,u),K(m,q),g.writable!==!0||l.writable!==!0?(i.log("xhr capture unavailable: XMLHttpRequest methods are not writable"),null):(Object.defineProperty(d,"open",{...g,value:w}),Object.defineProperty(d,"send",{...l,value:m}),p=!0,()=>{p=!1;for(let R of[...r])R();$(d,"open",w,g,i),$(d,"send",m,l,i)})},j=()=>{let d=globalThis,g=Object.getOwnPropertyDescriptor(d,"fetch");if(!g||!("value"in g))return i.log("fetch capture unavailable: fetch is not an own data property"),null;let l=g.value;if(typeof l!="function")return i.log("fetch capture unavailable: fetch missing"),null;if(_(l))return i.log("fetch capture unavailable: an equivalent capture is already active"),null;let u=!1,q=async(r,p,w,m)=>{try{if(!O||!u){ne(w);return}let[R,o]=await Promise.all([m!=null?m:Promise.resolve(void 0),w?ce(w,i):Promise.resolve(void 0)]);if(!O||!u)return;let C={direction:"request",transport:"fetch",method:r.method,url:r.url,path:r.path},M={...C,direction:"response"},H=r.requestBody;H===void 0&&R!==void 0&&(H=L(R,C,f));let P=o!==void 0?L(o,M,A):void 0;k({requestId:r.requestId,transport:"fetch",method:r.method,url:r.url,path:r.path,status:p.status,ok:p.ok,outcome:"load",durationMs:Date.now()-r.startedAt,responseUrl:p.url||void 0,requestBody:H,responseBody:P})}catch(R){i.log("fetch exchange observation failed",R)}},x={fetch(...r){var H,P,J,G;let p;try{let v=r[0],E=r[1];if(O&&u&&s&&typeof Request!="undefined"&&v instanceof Request&&(E==null?void 0:E.body)===void 0&&v.body){let V=String((H=E==null?void 0:E.method)!=null?H:v.method).toUpperCase(),U=(P=v.headers.get("content-type"))!=null?P:"";S(v.url,V)&&de(U)&&(p=v.clone())}}catch(v){i.log("fetch observation failed",v)}let w,m=Date.now();try{w=Reflect.apply(l,this,r)}catch(v){throw ne(p),v}let R,o;try{if(O&&u){let v=r[0],E=r[1],V=typeof Request!="undefined"&&v instanceof Request,U=String((J=E==null?void 0:E.method)!=null?J:V?v.method:"GET").toUpperCase(),X=V?v.url:v,W=S(X,U);W&&(R={requestId:se(),method:U,url:W.url,path:W.path,startedAt:m},o=(G=E==null?void 0:E.signal)!=null?G:V?v.signal:void 0,s&&typeof(E==null?void 0:E.body)=="string"&&(R.requestBody=L(E.body,{direction:"request",transport:"fetch",method:U,url:W.url,path:W.path},f)))}}catch(v){i.log("fetch observation failed",v)}if(!R)return ne(p),w;let C=R;D({requestId:C.requestId,transport:"fetch",method:C.method,url:C.url,path:C.path,startedAt:C.startedAt,requestBody:C.requestBody});let M=p?ce(p,i):void 0;return w.then(v=>{var V;let E;try{if(O&&u&&B){let U=(V=v.headers.get("content-type"))!=null?V:"";de(U)&&v.body&&(E=v.clone())}}catch{}q(C,v,E,M)},v=>{try{if(!O||!u)return;let E=(o==null?void 0:o.aborted)===!0||(v==null?void 0:v.name)==="AbortError"||typeof DOMException!="undefined"&&v instanceof DOMException&&v.code===DOMException.ABORT_ERR;k({requestId:C.requestId,transport:"fetch",method:C.method,url:C.url,path:C.path,status:0,ok:!1,outcome:E?"abort":"error",durationMs:Date.now()-C.startedAt})}catch(E){i.log("fetch failure observation failed",E)}}),w}}.fetch;return K(x,l),g.writable!==!0?(i.log("fetch capture unavailable: fetch is not writable"),null):(Object.defineProperty(d,"fetch",{...g,value:x}),u=!0,()=>{u=!1,$(d,"fetch",x,g,i)})},c=[];if(y.includes("xhr")){let d=I();d&&c.push(d)}if(y.includes("fetch")){let d=j();d&&c.push(d)}return c.length===0?N():(O=!0,{mode:"standard",disconnect:()=>{O=!1;for(let d of c.splice(0))d()}})}function Ie(e){let t=e.onNavigate;if(typeof t!="function")throw new TypeError("captureNavigation requires an onNavigate callback");let n=F(e.logger),a,i,y,f,A,s;try{if(a=window,i=a==null?void 0:a.history,!a||!i)return n.log("navigation capture unavailable: window/history missing"),N();if(A=le(i,"pushState"),s=le(i,"replaceState"),!A||!s)return n.log("navigation capture unavailable: history method descriptors missing"),N();if(y=A.descriptor.value,f=s.descriptor.value,typeof y!="function"||typeof f!="function")return n.log("navigation capture unavailable: history methods missing"),N();if(typeof a.addEventListener!="function"||typeof a.removeEventListener!="function")return n.log("navigation capture unavailable: window event methods missing"),N()}catch(h){return n.log("navigation capture unavailable: history inspection failed",h),N()}if(_(y)||_(f))return n.log("navigation capture unavailable: an equivalent capture is already active"),N();let B=!1,O=()=>({path:a.location.pathname,search:a.location.search,hash:a.location.hash}),k;try{k=O()}catch(h){return n.log("navigation capture unavailable: location inspection failed",h),N()}let D=z(n,"navigation",h=>{if(B)return t(h)}),L=h=>{if(B)try{let b=O();if(b.path===k.path&&b.search===k.search&&b.hash===k.hash)return;k=b,D({...b,source:h})}catch(b){n.log("navigation observation failed",b)}},S={pushState(...h){let b=Reflect.apply(y,this,h);return L("push"),b}}.pushState,I={replaceState(...h){let b=Reflect.apply(f,this,h);return L("replace"),b}}.replaceState;K(S,y),K(I,f);let j=()=>L("pop"),c=()=>L("hash");try{if(pe(A,S),pe(s,I),i.pushState!==S||i.replaceState!==I)throw new Error("history method replacement did not take effect");a.addEventListener("popstate",j),a.addEventListener("hashchange",c),B=!0}catch(h){return B=!1,Q(a,"popstate",j,n),Q(a,"hashchange",c,n),Y(s,I,n),Y(A,S,n),n.log("navigation capture unavailable: history methods are not writable",h),t=()=>{},D=()=>{},n=F(),N()}return{mode:"standard",disconnect:()=>{B=!1,t=()=>{},Q(a,"popstate",j,n),Q(a,"hashchange",c,n),Y(A,S,n),Y(s,I,n),D=()=>{},n=F()}}}function le(e,t){let n=e;for(;n;){let a=Object.getOwnPropertyDescriptor(n,t);if(a)return!("value"in a)||typeof a.value!="function"?null:{owner:n,key:t,descriptor:a};n=Object.getPrototypeOf(n)}return null}function pe(e,t){if(e.descriptor.writable!==!0)throw new TypeError(`${e.key} is not writable`);let n=Object.getOwnPropertyDescriptor(e.owner,e.key);if(!ee(n,e.descriptor))throw new Error(`${e.key} changed during installation`);Object.defineProperty(e.owner,e.key,{...e.descriptor,value:t})}function Y(e,t,n){$(e.owner,e.key,t,e.descriptor,n,`navigation ${e.key}`)}function Q(e,t,n,a){try{e.removeEventListener(t,n)}catch(i){a.log(`navigation ${t} listener removal skipped`,i)}}function Pe(e){let t=e.composedPath();return t.length>0?t:e.target?[e.target]:[]}var Se="0.8.0";var Te=["valueMissing","typeMismatch","patternMismatch","tooShort","tooLong","rangeUnderflow","rangeOverflow","stepMismatch","badInput","customError"];function fe(e){return Te.find(t=>e.validity[t])}function Le(e){if(!(e!=null&&e.isConnected)||!e.getClientRects().length)return!1;let t=e.ownerDocument.defaultView;if(!t)return!1;for(let n=e;n;n=n.parentElement){let a=t.getComputedStyle(n);if(n.hasAttribute("hidden")||a.display==="none"||a.visibility==="hidden"||a.visibility==="collapse"||a.opacity==="0")return!1}return!0}function Be(e){var q,x;if(typeof e.readValidation!="function"||typeof e.onError!="function")throw new TypeError("captureInputValidation requires readValidation and onError callbacks");let{form:t}=e,n=[...e.fields],a=(q=e.maxObservationMs)!=null?q:1e4;if(!n.length||!Number.isFinite(a)||a<=0)throw new TypeError("captureInputValidation requires fields and a positive maxObservationMs");let i={mode:"unavailable",disconnect(){},beginAttempt:()=>{},requestStarted(){},refresh(){}},y=(x=t==null?void 0:t.ownerDocument)==null?void 0:x.defaultView;if(!y||!n.every(r=>r.form===t))return i;let f=!0,A=0,s,B=!1,O,k,D,L,S=[],I=()=>t.isConnected&&n.every(r=>r.isConnected&&r.form===t),j=()=>{try{let r=e.readValidation();if(r&&["clear","pending","unknown"].includes(r.status)||(r==null?void 0:r.status)==="invalid"&&typeof r.code=="string"&&["constraint","application"].includes(r.source))return r}catch{}return{status:"unknown"}},c=r=>r.status==="invalid"?JSON.stringify([r.code,r.fieldIndex]):void 0,h=()=>{s=void 0,clearTimeout(k),clearTimeout(D),k=D=void 0},b=()=>{k=void 0;let r=s;if(!f||!(r!=null&&r.confirmed))return;if(!I()){h();return}let p=r.nativeInvalid?(()=>{for(let[m,R]of n.entries()){let o=fe(R);if(o)return{status:"invalid",source:"constraint",code:o,fieldIndex:m}}return{status:"clear"}})():j();if(p.status==="clear"){r.serverBaseline=void 0;return}if(p.status!=="invalid"||p.source==="application"&&r.serverBaseline===c(p))return;let w={attemptId:r.id,startedAt:r.startedAt,timestamp:Date.now(),code:p.code,...p.fieldIndex===void 0?{}:{fieldIndex:p.fieldIndex}};h(),B=!1;try{Promise.resolve(e.onError(w)).catch(()=>{})}catch{}},T=()=>{!f||!s||k!==void 0||(k=setTimeout(b,0))},d=r=>{if(!f||!I())return;h();let p=B?c(j()):void 0;return s={id:++A,startedAt:Date.now(),confirmed:r,nativeInvalid:!1,serverBaseline:p},D=setTimeout(h,a),T(),s.id},g=()=>{O===void 0&&(O=d(!1),L=setTimeout(()=>{s&&s.id===O&&!s.confirmed&&h(),O=void 0},0))},l=(r,p,w)=>{r.addEventListener(p,w,!0),S.push(()=>r.removeEventListener(p,w,!0))},u={mode:"standard",beginAttempt:()=>d(!0),refresh:T,requestStarted(r={}){f&&(r.attemptId!==void 0&&r.attemptId!==(s==null?void 0:s.id)||s&&r.timestamp!==void 0&&r.timestamp<s.startedAt||(h(),B=!0))},disconnect(){if(f){f=!1,h(),clearTimeout(L);for(let r of S.splice(0))r()}}};try{let r=w=>{var o;let m=w.target,R=(o=m==null?void 0:m.closest)==null?void 0:o.call(m,"button,input");(R==null?void 0:R.form)===t&&!R.disabled&&["submit","image"].includes(R.type)&&g()};l(t.ownerDocument,"click",r),l(t,"click",r),l(t,"keydown",w=>{let m=w;m.key==="Enter"&&!m.isComposing&&!m.defaultPrevented&&n.includes(m.target)&&g()}),l(t,"submit",()=>{(s==null?void 0:s.id)===O&&s?(s.confirmed=!0,T()):d(!0),O=void 0}),l(t,"invalid",w=>{!s||!n.includes(w.target)||(s.confirmed=!0,s.nativeInvalid=!0,T())}),l(t,"input",w=>{n.includes(w.target)&&h()});let p=new y.MutationObserver(T);p.observe(t,{subtree:!0,childList:!0,attributes:!0,characterData:!0}),S.push(()=>p.disconnect())}catch{return u.disconnect(),i}return u}import{sanitizeCreationOptions as et,sanitizeCreationResponse as tt,sanitizeRequestOptions as nt,sanitizeAssertionResponse as rt}from"@corbado/observe";export{Se as VERSION,Be as captureInputValidation,Ie as captureNavigation,ke as captureNetwork,we as captureWebAuthn,Pe as composedPath,fe as inputValidationCode,Le as isValidationMessageVisible,rt as sanitizeAssertionResponse,et as sanitizeCreationOptions,tt as sanitizeCreationResponse,nt as sanitizeRequestOptions};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@corbado/autocapture",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.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",
|
|
@@ -14,19 +14,24 @@
|
|
|
14
14
|
"lint": "tsc --noEmit",
|
|
15
15
|
"test": "vitest run",
|
|
16
16
|
"test:watch": "vitest",
|
|
17
|
-
"test:e2e": "pnpm build && playwright test --config e2e/playwright.config.ts",
|
|
17
|
+
"test:e2e": "pnpm --filter @corbado/autocapture... build && playwright test --config e2e/playwright.config.ts",
|
|
18
18
|
"check:dist": "es-check es2019 './dist/index.js' && es-check es2019 './dist/index.mjs' --module",
|
|
19
19
|
"format": "prettier --write 'src/**/*.ts' 'e2e/**/*.ts'",
|
|
20
20
|
"format:check": "prettier --check 'src/**/*.ts' 'e2e/**/*.ts'"
|
|
21
21
|
},
|
|
22
22
|
"devDependencies": {
|
|
23
|
+
"@corbado/observe": "workspace:*",
|
|
23
24
|
"@playwright/test": "^1.57.0",
|
|
24
25
|
"@types/node": "^20",
|
|
25
26
|
"es-check": "9.6.4",
|
|
27
|
+
"esbuild": "^0.27.0",
|
|
26
28
|
"jsdom": "29.1.1",
|
|
27
29
|
"prettier": "^3.7.4",
|
|
28
30
|
"tsup": "8.5.1",
|
|
29
31
|
"typescript": "6.0.3",
|
|
30
32
|
"vitest": "^4.1.0"
|
|
33
|
+
},
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"@corbado/observe": "^0.16.0"
|
|
31
36
|
}
|
|
32
37
|
}
|