@keploy/capture-sdk 3.0.1 → 3.1.0-rc.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.
@@ -1,4 +1,34 @@
1
1
  import type { CaptureConfig, SessionEvent, SessionMetadata } from "./types";
2
+ import { DomRecorderRefusal } from "./errors";
3
+ /**
4
+ * What moved the page to a new URL: the `cause` of the route Meta event the
5
+ * recorder writes (rrweb's own Meta, on a load or a returning tab, has none).
6
+ * "push" and "replace": a navigation that added or replaced a history entry
7
+ * -- history.pushState or replaceState (a replace that changes the URL is a
8
+ * redirect), or, where the Navigation API reports it, one the page made
9
+ * another way. "traverse": a move through the session history -- the
10
+ * browser's Back or Forward, or the page's own history.back() or go().
11
+ * "hash": a fragment navigation the History API did not make -- a link to
12
+ * `#/orders`, `location.hash = ...` -- told only where the browser has the
13
+ * Navigation API; without it such a navigation reads as "traverse".
14
+ */
15
+ export type NavigationCause = "push" | "replace" | "traverse" | "hash";
16
+ /**
17
+ * Who asked for a traversal, where the SDK saw it asked: "script" when the
18
+ * page's own script called history.back(), forward() or go(), or the
19
+ * Navigation API's navigation.back(), forward() or traverseTo(), for it. The
20
+ * route Meta carries it as `initiator`; it is absent when that is not
21
+ * known, never guessed.
22
+ */
23
+ export type NavigationInitiator = "script";
24
+ /**
25
+ * Keep collecting the page's URL credentials while no recorder is open --
26
+ * between a continuous capture's sessions -- and return the release. A
27
+ * visitor going back to `/reset/<token>` in that gap started no session,
28
+ * the token was never collected, and the next session's snapshot carried
29
+ * it once the page had hidden it (found in review).
30
+ */
31
+ export declare function collectPageSecrets(): () => void;
2
32
  export type RecorderState = "idle" | "recording" | "paused" | "stopped";
3
33
  /**
4
34
  * Callback invoked every time a new {@link SessionEvent} is produced
@@ -11,30 +41,118 @@ export type OnEventCallback = (event: SessionEvent) => void;
11
41
  * caller of stop() already knows.
12
42
  */
13
43
  export type OnSessionEndCallback = () => void;
