@keploy/capture-sdk 3.0.1

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.
@@ -0,0 +1,90 @@
1
+ import type { NetworkEventCallback, PrivacyConfig } from "./types";
2
+ /**
3
+ * Cut a recorded body at `maxBodySize`.
4
+ *
5
+ * ONE RULE IN ONE PLACE. The cap was written out at six call sites and
6
+ * missed the seventh: an XHR FormData body was assembled and recorded
7
+ * WHOLE, however large. An upload form with a base64 field put
8
+ * megabytes into one event — past the queue's byte accounting, and far
9
+ * past the 64 KiB the page-unload flush can carry, so it held back
10
+ * everything behind it there too.
11
+ *
12
+ * THE CAP COUNTS UTF-16 CODE UNITS, not bytes: the unit a JS string is
13
+ * measured in, equal to bytes for ASCII and up to 2x under it for
14
+ * multi-byte text. `maxBodySize` is a bound on what is RECORDED, not an
15
+ * exact byte budget, and counting bytes would mean a TextEncoder pass
16
+ * over every body the page sends. The option's docs say so.
17
+ */
18
+ declare function truncate(text: string, maxSize: number): string;
19
+ /**
20
+ * The body an XHR was sent with, as it is recorded.
21
+ *
22
+ * Exported through `__internals` because the only other way to reach it
23
+ * is a real XMLHttpRequest against a real server, and the rules under
24
+ * test — that every shape faces the cap, and that a shape the SDK does
25
+ * not read is named with its kind and its size — are about this
26
+ * function.
27
+ *
28
+ * EVERY SHAPE, NOT ONE. This returned `[Binary/Document body]` for a
29
+ * Blob, an ArrayBuffer, a view and a Document alike: no kind, no size,
30
+ * and a string the npm page never listed among the notes it promised.
31
+ * `xhr.send(blob)` with a 2 MB Blob therefore recorded strictly less
32
+ * than `fetch` recorded for the same Blob, which answered `[Blob: N
33
+ * bytes, truncated]`.
34
+ *
35
+ * A BLOB IS NAMED, NOT READ, and that is the one place this path
36
+ * cannot match fetch's: Blob.text() is async and the body must be
37
+ * serialised inside send(), before the request goes out.
38
+ */
39
+ declare function serializeXhrBody(body: Document | XMLHttpRequestBodyInit | null | undefined, maxSize: number): string | null;
40
+ /**
41
+ * The URL the RECORDING carries: the WHATWG serialization of what the
42
+ * app passed, resolved against the document.
43
+ *
44
+ * `spec/canonical-key.v1.json` computes the key over the serialized
45
+ * absolute URL at both ends. Replay keys Playwright's `request.url()`,
46
+ * which is that form; the recorder has to supply the same form or the
47
+ * stored key and the live key disagree on exactly the inputs a browser
48
+ * rewrites before sending -- a default port (`:443` is gone on the
49
+ * wire), a protocol-relative `//host` (the browser fills in the page's
50
+ * scheme), non-ASCII (percent-encoded), `..` (resolved). `fetch` was
51
+ * already covered because `new Request(input).url` IS this
52
+ * serialization; `XMLHttpRequest.open` recorded the raw string, so an
53
+ * app that opened `/api/jobs/42` recorded a key nothing at replay could
54
+ * match. Both paths go through here now.
55
+ *
56
+ * `document.baseURI` is the base a browser resolves against, `<base
57
+ * href>` included. Outside a document (a worker) `location.href` is the
58
+ * base. The raw string is returned only when neither exists AND the
59
+ * value is already absolute -- the one case where there is nothing to
60
+ * resolve against and nothing to resolve.
61
+ */
62
+ export declare function recordedUrl(raw: string): string;
63
+ export declare class NetworkInterceptor {
64
+ private callback;
65
+ private privacyEngine;
66
+ private maxBodySize;
67
+ /** Absolute URLs never observed — the SDK's own ingest endpoint. */
68
+ private ignored;
69
+ private active;
70
+ private originalFetch;
71
+ private originalXhrOpen;
72
+ private originalXhrSend;
73
+ private originalXhrSetHeader;
74
+ constructor(privacyConfig?: Partial<PrivacyConfig>, maxBodySize?: number, ignoreUrls?: string[]);
75
+ /** True for a request the interceptor must pass through untouched. */
76
+ private ignores;
77
+ start(callback: NetworkEventCallback): void;
78
+ stop(): void;
79
+ private patchFetch;
80
+ private restoreFetch;
81
+ private patchXHR;
82
+ private restoreXHR;
83
+ private emit;
84
+ }
85
+ /** Exposed for tests: the cut and the XHR body shape, without an XHR. */
86
+ export declare const __internals: {
87
+ truncate: typeof truncate;
88
+ serializeXhrBody: typeof serializeXhrBody;
89
+ };
90
+ export {};
@@ -0,0 +1,36 @@
1
+ import type { NetworkEvent, PrivacyConfig } from "./types";
2
+ export declare function defaultPrivacyConfig(): PrivacyConfig;
3
+ export declare class PrivacyEngine {
4
+ private config;
5
+ private builtinPatterns;
6
+ /** The integrator's piiPatterns, compiled global once. */
7
+ private userPatterns;
8
+ constructor(config?: Partial<PrivacyConfig>);
9
+ /**
10
+ * Replace every occurrence of known PII patterns in `text` with
11
+ * `[REDACTED]`. Returns the scrubbed string.
12
+ */
13
+ maskText(text: string): string;
14
+ /**
15
+ * Redact a URL without disturbing the parts that carry request identity.
16
+ *
17
+ * The path is left exactly as captured — it is what the canonical key is
18
+ * computed from, and rewriting it makes the recording unreplayable.
19
+ * Query values are redacted by parameter NAME (token, password, apikey,
20
+ * ... — the set canonkey.ts excludes from the key) and by nothing else:
21
+ * no regex, built-in or user-supplied, runs over a URL. Every other
22
+ * value and every name is kept, because they are part of identity too.
23
+ * An earlier version of this method scanned every value (the inline
24
+ * comment below records what that did to the key); this comment said
25
+ * so and outlived the fix.
26
+ */
27
+ maskUrl(rawUrl: string): string;
28
+ /**
29
+ * Returns a deep-copy of the given {@link NetworkEvent} with sensitive
30
+ * headers redacted and (optionally) bodies masked.
31
+ */
32
+ maskNetworkData(event: NetworkEvent): NetworkEvent;
33
+ getConfig(): Readonly<PrivacyConfig>;
34
+ updateConfig(partial: Partial<PrivacyConfig>): void;
35
+ private maskHeaders;
36
+ }
@@ -0,0 +1,164 @@
1
+ import type { CaptureConfig, SessionEvent, SessionMetadata } from "./types";
2
+ export type RecorderState = "idle" | "recording" | "paused" | "stopped";
3
+ /**
4
+ * Callback invoked every time a new {@link SessionEvent} is produced
5
+ * by the recorder.
6
+ */
7
+ export type OnEventCallback = (event: SessionEvent) => void;
8
+ /**
9
+ * Called when the recorder ends the session ON ITS OWN — today, when
10
+ * `maxSessionDuration` elapses. Not called for an explicit stop(): the
11
+ * caller of stop() already knows.
12
+ */
13
+ export type OnSessionEndCallback = () => void;
14
+ export declare class KeployCaptureRecorder {
15
+ private phase;
16
+ private userPaused;
17
+ private hidden;
18
+ /**
19
+ * A dom event has been dropped since the DOM gate last shut — i.e.
20
+ * the recording has a hole that only a new baseline can close.
21
+ *
22
+ * Set in emitEvent, which is the single place a dom event is
23
+ * dropped, and cleared by the baseline that closes it. Without it
24
+ * openDomGate() re-serialised the document on EVERY transition: a
25
+ * visitor who alt-tabs thirty times on a page that mutates nothing
26
+ * while hidden paid thirty FullSnapshots of a document that had not
27
+ * changed. A snapshot of a real page is large — transport.ts's own
28
+ * measurement is 236 KB for one — and any event over
29
+ * KEEPALIVE_QUOTA_BYTES (64 KiB) is sent the moment it is queued as
30
+ * a full drain, so each one is also an upload of its own.
31
+ */
32
+ private droppedWhileShut;
33
+ private sessionId;
34
+ private metadata;
35
+ private config;
36
+ private onEvent;
37
+ private onSessionEnd;
38
+ private rrwebStopFn;
39
+ /** rrweb's record(), once its import has landed. Held for takeFullSnapshot. */
40
+ private rrwebRecord;
41
+ /** Set the moment rrweb's start is requested, so it is requested once. */
42
+ private rrwebRequested;
43
+ /**
44
+ * Counts start() calls. Both awaits below — start()'s on startRRWeb()
45
+ * and startRRWeb()'s on the import — resume into whatever session is
46
+ * current by then, and compare this against the value they captured
47
+ * before yielding: a continuation of a superseded session does
48
+ * nothing. See startRRWeb().
49
+ */
50
+ private generation;
51
+ private sessionTimer;
52
+ private visibilityHandler;
53
+ constructor(config: CaptureConfig);
54
+ start(onEvent: OnEventCallback, onSessionEnd?: OnSessionEndCallback | null): Promise<string>;
55
+ stop(): void;
56
+ /** Close the gate until resume(). A visibility change cannot reopen it. */
57
+ pause(): void;
58
+ /**
59
+ * Reopen the manual pause. A hidden tab still keeps the gate shut.
60
+ *
61
+ * And start rrweb if it has been waiting for this — the same way the
62
+ * visibilitychange that shows the tab does. A pause() before rrweb's
63
+ * import landed (init() and pause() in one tick behind a consent
64
+ * gate) meant the import resolved into a shut gate; the decision
65
+ * there read `hidden` alone, so record() went ahead, Meta and
66
+ * FullSnapshot were dropped, and with nothing here to start it
67
+ * again, the session stayed snapshotless for good.
68
+ */
69
+ resume(): void;
70
+ /**
71
+ * The DOM gate has just reopened: give the recording a baseline.
72
+ *
73
+ * rrweb HAS NO PAUSE, so while the gate was shut it went on observing
74
+ * and emitEvent dropped what it emitted. Every incremental event
75
+ * rrweb produces names its nodes by the ids of the last FullSnapshot
76
+ * — an `add` introduces an id and the `attributes`, `texts` and
77
+ * `removes` after it refer to it — so the events from here on refer
78
+ * to nodes the recording never showed. The flow engine resolves those
79
+ * ids against the node map it builds from the snapshot
80
+ * (flow-engine/src/extractor.ts) and selectorFromNode answers `body`
81
+ * for an id it cannot find: a click on a button added while the tab
82
+ * was hidden becomes a click on `body` in the generated test, and it
83
+ * passes. Nothing anywhere said the recording had a hole.
84
+ *
85
+ * So a reopened gate re-serialises the document and re-numbers
86
+ * rrweb's mirror. Two ways in, and exactly one of them fires:
87
+ *
88
+ * - rrweb has not started (hidden or paused since init, where
89
+ * starting it would have emitted Meta and FullSnapshot into the
90
+ * shut gate). Start it now; the snapshot record() takes inside
91
+ * that call IS the baseline.
92
+ * - rrweb is running. takeFullSnapshot(), which also throws before
93
+ * record() has run — inside a visibilitychange handler that would
94
+ * be an exception in the integrator's document.
95
+ */
96
+ private openDomGate;
97
+ /**
98
+ * The id of the session that is LIVE, or null when none is.
99
+ *
100
+ * Null once the session has ended, including when the
101
+ * maxSessionDuration timer ended it — this used to keep answering
102
+ * with the id of a session its own timer had stopped, so an
103
+ * integrator tagging their logs with it went on tagging them with a
104
+ * session that had finished ten minutes earlier. A pause does not
105
+ * end a session, so this keeps answering through one.
106
+ */
107
+ getSessionId(): string | null;
108
+ /**
109
+ * The SESSION gate: a live session the integrator has not paused.
110
+ *
111
+ * Deliberately not derived from getState(), which is the narrower DOM
112
+ * gate and answers "paused" for a hidden tab.
113
+ */
114
+ private get sessionOpen();
115
+ /**
116
+ * The DOM gate, as a public state.
117
+ *
118
+ * "recording" means rrweb may run and its events are emitted; a
119
+ * hidden tab reads "paused" here while the session itself is still
120
+ * open and still recording the exchanges the page makes. This is the
121
+ * meaning the state has always had — every caller of it decides
122
+ * something about rrweb — and it is the only one it can have while
123
+ * one enum stands for two independent gates.
124
+ */
125
+ getState(): RecorderState;
126
+ getMetadata(): SessionMetadata | null;
127
+ private startRRWeb;
128
+ /**
129
+ * Everything the SDK's privacy configuration means to rrweb.
130
+ *
131
+ * NO `maskAllInputs`. MEASURED in rrweb 2.0.0-alpha.20's record()
132
+ * (rrweb.js:13778-13795): `maskAllInputs: true` DISCARDS the
133
+ * maskInputOptions object it was handed and substitutes a fixed map
134
+ * of 16 input types, and neither `hidden` nor `file` is among them —
135
+ * so the SDK's own map was dead in balanced and strict, and a CSRF
136
+ * token, a session id or an internal record id in `<input
137
+ * type="hidden">` was serialised in the clear in every mode.
138
+ * Leaving `maskAllInputs` unset makes rrweb use the map below
139
+ * verbatim (the `_maskInputOptions !== void 0` branch of the same
140
+ * expression), which is the only way to name a type rrweb's fixed
141
+ * map omits.
142
+ *
143
+ * The map is the ONLY statement of what each mode masks. Three
144
+ * things are held to it and none of them keeps a second copy:
145
+ * dom-masking.test.ts drives one case per entry through real rrweb
146
+ * and asserts the serialised `value`, readme.test.ts holds the npm
147
+ * page's privacy table to it, and readme.test.ts also requires every
148
+ * input type the HTML spec has to be either in it or named in the
149
+ * page's carve-out. Before that, thirteen of its rows were untested:
150
+ * MEASURED, flipping `email`, `select`, `month`, `tel` and `number`
151
+ * to `false` left the whole SDK suite green.
152
+ */
153
+ private rrwebOptions;
154
+ /**
155
+ * Emit an event to the registered callback. This is also called
156
+ * externally by the main KeployCapture orchestrator for network
157
+ * events.
158
+ *
159
+ * THE GATES ARE HERE, so every emitter faces the same two. They used
160
+ * to sit only in rrweb's emit callback, which meant "paused" and
161
+ * "stopped" applied to DOM events and to nothing else.
162
+ */
163
+ emitEvent(type: SessionEvent["type"], data: unknown): void;
164
+ }
@@ -0,0 +1,47 @@
1
+ /** Emitted for a JSON-shaped body that cannot be parsed (usually truncated). */
2
+ export declare const TRUNCATED_UNPARSEABLE = "[UNPARSEABLE_BODY_NOT_REDACTED]";
3
+ /** True for a body that IS one of the SDK's own not-recorded notes. */
4
+ export declare function isNotRecordedNote(body: string): boolean;
5
+ declare function isSensitiveKey(key: string): boolean;
6
+ /** Luhn check — the standard checksum every real card number satisfies. */
7
+ declare function passesLuhn(digits: string): boolean;
8
+ /**
9
+ * A real card number: a known issuer prefix, a valid length for that
10
+ * issuer, AND a passing Luhn checksum.
11
+ *
12
+ * All three are required on purpose. Length alone matched timestamps;
13
+ * Luhn alone still admits ~10% of random digit runs. Together the false
14
+ * positive rate on non-card data is negligible, and — critically — a
15
+ * 13-digit millisecond timestamp has no valid issuer prefix.
16
+ */
17
+ declare function isLikelyCardNumber(digits: string): boolean;
18
+ /** Redact card-shaped runs inside a string, preserving everything else. */
19
+ declare function redactCards(s: string): string;
20
+ /**
21
+ * Apply every value-level detector to one string, then every
22
+ * caller-supplied pattern.
23
+ *
24
+ * `extra` is the integrator's `privacy.piiPatterns`, already compiled
25
+ * global (see PrivacyEngine). It rides through every scan the engine
26
+ * makes — this function is the ONLY string scanner — so a pattern
27
+ * applies to a JSON string value, a text body and a header value alike.
28
+ * It used to reach header values only, while its documentation said
29
+ * "matched text is replaced".
30
+ */
31
+ export declare function redactStringValue(value: string, extra?: readonly RegExp[]): string;
32
+ /**
33
+ * Redact a captured body.
34
+ *
35
+ * JSON in, valid JSON out — always. A body that is not JSON is treated as
36
+ * opaque text and only value-level detectors are applied, so it can never
37
+ * be turned into something that fails to parse downstream.
38
+ */
39
+ export declare function redactBody(body: string | null | undefined, contentType?: string, extra?: readonly RegExp[]): string | null;
40
+ /** Exposed for tests and diagnostics. */
41
+ export declare const __internals: {
42
+ isSensitiveKey: typeof isSensitiveKey;
43
+ isLikelyCardNumber: typeof isLikelyCardNumber;
44
+ passesLuhn: typeof passesLuhn;
45
+ redactCards: typeof redactCards;
46
+ };
47
+ export {};
@@ -0,0 +1,32 @@
1
+ /**
2
+ * THE SERVER'S RULE FOR A SESSION ID, CHECKED BEFORE A BYTE IS SENT.
3
+ *
4
+ * The ingest route refuses a session id outside this shape with a 400
5
+ * whose only diagnosis is `issues: [{path: "sessionId", ...}]`. The SDK
6
+ * mints its own ids as UUIDs, which always pass; the one integrator-
7
+ * supplied value on the wire is what `sessionIdGenerator` returns, and
8
+ * a `user:42/session 1`-style correlation id -- exactly what the option
9
+ * invites -- used to reach onError as "Invalid request" with a remedy
10
+ * blaming a version mismatch. Now the recorder refuses to start with
11
+ * it, and names the value and the rule (KUI_E_SESSION_ID_INVALID).
12
+ *
13
+ * THE RULE IS THE SERVER'S, VERBATIM: api-server
14
+ * pkg/uicapture/sdkwire.ValidSessionID and the sidecar router's
15
+ * SafeIdSchema enforce `^[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]+)*$` at 1-200
16
+ * characters. spec/session-id.v1.json is emitted from this module and
17
+ * executed against it, so a rule that loosens or tightens here without
18
+ * the server following is a red vector, not a 400 in production.
19
+ */
20
+ /** `MaxSessionIDLen` in api-server sdkwire; `.max(200)` in the sidecar's SafeIdSchema. */
21
+ export declare const SESSION_ID_MAX_LENGTH = 200;
22
+ /** Every dot-separated segment non-empty and made of [A-Za-z0-9_-]. */
23
+ export declare const SESSION_ID_PATTERN: RegExp;
24
+ /**
25
+ * The rule as one sentence: BYTE FOR BYTE the `issues[].message` the
26
+ * server sends on the 400 this check pre-empts (sdkwire.Parse), so what
27
+ * the SDK says locally is what the server would have said, and a Go
28
+ * twin can compare the two strings rather than two paraphrases.
29
+ */
30
+ export declare const SESSION_ID_RULE: string;
31
+ /** Whether the server would accept `value` as a session id (or a batch id, which has the same shape). */
32
+ export declare function isValidSessionId(value: unknown): value is string;