44
+ /**
45
+ * Called when an event is dropped because scrubbing it passed the ingest
46
+ * server's body cap (privacy.ts ScrubOverCap): its type, how many
47
+ * characters the scrubbed event was certain to reach, and the cap.
48
+ */
49
+ export type OnScrubOversizedCallback = (eventType: SessionEvent["type"], atLeast: number, cap: number) => void;
14
50
  export declare class KeployCaptureRecorder {
15
51
  private phase;
16
52
  private userPaused;
17
53
  private hidden;
54
+ private droppedWhileShut;
55
+ /**
56
+ * A DOM event was dropped while the gate was OPEN -- its scrub failed or
57
+ * passed the body cap -- so the recording has no baseline rrweb's later
58
+ * events can be read against: each names its nodes by the ids of the
59
+ * last FullSnapshot and the mutations after it. Until a FullSnapshot is
60
+ * sent again, rrweb's incremental events are held back: posted, a click
61
+ * on a button the dropped snapshot held was resolved by the flow engine
62
+ * to `body`, and a generated test clicked the page body (found in
63
+ * review #22). Not cleared by retaking one at once: a snapshot dropped
64
+ * for its size would be dropped again. The next opening of the gate
65
+ * takes it: a hold is a hole to openDomGate() whatever the gate itself
66
+ * dropped, so nothing that sets this sets droppedWhileShut beside it.
67
+ * Set beside it, that flag outlived the snapshot that ended the hold
68
+ * wherever the drop was said from INSIDE takeFullSnapshot -- the Meta
69
+ * rrweb emits first evicting an event from a full queue, or failing its
70
+ * scrub -- since the snapshot behind it clears the hold alone: the next
71
+ * reopening of the gate serialised the whole page again for nothing
72
+ * (measured refuting review #30, real rrweb and transport: two
73
+ * takeFullSnapshot calls where one is owed).
74
+ */
75
+ private baselineLost;
76
+ /** The pending retake of a FullSnapshot after a dropped DOM event; see rebaseline(). */
77
+ private retakeTimer;
78
+ /** The pending retake is the one taken AT ONCE, after a dropped incremental; see rebaseline(). */
79
+ private retakeAtOnce;
80
+ /** How long the next retake after a dropped SNAPSHOT waits; see rebaseline(). */
81
+ private retakeDelay;
82
+ /** Uploads are failing (TransportConfig.onFailing): no snapshot is taken; see failing(). */
83
+ private outage;
18
84
  /**
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.
85
+ * UPLOADS FAIL, SO NOTHING IS RE-SERIALISED UNTIL ONE IS ACCEPTED AGAIN.
86
+ * Each DOM event the transport drops in an outage is a hole, and each
87
+ * hole asked for a FullSnapshot -- at once after an incremental -- into
88
+ * a queue nothing drains, where the snapshot evicted more DOM events
89
+ * and asked for the next. MEASURED (MEASURE.md "Outage", 22.5k nodes,
90
+ * ingest down): in the 90 s after the cap, 19 long tasks over 200 ms
91
+ * (up to 373 ms) and the heap 29 -> 211 MB. Now a hole in an outage only starts the hold (baselineLost:
92
+ * rrweb's incrementals are not queued), a retake already pending is
93
+ * cancelled, and the ONE snapshot is taken when the outage ends -- an upload accepted, or
94
+ * on a page that makes only DOM events, a queue run empty, which comes
95
+ * again only once the cap has refilled: it
96
+ * is queued after everything the outage left, so the server, sorting by
97
+ * seq, has it before every incremental that follows.
98
+ */
99
+ failing(on: boolean): void;
100
+ /**
101
+ * Events the transport dropped unsent (TransportConfig.onDropped). A
102
+ * DOM event among them is a hole exactly as one the recorder drops: no
103
+ * baseline until a FullSnapshot is sent, so rrweb's incrementals are
104
+ * held, and one is retaken (rebaseline()). Unless a snapshot queued
105
+ * after it still stands (`rebaselined`): that is the baseline already. Unsaid, clicks
106
+ * after a snapshot too big to send were posted and resolved to `body`
107
+ * (found in review #23).
108
+ */
109
+ lost(events: readonly SessionEvent[], rebaselined: boolean): void;
110
+ /**
111
+ * A dropped DOM event left the recording with no baseline: take one when
112
+ * it could fit, rather than only at the next opening of the gate -- a
113
+ * visitor who never switched tab had every later click held for the rest
114
+ * of the session (found in review #23). After an incremental, at once: a
115
+ * snapshot of the page may well fit where the event did not reach the
116
+ * server (a full queue). After a SNAPSHOT, on a backoff -- RETAKE_FIRST_MS,
117
+ * doubling to RETAKE_MAX_MS -- because the page must shrink before one
118
+ * fits and each attempt serialises the whole document. Only while the
119
+ * gate is open: a shut gate's reopening takes its own (droppedWhileShut).
120
+ * The delay starts over once a snapshot is sent.
21
121
  *
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.
122
+ * ONE RETAKE IS PENDING AT A TIME, and a dropped SNAPSHOT puts its
123
+ * backoff in the place of one pending at once. rrweb emits a Meta and
124
+ * then the snapshot: with the transport's queue full, the retake's own
125
+ * Meta evicted a DOM event, which asked for a retake at once from inside
126
+ * takeFullSnapshot; the snapshot behind it was then refused by the
127
+ * scrub, found that retake pending and left it -- so the page was
128
+ * serialised again on the next turn, and the next: 3,212 times in 4 s
129
+ * where the backoff allows none (found refuting review #30). A backoff
130
+ * already pending is left as it is: put off again by every drop, it
131
+ * would never fire.
31
132
  */
32
- private droppedWhileShut;
133
+ private rebaseline;
134
+ /**
135
+ * Events the transport delivered (TransportConfig.onDelivered). A
136
+ * FullSnapshot among them is the baseline on the server: the retake's
137
+ * backoff starts over.
138
+ */
139
+ delivered(events: readonly SessionEvent[]): void;
140
+ /** Which of rrweb's text nodes are a <style>'s, so their text is scrubbed as CSS (StyleTexts). */
141
+ private readonly styles;
142
+ /** The node of each id the styles' observer follows, kept from when it started (NodePresence). */
143
+ private readonly styleNodes;
33
144
  private sessionId;
34
145
  private metadata;
35
146
  private config;
36
147
  private onEvent;
37
148
  private onSessionEnd;
149
+ private onScrubOversized;
150
+ /** Told how rrweb's import went once the network is back -- null when it landed; see startRRWeb(). */
151
+ private onRRWeb;
152
+ /** The `online` listener that retries rrweb's import; see startRRWeb(). */
153
+ private onlineRetry;
154
+ /** The timer that reads the browser's state while onlineRetry waits; see retryWhenOnline(). */
155
+ private onlinePoll;
38
156
  private rrwebStopFn;
39
157
  /** rrweb's record(), once its import has landed. Held for takeFullSnapshot. */
40
158
  private rrwebRecord;
@@ -50,9 +168,49 @@ export declare class KeployCaptureRecorder {
50
168
  private generation;
51
169
  private sessionTimer;
52
170
  private visibilityHandler;
171
+ private stopNavigation;
172
+ private lastHref;
173
+ /** location.href as the recorder last read it; see noticeUnheardMove(). */
174
+ private seenHref;
53
175
  constructor(config: CaptureConfig);
54
- start(onEvent: OnEventCallback, onSessionEnd?: OnSessionEndCallback | null): Promise<string>;
176
+ /**
177
+ * Start recording. Resolves to the session id, or "" when sampleRate
178
+ * left this visitor out. `onSessionEnd` is called when the session ends
179
+ * on its own; `startPaused` opens it paused, as pause() would;
180
+ * `onScrubOversized` when an event is dropped because scrubbing it passed
181
+ * the ingest server's body cap; `onNavigationUnwrapped` when the page made
182
+ * a History or Navigation API method the SDK wraps impossible to replace,
183
+ * with that method's name (wrapHistory).
184
+ */
185
+ start(onEvent: OnEventCallback, onSessionEnd?: OnSessionEndCallback | null, startPaused?: boolean, onScrubOversized?: OnScrubOversizedCallback | null, onRRWeb?: ((err: DomRecorderRefusal | null) => void) | null, onNavigationUnwrapped?: ((method: string) => void) | null): Promise<string>;
186
+ /**
187
+ * Stop DOM recording now, and leave the session open for what is
188
+ * already in flight (the network exchanges stop() settles): the phase
189
+ * moves to "stopping", which every gate reads as ended -- rrweb is
190
+ * not started, an import still in flight resumes into nothing, a
191
+ * hidden tab shown starts nothing, a retake due takes no snapshot, a
192
+ * same-document navigation is not recorded -- while an exchange
193
+ * already admitted still reports. Review round 3 measured the
194
+ * alternative: a tab hidden at init() and shown during stop()'s
195
+ * settle started rrweb and posted a FullSnapshot after stop(). rrweb
196
+ * is stopped here too. The visibility handler, which the phase now
197
+ * keeps from starting anything, and the navigation subscription stay
198
+ * until stop(): the URLs the page moves to are still read for their
199
+ * credentials, which the exchanges recorded in the window are
200
+ * scrubbed of. And maxSessionDuration is disarmed: the session is
201
+ * ending, and a timer that ended it inside the window dropped the
202
+ * very exchanges the window is for. stop() must follow
203
+ * (KeployCapture.stop() calls it once the settle ends); start()
204
+ * finishes a stopping session first.
205
+ */
206
+ stopDom(): void;
55
207
  stop(): void;
208
+ /** A same-document navigation, recorded as rrweb records a load: a Meta event. */
209
+ private navigated;
210
+ /** rrweb's events on their way to emitEvent, a Meta event's href recorded as the page URL. */
211
+ private recordedRRWebEvent;
212
+ /** Whether pause() closed the gate; a hidden tab does not count. */
213
+ isUserPaused(): boolean;
56
214
  /** Close the gate until resume(). A visibility change cannot reopen it. */
57
215
  pause(): void;
58
216
  /**
@@ -67,32 +225,6 @@ export declare class KeployCaptureRecorder {
67
225
  * again, the session stayed snapshotless for good.
68
226
  */
69
227
  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
228
  private openDomGate;
97
229
  /**
98
230
  * The id of the session that is LIVE, or null when none is.
@@ -124,33 +256,107 @@ export declare class KeployCaptureRecorder {
124
256
  */
125
257
  getState(): RecorderState;
126
258
  getMetadata(): SessionMetadata | null;
259
+ /** Starts rrweb when the gate allows; answers why rrweb could not be imported, else null. */
127
260
  private startRRWeb;
128
261
  /**
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.
262
+ * Asks for rrweb again when the browser is back online, for this session
263
+ * only.
142
264
  *
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.
265
+ * THE BROWSER'S STATE IS READ WHILE THIS WAITS, AS WELL AS HEARD. The
266
+ * `online` event is on window, and a page's own listener, registered
267
+ * first, can stop it before it reaches this one
268
+ * (stopImmediatePropagation). Waiting for the event alone, such a page's
269
+ * capture sat for good once started offline: rrweb never asked for, its
270
+ * transport held, nothing sent and nothing said until the visitor
271
+ * switched tab (found refuting review #30, with the real stack). So a
272
+ * timer asks navigator.onLine, which is what the event reports, and
273
+ * whichever comes first runs the retry, once, and ends the other. (The
274
+ * timer asks before it runs the retry only so that a look at a browser
275
+ * still offline changes nothing: the retry would find the same, and
276
+ * start this wait over.)
152
277
  */
278
+ private retryWhenOnline;
279
+ /** Ends the timer retryWhenOnline() started, if it is still running. */
280
+ private stopOnlinePoll;
281
+ /**
282
+ * rrweb could not be imported after start(): the capture is refused as it
283
+ * is at start, once, unless it has ended or been superseded meanwhile.
284
+ */
285
+ private refuseLate;
286
+ /**
287
+ * rrweb landed while the retry at `online` was still waiting -- the page
288
+ * resumed the capture, or showed its tab, once the browser was online,
289
+ * and the DOM gate imported rrweb itself. The capture's owner is told as
290
+ * the retry would have told it, and the retry is dropped: left waiting,
291
+ * the capture was live and recording and its transport stayed held until
292
+ * an `online` event came to ask again (found in review #28).
293
+ */
294
+ private landedBeforeTheRetry;
295
+ /** Whether rrweb's import waits for the network: onRRWeb says how it went. */
296
+ awaitingRRWeb(): boolean;
153
297
  private rrwebOptions;
298
+ /**
299
+ * rrweb's node `id` is still in the page: the node kept for it when the
300
+ * styles' observer started following it (rrweb's mirror forgets the id
301
+ * of a node moved out of a frame into the page; NodePresence), else the
302
+ * one rrweb's mirror has, connected, and -- in a frame -- in a frame
303
+ * that is itself still in the page, up to the top. A removed shadow
304
+ * host's insides stay in the mirror and a removed frame's nodes stay
305
+ * connected to that frame's document, so the mirror alone could not
306
+ * say. Asked by the styles' observer after a mutation that removes
307
+ * nodes; with no rrweb, nothing is pruned.
308
+ */
309
+ private inPage;
310
+ /**
311
+ * A MOVE NO LISTENER HEARD, found when the next event is recorded. A
312
+ * router that calls a pushState it saved before the SDK wrapped history
313
+ * moves the page past the wrapper; where the browser has the Navigation
314
+ * API its entry change still reports the move, and where it has none the
315
+ * move is found here, before the event that follows it is recorded, so
316
+ * that event and every one after it belong to the new page. Recorded
317
+ * while popstate itself is being dispatched (by a listener of the page's
318
+ * own that ran before the SDK's) it was the traversal; anywhere else it is
319
+ * read as a push -- a replace cannot be told apart from one any more, and
320
+ * nor can a traversal whose popstate listener caused another event first
321
+ * (earlierMove reads the innermost event).
322
+ * No timer looks
323
+ * for it: one string comparison per event, and the page URL is read
324
+ * again only when it has changed. rrweb's own Meta (the snapshot that
325
+ * reopens a shut gate) names the page itself: a move made while the
326
+ * gate was shut is that snapshot's, as a heard one is, and no step's.
327
+ */
328
+ private noticeUnheardMove;
329
+ /**
330
+ * A page URL as this capture records it: the page URL's rule
331
+ * (recordedPageUrl), then scrubPageUrl over what that keeps -- every
332
+ * query value under strict, and otherwise a value shaped like a token
333
+ * or holding a PII pattern, a JWT path segment and a URL nested in a
334
+ * value; never a value that rule kept by its own judgement of names and
335
+ * ids. Used for the session's URL and referrer and for every Meta
336
+ * event's href, rrweb's and this recorder's.
337
+ */
338
+ private scrubUrl;
339
+ /**
340
+ * The URLs in an rrweb event's DOM, scrubbed: every URL-valued
341
+ * attribute in a full snapshot (type 2), and in a mutation (type 3,
342
+ * source 0) every added subtree's, every changed attribute and every
343
+ * changed text's CSS; the CSS of a rule, a replaced sheet, a declaration
344
+ * or an adopted sheet a script put through the CSSOM (sources 8, 13,
345
+ * 15). See scrubDomAttributes and scrubDomCss. A Meta event's href is the page URL, scrubbed by
346
+ * scrubUrl in recordedRRWebEvent. It runs before the credential scrub
347
+ * (scrubSecrets), knowing the page URL's credentials by value
348
+ * (`matcher`), on rrweb's own objects, in place: copying a 50,000-node
349
+ * tree to change three attributes would cost more than the scrub. A
350
+ * throw is emitEvent's to handle, as the credential scrub's is: the
351
+ * event is not sent.
352
+ */
353
+ private scrubDomUrls;
354
+ /**
355
+ * True while an event decided now would pass the session gate: what the
356
+ * network interceptor asks at an exchange's own moment (see
357
+ * NetworkInterceptor's `admit`).
358
+ */
359
+ acceptsNetwork(): boolean;
154
360
  /**
155
361
  * Emit an event to the registered callback. This is also called
156
362
  * externally by the main KeployCapture orchestrator for network
@@ -158,7 +364,17 @@ export declare class KeployCaptureRecorder {
158
364
  *
159
365
  * THE GATES ARE HERE, so every emitter faces the same two. They used
160
366
  * to sit only in rrweb's emit callback, which meant "paused" and
161
- * "stopped" applied to DOM events and to nothing else.
367
+ * "stopped" applied to DOM events and to nothing else. `prepare`
368
+ * rewrites `data` only once the gates let the event through: rewriting
369
+ * one that is then dropped is work for nothing.
370
+ *
371
+ * `admitted`: the caller asked {@link acceptsNetwork} at the event's own
372
+ * moment and the gate was open, so a pause() since then does not drop
373
+ * it -- the exchange happened before the pause. The session must still
374
+ * be live. `at`: the event's timestamp when it is not now -- a fetch's,
375
+ * stamped when it was answered (see NetworkEventCallback). `seq`: its
376
+ * place in the session when one was taken for it before (see
377
+ * Transport.place), else the transport stamps it as it is queued.
162
378
  */
163
- emitEvent(type: SessionEvent["type"], data: unknown): void;
379
+ emitEvent(type: SessionEvent["type"], data: unknown, prepare?: (data: unknown) => unknown, admitted?: boolean, at?: number, seq?: number): void;
164
380
  }
package/dist/redact.d.ts CHANGED
@@ -2,7 +2,18 @@
2
2
  export declare const TRUNCATED_UNPARSEABLE = "[UNPARSEABLE_BODY_NOT_REDACTED]";
3
3
  /** True for a body that IS one of the SDK's own not-recorded notes. */
4
4
  export declare function isNotRecordedNote(body: string): boolean;
5
- declare function isSensitiveKey(key: string): boolean;
5
+ /**
6
+ * Whether a state is an app's word rather than OAuth's generated value:
7
+ * letters, or words joined by `-` or `_`, of at most 16 characters --
8
+ * `delivered`, `California`, `in-progress` -- or longer camelCase or
9
+ * joined words. A random run of letters past 16 is not one (review).
10
+ */
11
+ export declare function isPlainState(state: string): boolean;
12
+ /**
13
+ * A JSON key's, a HAR-style pair's or a header's name, read by the one
14
+ * rule (@keploy/contract's privacy.ts isCredentialName) as a `key`.
15
+ */
16
+ export declare function isSensitiveKey(key: string): boolean;
6
17
  /** Luhn check — the standard checksum every real card number satisfies. */
7
18
  declare function passesLuhn(digits: string): boolean;
8
19
  /**
@@ -17,26 +28,57 @@ declare function passesLuhn(digits: string): boolean;
17
28
  declare function isLikelyCardNumber(digits: string): boolean;
18
29
  /** Redact card-shaped runs inside a string, preserving everything else. */
19
30
  declare function redactCards(s: string): string;
31
+ /** A half-open span of a text to redact: [start, end). */
32
+ type Range = [number, number] | [number, number, string];
20
33
  /**
21
34
  * Apply every value-level detector to one string, then every
22
- * caller-supplied pattern.
35
+ * caller-supplied pattern, all over the string as it came.
23
36
  *
24
37
  * `extra` is the integrator's `privacy.piiPatterns`, already compiled
25
38
  * global (see PrivacyEngine). It rides through every scan the engine
26
- * makes — this function is the ONLY string scanner — so a pattern
39
+ * makes -- this function is the ONLY string scanner -- so a pattern
27
40
  * applies to a JSON string value, a text body and a header value alike.
28
41
  * It used to reach header values only, while its documentation said
29
42
  * "matched text is replaced".
30
43
  */
31
44
  export declare function redactStringValue(value: string, extra?: readonly RegExp[]): string;
45
+ /**
46
+ * The token detectors alone -- a JWT, a provider-prefixed key -- over one
47
+ * string: what the page's own text is read for (privacy.ts scrubDomText).
48
+ * A credential on screen is one whatever text is around it; an email or a
49
+ * phone number in the page's text is the page's content, which balanced
50
+ * records.
51
+ */
52
+ export declare function redactTokens(value: string): string;
53
+ /** Where `value`'s JWTs and provider-prefixed keys lie. */
54
+ export declare function tokenRanges(value: string): Range[];
55
+ /**
56
+ * Every URL a header's value holds, scrubbed as a text body's URLs are
57
+ * (TEXT_URL_RULES: a credential's own value replaced, ended at its first
58
+ * stop, every other byte kept),
59
+ * and every pair a header's leads start (EMBEDDED_NAME_IN_HEADER), as a
60
+ * relative URL's, which the URL scan does not find, is: a `Referer`, an
61
+ * `X-Redirect-To`, a `Content-Security-Policy`'s `report-uri` absolute or
62
+ * relative (`/csp-report?token=...`). A header is no replay key, so no
63
+ * pair is replaced whole for a name inside it. Only Location,
64
+ * Content-Location, Link and Refresh were read, and a URL any other header
65
+ * carried was recorded as it came (found in review).
66
+ */
67
+ export declare function scrubHeaderUrls(value: string): string;
32
68
  /**
33
69
  * Redact a captured body.
34
70
  *
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.
71
+ * JSON in, valid JSON out — always. A body that is not JSON keeps every
72
+ * byte except what is redacted: a form's credential values and the
73
+ * pattern matches in its other values, or, in any other text, the value
74
+ * of an embedded credential pair and the pattern matches.
38
75
  */
39
76
  export declare function redactBody(body: string | null | undefined, contentType?: string, extra?: readonly RegExp[]): string | null;
77
+ /**
78
+ * What network.ts appends to a body it cut at the cap. Defined here and
79
+ * imported there, so the form parser and the cut agree on one string.
80
+ */
81
+ export declare const TRUNCATED_SUFFIX = "...[truncated]";
40
82
  /** Exposed for tests and diagnostics. */
41
83
  export declare const __internals: {
42
84
  isSensitiveKey: typeof isSensitiveKey;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The request term of a raw body: "" or "graphql:<name>#<documentId>".
3
+ * `subtle` hashes the document (SHA-256).
4
+ */
5
+ export declare function requestTerm(body: string | null | undefined, subtle: SubtleCrypto): Promise<string>;
6
+ /**
7
+ * The requestTerm to record for a body AS THE APP HANDED IT to fetch or
8
+ * XHR -- before redaction, masking or truncation touch it. Known at once
9
+ * unless a document has to be hashed; only then a Promise. What needs no
10
+ * term code (no body, a form, a body that is not text or is longer than
11
+ * MAX_TERM_BODY, text that cannot be a GraphQL request) is
12
+ * termBeforeLoad()'s, which the interceptor asks before it loads this
13
+ * chunk. Where the page has no SubtleCrypto (an insecure context) a
14
+ * GraphQL document cannot be hashed and is "body:*", and every other term
15
+ * needs no hash: the recording is still a canonical-key.v2 document,
16
+ * whose redacted values match as wildcards (spec/canonical-key.v2.json
17
+ * rules.record). It may throw or reject: the interceptor's termFor() is
18
+ * the one place that turns any failure into "no term", so nothing here
19
+ * can reach the page.
20
+ */
21
+ export declare function recordTermFor(body: unknown, subtle: SubtleCrypto | undefined): string | Promise<string>;
@@ -0,0 +1,2 @@
1
+ "use strict";var l=Object.defineProperty;var y=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var m=Object.prototype.hasOwnProperty;var w=(n,t)=>{for(var e in t)l(n,e,{get:t[e],enumerable:!0})},A=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of h(t))!m.call(n,r)&&r!==e&&l(n,r,{get:()=>t[r],enumerable:!(s=y(t,r))||s.enumerable});return n};var E=n=>A(l({},"__esModule",{value:!0}),n);var _={};w(_,{recordTermFor:()=>M,requestTerm:()=>O});module.exports=E(_);var x=/^[\t\n\r ]*\{/;function F(n){return x.test(n)&&(n.includes('"query"')||n.includes("persistedQuery")||n.includes("\\u"))}function f(n){return n==null||n===""?"":typeof n=="string"?n.length>4194304?"body:*":F(n)?null:"":n instanceof URLSearchParams||typeof FormData<"u"&&n instanceof FormData?"":"body:*"}var S=/^[_A-Za-z]\w*$/,T=["{","query","mutation","subscription","fragment"],k=["query","operationName","variables","extensions"],a=/([\t\n\r ,\uFEFF]+|#[^\n\r]*)|("""[^"\\]*(?:(?:\\"""|\\(?!""")|"(?!""))[^"\\]*)*""")|(""")|("[^"\\]*(?:\\[^][^"\\]*)*")|(\.\.\.|[!$&()[\]{}:=@|])|([_A-Za-z]\w*)|([0-9-](?:(?!\.\.\.)[^\t\n\r ,\uFEFF!$&()[\]{}:=@|"#])*)|((?:(?!\.\.\.)[^\t\n\r ,\uFEFF!$&()[\]{}:=@|"#\w-])+)/y;function q(n){let t=[],e=[];for(a.lastIndex=0;a.lastIndex<n.length;){let r=a.exec(n);if(!r||r[3])return null;r[1]||(t.push(r[2]||r[4]?'""':r[7]?"0":r[0]),e.push(!!r[6]))}let s=[];for(let r=0;r<t.length;r++){let o=t[r],i="{([".indexOf(o);if(i!==-1){if(s.push("})]"[i]),!i&&!(e[r+1]||t[r+1]==="..."||t[r+1]==="}"))return null}else if("})]".includes(o)&&o.length===1&&s.pop()!==o)return null}return T.includes(t[0])&&t[t.length-1]==="}"&&!s.length?t.join(" "):null}function u(n,t){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0}function p(n){let t;try{t=n?JSON.parse(n):null}catch{return""}if(t===null||typeof t!="object"||Array.isArray(t))return"";let e=Object.keys(t);if(!e.length||e.some(d=>!k.includes(d)))return"";let s=u(t,"operationName"),r=u(t,"query");if(s!=null&&(typeof s!="string"||!S.test(s))||r!=null&&typeof r!="string")return"";let o=s??"",i=u(u(u(t,"extensions"),"persistedQuery"),"sha256Hash");if(typeof i=="string"&&/^[0-9A-Fa-f]{64}$/.test(i))return`graphql:${o}#pq`;let c=typeof r=="string"?q(r):null;return c===null?"":[o,c]}async function g([n,t],e){let s=new Uint8Array(await e.digest("SHA-256",new TextEncoder().encode(t))),r="";for(let o=0;o<8;o++)r+=s[o].toString(16).padStart(2,"0");return`graphql:${n}#${r}`}async function O(n,t){let e=p(n);return typeof e=="string"?e:g(e,t)}function M(n,t){let e=f(n);if(e!==null)return e;let s=p(n);return typeof s=="string"?s:t?g(s,t):"body:*"}
2
+ //# sourceMappingURL=request-term.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/request-term.ts","../src/term-candidate.ts"],"sourcesContent":["/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - request term (canonical-key.v2) */\n/* ------------------------------------------------------------------ */\n/*\n * The term spec/canonical-key.v2.json keys a GraphQL request by:\n * \"graphql:<operationName>#<documentId>\", or \"\" when the body is not a\n * GraphQL request. Executed against that file's `term` vectors by\n * __tests__/request-term.test.ts.\n *\n * It is computed HERE, over the RAW body, before redaction, masking or\n * truncation touch it: the stored body may have had a PII pattern\n * redacted inside the document, may be \"[MASKED]\" (strict mode) or may\n * be cut at maxBodySize, and a term derived from it would be wrong or\n * missing. An operation name and a document hash are not user data:\n * every literal (string, block string, number) is blanked before\n * hashing, so input inlined into a document never reaches the hash, and\n * a persisted query's own hash is never recorded.\n *\n * The replay runtime holds a second implementation (packages/replay-\n * runtime/src/canonkey.ts, `graphqlTerm`) held to the same vectors: this\n * package is public and dependency-free, that one is private, and\n * neither may depend on the other. No GraphQL parser: one sticky regex\n * cuts the lexemes, which keeps the code the page downloads small.\n *\n * THIS FILE IS A CHUNK OF ITS OWN (dist/request-term.{mjs,js}, the\n * package's \"./request-term\" export), which network.ts loads the first\n * time a body could be a GraphQL request (term-candidate.ts), and never\n * for a page that sends none. It imports nothing but term-candidate.ts,\n * and nothing in the main bundle imports it but by that name:\n * __tests__/bundle-size.test.ts fails when its lexer is in\n * dist/index.{mjs,js}.\n */\n\nimport { termBeforeLoad } from \"./term-candidate\";\n\nconst NAME = /^[_A-Za-z]\\w*$/;\nconst STARTS = [\"{\", \"query\", \"mutation\", \"subscription\", \"fragment\"];\nconst MEMBERS = [\"query\", \"operationName\", \"variables\", \"extensions\"];\n\n/*\n * One lexeme per match, by the spec's rules.normalisation, in groups:\n * 1 ignored tokens (dropped) 2 a block string 3 an\n * unterminated block string 4 a string 5 a punctuator\n * 6 a NAME run 7 a NUMBER run 8 any other run\n * Anything no alternative matches (an unterminated string) fails the\n * scan. Sticky (y), so a lexeme can only start where the last one ended.\n * Both string alternatives are UNROLLED (a run of plain characters, then\n * one escape or quote at a time), so a long literal is a simple loop and\n * never a backtrack frame per character; and a block string's escaped\n * \\\"\"\" can only be read as the escape -- were its backslash content, the\n * regex would backtrack into it and close a block string the spec says\n * is unterminated.\n */\nconst LEXEME =\n /([\\t\\n\\r ,\\uFEFF]+|#[^\\n\\r]*)|(\"\"\"[^\"\\\\]*(?:(?:\\\\\"\"\"|\\\\(?!\"\"\")|\"(?!\"\"))[^\"\\\\]*)*\"\"\")|(\"\"\")|(\"[^\"\\\\]*(?:\\\\[^][^\"\\\\]*)*\")|(\\.\\.\\.|[!$&()[\\]{}:=@|])|([_A-Za-z]\\w*)|([0-9-](?:(?!\\.\\.\\.)[^\\t\\n\\r ,\\uFEFF!$&()[\\]{}:=@|\"#])*)|((?:(?!\\.\\.\\.)[^\\t\\n\\r ,\\uFEFF!$&()[\\]{}:=@|\"#\\w-])+)/y;\n\n/**\n * The normalised text of a GraphQL document -- lexemes joined by one\n * space, every string blanked to \"\" and every number to 0 -- or null\n * when the text is not a GraphQL document.\n */\nfunction normalise(doc: string): string | null {\n const out: string[] = [];\n const name: boolean[] = [];\n LEXEME.lastIndex = 0;\n while (LEXEME.lastIndex < doc.length) {\n const m = LEXEME.exec(doc);\n if (!m || m[3]) return null;\n if (m[1]) continue;\n out.push(m[2] || m[4] ? '\"\"' : m[7] ? \"0\" : m[0]);\n name.push(!!m[6]);\n }\n // Every opener closes in order; every { opens a selection: a name,\n // '...' or } follows it. A string is \"\" here and a number 0, so no\n // literal can pass for a punctuator or a keyword.\n const open: string[] = [];\n for (let k = 0; k < out.length; k++) {\n const t = out[k] as string;\n const at = \"{([\".indexOf(t);\n if (at !== -1) {\n open.push(\"})]\"[at] as string);\n if (!at && !(name[k + 1] || out[k + 1] === \"...\" || out[k + 1] === \"}\"))\n return null;\n } else if (\"})]\".includes(t) && t.length === 1 && open.pop() !== t)\n return null;\n }\n return STARTS.includes(out[0] as string) &&\n out[out.length - 1] === \"}\" &&\n !open.length\n ? out.join(\" \")\n : null;\n}\n\nfunction own(o: unknown, k: string): unknown {\n return o !== null &&\n typeof o === \"object\" &&\n !Array.isArray(o) &&\n Object.prototype.hasOwnProperty.call(o, k)\n ? (o as Record<string, unknown>)[k]\n : undefined;\n}\n\n/**\n * Everything of the term that needs no hash: \"\" (not a GraphQL request),\n * \"graphql:<name>#pq\" (a persisted query), or [name, normalised text]\n * still to be hashed.\n */\nfunction prepare(body: string | null | undefined): string | [string, string] {\n let v: unknown;\n try {\n v = body ? JSON.parse(body) : null;\n } catch {\n return \"\";\n }\n if (v === null || typeof v !== \"object\" || Array.isArray(v)) return \"\";\n const keys = Object.keys(v);\n if (!keys.length || keys.some((key) => !MEMBERS.includes(key))) return \"\";\n const name = own(v, \"operationName\");\n const query = own(v, \"query\");\n if (name != null && (typeof name !== \"string\" || !NAME.test(name))) return \"\";\n if (query != null && typeof query !== \"string\") return \"\";\n const n = (name as string | null | undefined) ?? \"\";\n const hash = own(own(own(v, \"extensions\"), \"persistedQuery\"), \"sha256Hash\");\n if (typeof hash === \"string\" && /^[0-9A-Fa-f]{64}$/.test(hash))\n return `graphql:${n}#pq`;\n const text = typeof query === \"string\" ? normalise(query) : null;\n return text === null ? \"\" : [n, text];\n}\n\n/** The term of a prepared document: its name and 16 hex of SHA-256. */\nasync function hashed(\n [name, text]: [string, string],\n subtle: SubtleCrypto,\n): Promise<string> {\n const digest = new Uint8Array(\n await subtle.digest(\"SHA-256\", new TextEncoder().encode(text)),\n );\n let hex = \"\";\n for (let k = 0; k < 8; k++)\n hex += (digest[k] as number).toString(16).padStart(2, \"0\");\n return `graphql:${name}#${hex}`;\n}\n\n/**\n * The request term of a raw body: \"\" or \"graphql:<name>#<documentId>\".\n * `subtle` hashes the document (SHA-256).\n */\nexport async function requestTerm(\n body: string | null | undefined,\n subtle: SubtleCrypto,\n): Promise<string> {\n const p = prepare(body);\n return typeof p === \"string\" ? p : hashed(p, subtle);\n}\n\n/**\n * The requestTerm to record for a body AS THE APP HANDED IT to fetch or\n * XHR -- before redaction, masking or truncation touch it. Known at once\n * unless a document has to be hashed; only then a Promise. What needs no\n * term code (no body, a form, a body that is not text or is longer than\n * MAX_TERM_BODY, text that cannot be a GraphQL request) is\n * termBeforeLoad()'s, which the interceptor asks before it loads this\n * chunk. Where the page has no SubtleCrypto (an insecure context) a\n * GraphQL document cannot be hashed and is \"body:*\", and every other term\n * needs no hash: the recording is still a canonical-key.v2 document,\n * whose redacted values match as wildcards (spec/canonical-key.v2.json\n * rules.record). It may throw or reject: the interceptor's termFor() is\n * the one place that turns any failure into \"no term\", so nothing here\n * can reach the page.\n */\nexport function recordTermFor(\n body: unknown,\n subtle: SubtleCrypto | undefined,\n): string | Promise<string> {\n const known = termBeforeLoad(body);\n if (known !== null) return known;\n const p = prepare(body as string);\n if (typeof p === \"string\") return p;\n return subtle ? hashed(p, subtle) : \"body:*\";\n}\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - could a body be a GraphQL request? */\n/* ------------------------------------------------------------------ */\n/*\n * The term code (request-term.ts: the lexer, the document check, the\n * hash) is a chunk of its own, loaded only for a body that passes\n * couldBeGraphql(); every other body is recorded here, at once, and the\n * chunk is never fetched. So the check must be a SUPERSET of what the\n * term code gives a term: a GraphQL body it missed would be recorded ''\n * while replay computes its term from postData(), and the keys would\n * differ.\n *\n * DERIVED FROM THE TERM CODE'S OWN ENTRY CONDITIONS (spec/canonical-\n * key.v2.json rules.term and rules.document; request-term.ts prepare()),\n * not from examples. A body has a term only when:\n * 1. it parses as ONE JSON value with nothing but JSON's whitespace\n * (U+0020, U+0009, U+000A, U+000D) before it -- a byte order mark\n * is refused -- and that value is an OBJECT, so the first character\n * that is not JSON whitespace is `{`; and\n * 2. it has a documentId, which needs a member named `query` (a string\n * that is a document) or a member named `persistedQuery` (inside\n * `extensions`). A member name is a JSON string: written with no\n * escape it is exactly `\"query\"`, quotes included, or holds\n * `persistedQuery`; written with any escape it holds `\\u`, the only\n * JSON escape that yields a letter.\n * So a batch (`[...]`), a raw application/graphql document (`{ me { id\n * } }`, `query Q { ... }`), a form and plain text have no term on either\n * side, and a GET has no body to read (the live term is\n * term(request.postData())). __tests__/term-candidate.test.ts runs every\n * term vector and every e2e GraphQL body through the check.\n */\n\n/** Longer bodies (UTF-16 units) are recorded \"body:*\": bounded work, and no literal long enough to strain a regex engine. */\nexport const MAX_TERM_BODY = 4 * 1024 * 1024;\n\n/** Text that starts as a JSON object does: JSON whitespace, then `{` (condition 1 above). */\nexport const OBJECT_START = /^[\\t\\n\\r ]*\\{/;\n\n/** The first character that is not JSON whitespace. */\nexport const NOT_SPACE = /[^\\t\\n\\r ]/;\n\n/** True when `text` could be a body the term code gives a term (see above). */\nexport function couldBeGraphql(text: string): boolean {\n return (\n OBJECT_START.test(text) &&\n (text.includes('\"query\"') ||\n text.includes(\"persistedQuery\") ||\n text.includes(\"\\\\u\"))\n );\n}\n\n/**\n * The requestTerm of a body AS THE APP HANDED IT to fetch or XHR when it\n * needs no term code: '' for no body, a form, or text that cannot be a\n * GraphQL request; \"body:*\" for a body that is not text (a Blob, a\n * buffer, a stream, a Document) or is longer than MAX_TERM_BODY. null\n * when the body could be a GraphQL request: the term code decides it.\n */\nexport function termBeforeLoad(body: unknown): string | null {\n if (body == null || body === \"\") return \"\";\n if (typeof body === \"string\")\n return body.length > MAX_TERM_BODY\n ? \"body:*\"\n : couldBeGraphql(body)\n ? null\n : \"\";\n // Sent as form text, which is never a JSON object.\n if (\n body instanceof URLSearchParams ||\n (typeof FormData !== \"undefined\" && body instanceof FormData)\n )\n return \"\";\n return \"body:*\";\n}\n"],"mappings":"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","names":["request_term_exports","__export","recordTermFor","requestTerm","__toCommonJS","OBJECT_START","couldBeGraphql","text","OBJECT_START","termBeforeLoad","body","NAME","STARTS","MEMBERS","LEXEME","normalise","doc","out","name","m","open","k","t","at","own","o","prepare","body","v","keys","key","query","n","hash","text","hashed","subtle","digest","hex","requestTerm","p","recordTermFor","known","termBeforeLoad"]}
@@ -0,0 +1,2 @@
1
+ var d=/^[\t\n\r ]*\{/;function y(n){return d.test(n)&&(n.includes('"query"')||n.includes("persistedQuery")||n.includes("\\u"))}function c(n){return n==null||n===""?"":typeof n=="string"?n.length>4194304?"body:*":y(n)?null:"":n instanceof URLSearchParams||typeof FormData<"u"&&n instanceof FormData?"":"body:*"}var h=/^[_A-Za-z]\w*$/,m=["{","query","mutation","subscription","fragment"],w=["query","operationName","variables","extensions"],l=/([\t\n\r ,\uFEFF]+|#[^\n\r]*)|("""[^"\\]*(?:(?:\\"""|\\(?!""")|"(?!""))[^"\\]*)*""")|(""")|("[^"\\]*(?:\\[^][^"\\]*)*")|(\.\.\.|[!$&()[\]{}:=@|])|([_A-Za-z]\w*)|([0-9-](?:(?!\.\.\.)[^\t\n\r ,\uFEFF!$&()[\]{}:=@|"#])*)|((?:(?!\.\.\.)[^\t\n\r ,\uFEFF!$&()[\]{}:=@|"#\w-])+)/y;function A(n){let t=[],e=[];for(l.lastIndex=0;l.lastIndex<n.length;){let r=l.exec(n);if(!r||r[3])return null;r[1]||(t.push(r[2]||r[4]?'""':r[7]?"0":r[0]),e.push(!!r[6]))}let s=[];for(let r=0;r<t.length;r++){let o=t[r],i="{([".indexOf(o);if(i!==-1){if(s.push("})]"[i]),!i&&!(e[r+1]||t[r+1]==="..."||t[r+1]==="}"))return null}else if("})]".includes(o)&&o.length===1&&s.pop()!==o)return null}return m.includes(t[0])&&t[t.length-1]==="}"&&!s.length?t.join(" "):null}function u(n,t){return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:void 0}function f(n){let t;try{t=n?JSON.parse(n):null}catch{return""}if(t===null||typeof t!="object"||Array.isArray(t))return"";let e=Object.keys(t);if(!e.length||e.some(g=>!w.includes(g)))return"";let s=u(t,"operationName"),r=u(t,"query");if(s!=null&&(typeof s!="string"||!h.test(s))||r!=null&&typeof r!="string")return"";let o=s??"",i=u(u(u(t,"extensions"),"persistedQuery"),"sha256Hash");if(typeof i=="string"&&/^[0-9A-Fa-f]{64}$/.test(i))return`graphql:${o}#pq`;let a=typeof r=="string"?A(r):null;return a===null?"":[o,a]}async function p([n,t],e){let s=new Uint8Array(await e.digest("SHA-256",new TextEncoder().encode(t))),r="";for(let o=0;o<8;o++)r+=s[o].toString(16).padStart(2,"0");return`graphql:${n}#${r}`}async function F(n,t){let e=f(n);return typeof e=="string"?e:p(e,t)}function S(n,t){let e=c(n);if(e!==null)return e;let s=f(n);return typeof s=="string"?s:t?p(s,t):"body:*"}export{S as recordTermFor,F as requestTerm};
2
+ //# sourceMappingURL=request-term.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/term-candidate.ts","../src/request-term.ts"],"sourcesContent":["/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - could a body be a GraphQL request? */\n/* ------------------------------------------------------------------ */\n/*\n * The term code (request-term.ts: the lexer, the document check, the\n * hash) is a chunk of its own, loaded only for a body that passes\n * couldBeGraphql(); every other body is recorded here, at once, and the\n * chunk is never fetched. So the check must be a SUPERSET of what the\n * term code gives a term: a GraphQL body it missed would be recorded ''\n * while replay computes its term from postData(), and the keys would\n * differ.\n *\n * DERIVED FROM THE TERM CODE'S OWN ENTRY CONDITIONS (spec/canonical-\n * key.v2.json rules.term and rules.document; request-term.ts prepare()),\n * not from examples. A body has a term only when:\n * 1. it parses as ONE JSON value with nothing but JSON's whitespace\n * (U+0020, U+0009, U+000A, U+000D) before it -- a byte order mark\n * is refused -- and that value is an OBJECT, so the first character\n * that is not JSON whitespace is `{`; and\n * 2. it has a documentId, which needs a member named `query` (a string\n * that is a document) or a member named `persistedQuery` (inside\n * `extensions`). A member name is a JSON string: written with no\n * escape it is exactly `\"query\"`, quotes included, or holds\n * `persistedQuery`; written with any escape it holds `\\u`, the only\n * JSON escape that yields a letter.\n * So a batch (`[...]`), a raw application/graphql document (`{ me { id\n * } }`, `query Q { ... }`), a form and plain text have no term on either\n * side, and a GET has no body to read (the live term is\n * term(request.postData())). __tests__/term-candidate.test.ts runs every\n * term vector and every e2e GraphQL body through the check.\n */\n\n/** Longer bodies (UTF-16 units) are recorded \"body:*\": bounded work, and no literal long enough to strain a regex engine. */\nexport const MAX_TERM_BODY = 4 * 1024 * 1024;\n\n/** Text that starts as a JSON object does: JSON whitespace, then `{` (condition 1 above). */\nexport const OBJECT_START = /^[\\t\\n\\r ]*\\{/;\n\n/** The first character that is not JSON whitespace. */\nexport const NOT_SPACE = /[^\\t\\n\\r ]/;\n\n/** True when `text` could be a body the term code gives a term (see above). */\nexport function couldBeGraphql(text: string): boolean {\n return (\n OBJECT_START.test(text) &&\n (text.includes('\"query\"') ||\n text.includes(\"persistedQuery\") ||\n text.includes(\"\\\\u\"))\n );\n}\n\n/**\n * The requestTerm of a body AS THE APP HANDED IT to fetch or XHR when it\n * needs no term code: '' for no body, a form, or text that cannot be a\n * GraphQL request; \"body:*\" for a body that is not text (a Blob, a\n * buffer, a stream, a Document) or is longer than MAX_TERM_BODY. null\n * when the body could be a GraphQL request: the term code decides it.\n */\nexport function termBeforeLoad(body: unknown): string | null {\n if (body == null || body === \"\") return \"\";\n if (typeof body === \"string\")\n return body.length > MAX_TERM_BODY\n ? \"body:*\"\n : couldBeGraphql(body)\n ? null\n : \"\";\n // Sent as form text, which is never a JSON object.\n if (\n body instanceof URLSearchParams ||\n (typeof FormData !== \"undefined\" && body instanceof FormData)\n )\n return \"\";\n return \"body:*\";\n}\n","/* ------------------------------------------------------------------ */\n/* @keploy/capture-sdk - request term (canonical-key.v2) */\n/* ------------------------------------------------------------------ */\n/*\n * The term spec/canonical-key.v2.json keys a GraphQL request by:\n * \"graphql:<operationName>#<documentId>\", or \"\" when the body is not a\n * GraphQL request. Executed against that file's `term` vectors by\n * __tests__/request-term.test.ts.\n *\n * It is computed HERE, over the RAW body, before redaction, masking or\n * truncation touch it: the stored body may have had a PII pattern\n * redacted inside the document, may be \"[MASKED]\" (strict mode) or may\n * be cut at maxBodySize, and a term derived from it would be wrong or\n * missing. An operation name and a document hash are not user data:\n * every literal (string, block string, number) is blanked before\n * hashing, so input inlined into a document never reaches the hash, and\n * a persisted query's own hash is never recorded.\n *\n * The replay runtime holds a second implementation (packages/replay-\n * runtime/src/canonkey.ts, `graphqlTerm`) held to the same vectors: this\n * package is public and dependency-free, that one is private, and\n * neither may depend on the other. No GraphQL parser: one sticky regex\n * cuts the lexemes, which keeps the code the page downloads small.\n *\n * THIS FILE IS A CHUNK OF ITS OWN (dist/request-term.{mjs,js}, the\n * package's \"./request-term\" export), which network.ts loads the first\n * time a body could be a GraphQL request (term-candidate.ts), and never\n * for a page that sends none. It imports nothing but term-candidate.ts,\n * and nothing in the main bundle imports it but by that name:\n * __tests__/bundle-size.test.ts fails when its lexer is in\n * dist/index.{mjs,js}.\n */\n\nimport { termBeforeLoad } from \"./term-candidate\";\n\nconst NAME = /^[_A-Za-z]\\w*$/;\nconst STARTS = [\"{\", \"query\", \"mutation\", \"subscription\", \"fragment\"];\nconst MEMBERS = [\"query\", \"operationName\", \"variables\", \"extensions\"];\n\n/*\n * One lexeme per match, by the spec's rules.normalisation, in groups:\n * 1 ignored tokens (dropped) 2 a block string 3 an\n * unterminated block string 4 a string 5 a punctuator\n * 6 a NAME run 7 a NUMBER run 8 any other run\n * Anything no alternative matches (an unterminated string) fails the\n * scan. Sticky (y), so a lexeme can only start where the last one ended.\n * Both string alternatives are UNROLLED (a run of plain characters, then\n * one escape or quote at a time), so a long literal is a simple loop and\n * never a backtrack frame per character; and a block string's escaped\n * \\\"\"\" can only be read as the escape -- were its backslash content, the\n * regex would backtrack into it and close a block string the spec says\n * is unterminated.\n */\nconst LEXEME =\n /([\\t\\n\\r ,\\uFEFF]+|#[^\\n\\r]*)|(\"\"\"[^\"\\\\]*(?:(?:\\\\\"\"\"|\\\\(?!\"\"\")|\"(?!\"\"))[^\"\\\\]*)*\"\"\")|(\"\"\")|(\"[^\"\\\\]*(?:\\\\[^][^\"\\\\]*)*\")|(\\.\\.\\.|[!$&()[\\]{}:=@|])|([_A-Za-z]\\w*)|([0-9-](?:(?!\\.\\.\\.)[^\\t\\n\\r ,\\uFEFF!$&()[\\]{}:=@|\"#])*)|((?:(?!\\.\\.\\.)[^\\t\\n\\r ,\\uFEFF!$&()[\\]{}:=@|\"#\\w-])+)/y;\n\n/**\n * The normalised text of a GraphQL document -- lexemes joined by one\n * space, every string blanked to \"\" and every number to 0 -- or null\n * when the text is not a GraphQL document.\n */\nfunction normalise(doc: string): string | null {\n const out: string[] = [];\n const name: boolean[] = [];\n LEXEME.lastIndex = 0;\n while (LEXEME.lastIndex < doc.length) {\n const m = LEXEME.exec(doc);\n if (!m || m[3]) return null;\n if (m[1]) continue;\n out.push(m[2] || m[4] ? '\"\"' : m[7] ? \"0\" : m[0]);\n name.push(!!m[6]);\n }\n // Every opener closes in order; every { opens a selection: a name,\n // '...' or } follows it. A string is \"\" here and a number 0, so no\n // literal can pass for a punctuator or a keyword.\n const open: string[] = [];\n for (let k = 0; k < out.length; k++) {\n const t = out[k] as string;\n const at = \"{([\".indexOf(t);\n if (at !== -1) {\n open.push(\"})]\"[at] as string);\n if (!at && !(name[k + 1] || out[k + 1] === \"...\" || out[k + 1] === \"}\"))\n return null;\n } else if (\"})]\".includes(t) && t.length === 1 && open.pop() !== t)\n return null;\n }\n return STARTS.includes(out[0] as string) &&\n out[out.length - 1] === \"}\" &&\n !open.length\n ? out.join(\" \")\n : null;\n}\n\nfunction own(o: unknown, k: string): unknown {\n return o !== null &&\n typeof o === \"object\" &&\n !Array.isArray(o) &&\n Object.prototype.hasOwnProperty.call(o, k)\n ? (o as Record<string, unknown>)[k]\n : undefined;\n}\n\n/**\n * Everything of the term that needs no hash: \"\" (not a GraphQL request),\n * \"graphql:<name>#pq\" (a persisted query), or [name, normalised text]\n * still to be hashed.\n */\nfunction prepare(body: string | null | undefined): string | [string, string] {\n let v: unknown;\n try {\n v = body ? JSON.parse(body) : null;\n } catch {\n return \"\";\n }\n if (v === null || typeof v !== \"object\" || Array.isArray(v)) return \"\";\n const keys = Object.keys(v);\n if (!keys.length || keys.some((key) => !MEMBERS.includes(key))) return \"\";\n const name = own(v, \"operationName\");\n const query = own(v, \"query\");\n if (name != null && (typeof name !== \"string\" || !NAME.test(name))) return \"\";\n if (query != null && typeof query !== \"string\") return \"\";\n const n = (name as string | null | undefined) ?? \"\";\n const hash = own(own(own(v, \"extensions\"), \"persistedQuery\"), \"sha256Hash\");\n if (typeof hash === \"string\" && /^[0-9A-Fa-f]{64}$/.test(hash))\n return `graphql:${n}#pq`;\n const text = typeof query === \"string\" ? normalise(query) : null;\n return text === null ? \"\" : [n, text];\n}\n\n/** The term of a prepared document: its name and 16 hex of SHA-256. */\nasync function hashed(\n [name, text]: [string, string],\n subtle: SubtleCrypto,\n): Promise<string> {\n const digest = new Uint8Array(\n await subtle.digest(\"SHA-256\", new TextEncoder().encode(text)),\n );\n let hex = \"\";\n for (let k = 0; k < 8; k++)\n hex += (digest[k] as number).toString(16).padStart(2, \"0\");\n return `graphql:${name}#${hex}`;\n}\n\n/**\n * The request term of a raw body: \"\" or \"graphql:<name>#<documentId>\".\n * `subtle` hashes the document (SHA-256).\n */\nexport async function requestTerm(\n body: string | null | undefined,\n subtle: SubtleCrypto,\n): Promise<string> {\n const p = prepare(body);\n return typeof p === \"string\" ? p : hashed(p, subtle);\n}\n\n/**\n * The requestTerm to record for a body AS THE APP HANDED IT to fetch or\n * XHR -- before redaction, masking or truncation touch it. Known at once\n * unless a document has to be hashed; only then a Promise. What needs no\n * term code (no body, a form, a body that is not text or is longer than\n * MAX_TERM_BODY, text that cannot be a GraphQL request) is\n * termBeforeLoad()'s, which the interceptor asks before it loads this\n * chunk. Where the page has no SubtleCrypto (an insecure context) a\n * GraphQL document cannot be hashed and is \"body:*\", and every other term\n * needs no hash: the recording is still a canonical-key.v2 document,\n * whose redacted values match as wildcards (spec/canonical-key.v2.json\n * rules.record). It may throw or reject: the interceptor's termFor() is\n * the one place that turns any failure into \"no term\", so nothing here\n * can reach the page.\n */\nexport function recordTermFor(\n body: unknown,\n subtle: SubtleCrypto | undefined,\n): string | Promise<string> {\n const known = termBeforeLoad(body);\n if (known !== null) return known;\n const p = prepare(body as string);\n if (typeof p === \"string\") return p;\n return subtle ? hashed(p, subtle) : \"body:*\";\n}\n"],"mappings":"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","names":["OBJECT_START","couldBeGraphql","text","OBJECT_START","termBeforeLoad","body","NAME","STARTS","MEMBERS","LEXEME","normalise","doc","out","name","m","open","k","t","at","own","o","prepare","body","v","keys","key","query","n","hash","text","hashed","subtle","digest","hex","requestTerm","p","recordTermFor","known","termBeforeLoad"]}
@@ -0,0 +1,16 @@
1
+ /** Longer bodies (UTF-16 units) are recorded "body:*": bounded work, and no literal long enough to strain a regex engine. */
2
+ export declare const MAX_TERM_BODY: number;
3
+ /** Text that starts as a JSON object does: JSON whitespace, then `{` (condition 1 above). */
4
+ export declare const OBJECT_START: RegExp;
5
+ /** The first character that is not JSON whitespace. */
6
+ export declare const NOT_SPACE: RegExp;
7
+ /** True when `text` could be a body the term code gives a term (see above). */
8
+ export declare function couldBeGraphql(text: string): boolean;
9
+ /**
10
+ * The requestTerm of a body AS THE APP HANDED IT to fetch or XHR when it
11
+ * needs no term code: '' for no body, a form, or text that cannot be a
12
+ * GraphQL request; "body:*" for a body that is not text (a Blob, a
13
+ * buffer, a stream, a Document) or is longer than MAX_TERM_BODY. null
14
+ * when the body could be a GraphQL request: the term code decides it.
15
+ */
16
+ export declare function termBeforeLoad(body: unknown): string | null;