@libo11y/rum-replay 0.0.0-stage → 0.4.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,213 @@
1
- # Temporary Holding Version
1
+ # @libo11y/rum-replay
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Privacy-first session replay for
4
+ [`@libo11y/rum`](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/rum).
5
+ It records the page with rrweb's recorder
6
+ ([`@rrweb/record`](https://www.npmjs.com/package/@rrweb/record) 2.2.2,
7
+ pinned exactly) and passes every event through libo11y's own scrubber
8
+ before anything is buffered. Text is masked by default, and input values
9
+ are never recorded.
10
+
11
+ ## Status
12
+
13
+ The package first ships in `ts/v0.4.0`, and it releases with
14
+ `@libo11y/rum` at the same version. Neither is on npm yet. Until their
15
+ first npm publish, install both from the tarballs attached to the
16
+ [`ts/v0.4.0` GitHub Release](https://github.com/jamesainslie/libo11y/releases/tag/ts/v0.4.0),
17
+ whose notes list the exact URLs:
18
+
19
+ ```sh
20
+ npm install \
21
+ https://github.com/jamesainslie/libo11y/releases/download/ts/v0.4.0/libo11y-rum-0.4.0.tgz \
22
+ https://github.com/jamesainslie/libo11y/releases/download/ts/v0.4.0/libo11y-rum-replay-0.4.0.tgz
23
+ ```
24
+
25
+ The RUM gateway stores what it uploads from `go/o11yrum/v0.2.0` on, once
26
+ an app enables replay; see
27
+ [Session replay](../../../go/o11yrum/README.md#session-replay) in the
28
+ gateway's README.
29
+
30
+ ## Usage
31
+
32
+ Installing the collector is the opt-in. It records only while RUM's
33
+ consent is `granted`.
34
+
35
+ ```ts
36
+ import { errors, setupRum, views } from "@libo11y/rum";
37
+ import { replay } from "@libo11y/rum-replay";
38
+
39
+ const telemetry = await setupRum({
40
+ serviceName: "shop",
41
+ endpoint: "https://rum.example.com",
42
+ consent: { initial: "pending" },
43
+ rum: {
44
+ clientToken: "pub-shop",
45
+ collectors: [views(), errors(), replay({ privacy: { unmask: [".public"] } })],
46
+ },
47
+ });
48
+ ```
49
+
50
+ | Option | Default | Meaning |
51
+ | ------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
52
+ | `sampleRate` | `1` | The share of head-sampled sessions that record, 0 to 1 |
53
+ | `onRetain` | `false` | Also record sessions that are not head-sampled, into memory only, and upload that lead-up if an error or frustration keeps the session |
54
+ | `privacy` | `{}` | `unmask`, `mask` and `block` selectors. See [Privacy model](#privacy-model) |
55
+ | `limits.sampleRate` | `[sampleRate, sampleRate]` | The range remote configuration may move `sampleRate` within |
56
+ | `url` | `new URL("/_o11y/v1/replay", location.href)` | The gateway's replay endpoint. RUM counts it as its own traffic, so its requests are never instrumented |
57
+
58
+ `replay()` throws `O11yError` with code `INVALID_OPTION` for an invalid
59
+ option.
60
+
61
+ ## How it records
62
+
63
+ - **Which sessions.** A session records when replay is on and
64
+ `fnv1a32("replay:" + session.id) / 2^32` is below `sampleRate`, so every
65
+ tab of a session agrees. A head-sampled session records from its start
66
+ and uploads as it goes. With `onRetain`, a session that is not
67
+ head-sampled records into memory: the last two closed segments and the
68
+ open one. If an error or frustration keeps the session, they upload and
69
+ the rest of the session uploads as it goes. If the session ends unkept,
70
+ they are dropped.
71
+ - **rrweb loads lazily.** `replay()` itself adds about 10 KB to the page,
72
+ gzipped. rrweb's recorder, about 24 KB gzipped, is imported with a
73
+ dynamic `import()` the first time a session will record, so a page whose
74
+ session never records never downloads it. Bundlers emit it as a chunk of
75
+ its own. Nothing is recorded until it has loaded. If it fails to load,
76
+ replay stays off for the page, logs one warning and does not retry.
77
+ - **Segments.** Each segment is self-contained: it starts with a full
78
+ snapshot, so a player can start at any segment and a lost upload loses
79
+ only its own time. A segment closes after 30 seconds, at 1 MiB or
80
+ 10,000 events, when the page hides and when the session changes. An idle
81
+ page sends nothing.
82
+ - **Upload.** A segment is gzipped and sent with
83
+ `POST <url>?service=&session=&segment=&sent_at=&client_token=`, without
84
+ credentials and uninstrumented, one at a time and in order. Segment
85
+ numbers count per session across tabs, under a Web Lock. `429` and `503`
86
+ retry after `Retry-After`, at most three attempts, and any other `4xx`
87
+ drops the segment. At most 4 segments and 4 MiB wait to upload; the
88
+ oldest goes first past either bound.
89
+ - **Errors point at the replay.** While a session uploads, its
90
+ `o11y.rum.error` and `o11y.rum.frustration` events carry
91
+ `o11y.rum.replay.segment`, the number of the segment being sent or last
92
+ sent.
93
+ - **Consent.** Revoking consent stops the recorder, drops everything not
94
+ yet sent and removes the shared segment counter.
95
+ - **Where it runs.** Replay records pages and extension pages. It refuses
96
+ to start, with one warning, in an extension content script, which must
97
+ not record the host page, and in a browser without Web Locks or
98
+ `CompressionStream`.
99
+
100
+ ## Privacy model
101
+
102
+ The scrubber is authoritative. rrweb's own masking options are only a
103
+ first line, and the scrubber does not rely on them. Everything is an
104
+ allow-list: an event type, incremental source, node field or attribute
105
+ the scrubber does not know is dropped, so a new rrweb field cannot leak.
106
+ The RUM gateway runs the same rules again before it stores a segment.
107
+ Both implementations run the shared vectors in
108
+ [`conformance/rum-replay`](../../../conformance/rum-replay).
109
+
110
+ | What | Recorded as |
111
+ | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
112
+ | Text | Masked: every character except ASCII whitespace becomes `*`, so layout survives and content does not |
113
+ | Text under a `privacy.unmask` selector | Kept, unless a mask or block selector also covers it |
114
+ | Text under `input`, `textarea`, `select`, `option`, `[contenteditable]` or `[data-o11y-mask]` | Masked, whatever the unmask list says |
115
+ | Text in a `textarea` or editable content, and links, images and styles inside editable content | Dropped |
116
+ | Text in `script` | Dropped |
117
+ | Comments | Dropped |
118
+ | Stylesheets | Kept, with URLs stripped, unless a mask covers them |
119
+ | Elements under `[data-o11y-block]` or a `privacy.block` selector | Replaced by an empty placeholder of the same size. Nothing added inside them later is recorded |
120
+ | `value`, `checked` and `selected` attributes | Never recorded |
121
+ | `title`, `alt`, `placeholder`, `aria-label`, `label`, `content` and other text attributes | Masked like text. An unmasked `content` that holds a URL (`og:url`, `og:image`, a refresh) is stripped like a URL attribute |
122
+ | `href`, `src`, `srcset`, `poster`, `xlink:href` | Path kept, query reduced to RUM's `queryAllowList`, fragment and userinfo removed. Every scheme but `http` and `https` (`data:`, `blob:`, `javascript:`, `mailto:` and the rest) becomes empty |
123
+ | `url()`, URL strings and bare URLs in `style` and CSS | Stripped the same way, also in custom properties (`--bg: https://cdn.example/a.png?token=1`) |
124
+ | Every other attribute (`on*` handlers, `data-*`, `srcdoc` and the rest) | Removed |
125
+ | Input events, canvas, fonts, console logs, custom and plugin events | Never recorded |
126
+
127
+ Rules that cover an element also cover its shadow DOM and the document of
128
+ a same-origin iframe it holds. A mask on a shadow host masks the shadow
129
+ content, even an element inside it that the unmask list names.
130
+
131
+ ### Unmasking
132
+
133
+ The unmask list, `privacy.unmask`, is empty by default and is set in code
134
+ only. Markup alone never unmasks: an element with `data-o11y-unmask` stays
135
+ masked unless the code lists `"[data-o11y-unmask]"`. Precedence is block,
136
+ then mask, then unmask, then the default mask.
137
+
138
+ ```ts
139
+ import type { ReplayOptions } from "@libo11y/rum-replay";
140
+
141
+ const options: ReplayOptions = {
142
+ privacy: {
143
+ unmask: [".public", "[data-o11y-unmask]"],
144
+ mask: [".price"],
145
+ block: [".chat-widget"],
146
+ },
147
+ };
148
+ ```
149
+
150
+ Text the app shows the user can still be personal data. Unmask only parts
151
+ of the page that never show it.
152
+
153
+ ### What masking does not cover
154
+
155
+ Some things the page shows are kept because replay needs them to draw the
156
+ page. Block the parts of a page where they carry personal data:
157
+
158
+ - **SVG geometry** (`d`, `points`, `transform`) is kept, so icons render. A
159
+ signature pad or a drawing that renders to SVG records what the user drew.
160
+ Block it.
161
+ - **CSS** is kept with its URLs stripped. A stylesheet or a `style`
162
+ attribute that holds personal data in a string that is not a URL, such
163
+ as a custom property, keeps it. A bare URL is found where a value or a
164
+ word in it starts. One written right after other punctuation
165
+ (`--x:=/a?token=1`), behind an escaped property name, or with a scheme
166
+ outside the web ones (`ssh:`) keeps its query.
167
+ - **URL paths** are kept. Only the query and fragment are stripped, so a
168
+ path that holds an email address or an account number keeps it.
169
+ - **`id`, `class` and `name`** are kept.
170
+
171
+ ## Remote configuration
172
+
173
+ The gateway's configuration document may carry a `replay` object. Remote
174
+ configuration can only make replay stricter:
175
+
176
+ | Field | Effect |
177
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
178
+ | `enabled: false` | Switches replay off. `true` is ignored |
179
+ | `onRetain: false` | Switches the lead-up buffer off. `true` is ignored |
180
+ | `sampleRate` | Lowers the sample rate, never below the minimum of `limits.sampleRate` set in code and never above the code rate. The default limits are `[sampleRate, sampleRate]`, which allow no change |
181
+ | `mask`, `block` | Selectors added after the fixed and code ones, which stay |
182
+ | `unmask` | Intersected with the code list, so it can only remove selectors |
183
+
184
+ A selector that does not parse is dropped, and so is any field not in the
185
+ table.
186
+
187
+ ## Reading recordings back
188
+
189
+ The gateway serves stored segments on an internal read API, behind a
190
+ bearer token, for a player backend to call server side, and erases a
191
+ session on request. See
192
+ [The read API and erasure](../../../go/o11yrum/README.md#the-read-api-and-erasure).
193
+ A stored segment is the uploaded envelope after the gateway's own
194
+ scrubbing, with `service`, `session`, `segment`, `stored_at` and
195
+ `clock_offset_ms` added. Its `events` replay with
196
+ [`@rrweb/replay`](https://www.npmjs.com/package/@rrweb/replay) 2.2.2, and
197
+ each segment replays on its own because it starts with a full snapshot.
198
+ `make rum-e2e` proves the whole path in Chromium: it records a session,
199
+ stores it through a gateway built from the checkout, reads it back with a
200
+ token, replays it, and erases it.
201
+
202
+ ## Budgets
203
+
204
+ - **Size.** `replay()` adds at most 11,264 bytes, gzipped, to the page's
205
+ initial bundle over `setupRum`. The lazily loaded recorder chunk is at
206
+ most 26,368 bytes gzipped. `make ts-size` checks both against
207
+ `ts/size-budget.json`.
208
+ - **Main-thread time.** The `ts-bench` workflow measures what replay adds
209
+ over RUM alone, with default options, in Chromium: at most 12 ms of
210
+ main-thread task time per soft navigation and 4 ms per click, on a page
211
+ that swaps 200 nodes per navigation and updates 50 per click. See the
212
+ overhead benchmark in
213
+ [CONVENTIONS.md](../../../docs/CONVENTIONS.md).
@@ -0,0 +1,34 @@
1
+ import type { ReplayPolicy } from "./policy.ts";
2
+ /** The replay object of a remote configuration document, after parseReplayRemote. */
3
+ export interface ReplayRemote {
4
+ readonly enabled?: false;
5
+ readonly sampleRate?: number;
6
+ readonly onRetain?: false;
7
+ readonly mask?: readonly string[];
8
+ readonly block?: readonly string[];
9
+ readonly unmask?: readonly string[];
10
+ }
11
+ /** Replay's settings: from code, then clamped by remote configuration. */
12
+ export interface ReplaySettings {
13
+ readonly enabled: boolean;
14
+ readonly sampleRate: number;
15
+ readonly onRetain: boolean;
16
+ readonly policy: ReplayPolicy;
17
+ }
18
+ /**
19
+ * The replay object of a remote configuration document with everything that could loosen replay
20
+ * removed, or undefined when value is not an object. validSelector says whether a CSS selector
21
+ * parses; in a browser the collector passes one that tries document.createDocumentFragment().querySelector.
22
+ */
23
+ export declare function parseReplayRemote(value: unknown, validSelector: (s: string) => boolean): ReplayRemote | undefined;
24
+ /**
25
+ * The range remote configuration may move the replay sample rate within. The default is
26
+ * [rate, rate]: no change. Throws O11yError INVALID_OPTION unless 0 <= min <= rate <= max <= 1.
27
+ * Remote configuration only ever lowers the rate, so min is the bound that matters: clampReplay
28
+ * never goes above the code rate, whatever max says.
29
+ */
30
+ export declare function resolveReplayLimits(rate: number, limits: {
31
+ readonly sampleRate?: readonly [min: number, max: number];
32
+ } | undefined): readonly [min: number, max: number];
33
+ /** code tightened by remote within limits. See the file comment. */
34
+ export declare function clampReplay(code: ReplaySettings, limits: readonly [min: number, max: number], remote: ReplayRemote | undefined): ReplaySettings;
package/dist/clamp.js ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Remote configuration of replay (design decision P3). The gateway's configuration document (R3d's
3
+ * GET /_o11y/v1/config) may carry an optional replay object:
4
+ * { enabled?: false, sampleRate?: number, onRetain?: false, mask?: string[], block?: string[], unmask?: string[] }.
5
+ *
6
+ * Remote configuration can only make replay stricter:
7
+ * - enabled and onRetain are honoured only as false: they switch replay or the lead-up buffer off,
8
+ * never on.
9
+ * - sampleRate can only lower the rate: down to the minimum of the limits code sets (default
10
+ * [rate, rate], no change), never above the code rate.
11
+ * - mask and block selectors are added after the fixed and code ones, which stay.
12
+ * - unmask is intersected with the code list, so it can only remove selectors. It can never add one.
13
+ * - A selector that is not a string, is empty or fails validSelector is dropped, and so is every
14
+ * unknown field.
15
+ *
16
+ * The clamped settings are pinned for the session by the collector, like the rest of R3d's
17
+ * document.
18
+ */
19
+ import { O11yError } from "@libo11y/core";
20
+ function isObject(v) {
21
+ return typeof v === "object" && v !== null && !Array.isArray(v);
22
+ }
23
+ function selectorList(v, validSelector) {
24
+ if (!Array.isArray(v))
25
+ return undefined;
26
+ return v.filter((s) => {
27
+ if (typeof s !== "string" || s.trim() === "")
28
+ return false;
29
+ try {
30
+ return validSelector(s);
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ });
36
+ }
37
+ /**
38
+ * The replay object of a remote configuration document with everything that could loosen replay
39
+ * removed, or undefined when value is not an object. validSelector says whether a CSS selector
40
+ * parses; in a browser the collector passes one that tries document.createDocumentFragment().querySelector.
41
+ */
42
+ export function parseReplayRemote(value, validSelector) {
43
+ if (!isObject(value))
44
+ return undefined;
45
+ const rate = value.sampleRate;
46
+ const mask = selectorList(value.mask, validSelector);
47
+ const block = selectorList(value.block, validSelector);
48
+ const unmask = selectorList(value.unmask, validSelector);
49
+ return {
50
+ ...(value.enabled === false ? { enabled: false } : {}),
51
+ ...(typeof rate === "number" && rate >= 0 && rate <= 1 ? { sampleRate: rate } : {}),
52
+ ...(value.onRetain === false ? { onRetain: false } : {}),
53
+ ...(mask === undefined ? {} : { mask }),
54
+ ...(block === undefined ? {} : { block }),
55
+ ...(unmask === undefined ? {} : { unmask }),
56
+ };
57
+ }
58
+ /**
59
+ * The range remote configuration may move the replay sample rate within. The default is
60
+ * [rate, rate]: no change. Throws O11yError INVALID_OPTION unless 0 <= min <= rate <= max <= 1.
61
+ * Remote configuration only ever lowers the rate, so min is the bound that matters: clampReplay
62
+ * never goes above the code rate, whatever max says.
63
+ */
64
+ export function resolveReplayLimits(rate, limits) {
65
+ const range = limits?.sampleRate;
66
+ if (range === undefined)
67
+ return [rate, rate];
68
+ const [min, max] = range;
69
+ if (!(min >= 0 && min <= rate && rate <= max && max <= 1)) {
70
+ throw new O11yError("INVALID_OPTION", "replay limits.sampleRate must satisfy 0 <= min <= sampleRate <= max <= 1");
71
+ }
72
+ return [min, max];
73
+ }
74
+ function append(base, extra) {
75
+ const out = [...base];
76
+ for (const s of extra ?? [])
77
+ if (!out.includes(s))
78
+ out.push(s);
79
+ return Object.freeze(out);
80
+ }
81
+ /** code tightened by remote within limits. See the file comment. */
82
+ export function clampReplay(code, limits, remote) {
83
+ if (remote === undefined)
84
+ return code;
85
+ // Remote configuration only lowers the rate: never above the code rate, never below min.
86
+ const hi = Math.min(limits[1], code.sampleRate);
87
+ const lo = Math.min(limits[0], hi);
88
+ const unmask = remote.unmask;
89
+ return Object.freeze({
90
+ enabled: code.enabled && remote.enabled !== false,
91
+ onRetain: code.onRetain && remote.onRetain !== false,
92
+ sampleRate: remote.sampleRate === undefined ? code.sampleRate : Math.min(Math.max(remote.sampleRate, lo), hi),
93
+ policy: Object.freeze({
94
+ unmask: unmask === undefined
95
+ ? code.policy.unmask
96
+ : Object.freeze(code.policy.unmask.filter((s) => unmask.includes(s))),
97
+ mask: append(code.policy.mask, remote.mask),
98
+ block: append(code.policy.block, remote.block),
99
+ queryAllowList: code.policy.queryAllowList,
100
+ }),
101
+ });
102
+ }
@@ -0,0 +1,51 @@
1
+ import type { RumCollector } from "@libo11y/rum";
2
+ import type { ReplayOptions } from "./options.ts";
3
+ import { type LoadRecorder } from "./recorder.ts";
4
+ import { type LockManagerLike } from "./sequence.ts";
5
+ /** Closed segments an unkept session keeps in memory, besides the open one. */
6
+ export declare const LEAD_UP_SEGMENTS = 2;
7
+ export declare const SEGMENT_MAX_MILLIS = 30000;
8
+ export declare const SEGMENT_MAX_BYTES = 1048576;
9
+ /** Well under the gateway's default replay.max_events of 20000. */
10
+ export declare const SEGMENT_MAX_EVENTS = 10000;
11
+ export declare const SEGMENT_MAX_REQUESTS = 200;
12
+ export declare const UPLOAD_MAX_QUEUE = 4;
13
+ export declare const UPLOAD_MAX_QUEUE_BYTES = 4194304;
14
+ type Timers = {
15
+ setTimeout(fn: () => void, ms: number): unknown;
16
+ clearTimeout(h: unknown): void;
17
+ };
18
+ /** What replay runs on. Internal: the unit tests replace parts of it. */
19
+ export interface ReplayDeps {
20
+ /** rrweb's recorder, loaded on first use: the recorder itself once loaded, else the load. */
21
+ readonly loadRecorder: LoadRecorder;
22
+ readonly fetch: typeof fetch | undefined;
23
+ readonly locks: LockManagerLike | undefined;
24
+ readonly storage: Pick<Storage, "getItem" | "setItem" | "removeItem"> | undefined;
25
+ readonly timers: Timers;
26
+ /** Epoch milliseconds. */
27
+ readonly now: () => number;
28
+ /** CompressionStream exists. */
29
+ readonly compression: boolean;
30
+ /** The page is an extension content script. */
31
+ readonly contentScript: boolean;
32
+ /** The page URL, the base of the default endpoint. */
33
+ readonly location: string;
34
+ /** Whether a CSS selector parses. */
35
+ readonly validSelector: (s: string) => boolean;
36
+ /** A new recording ID. */
37
+ readonly recordingId: () => string;
38
+ readonly warn: (message: string) => void;
39
+ }
40
+ /** The real dependencies of a page, read when the collector starts. */
41
+ export declare function defaultReplayDeps(): ReplayDeps;
42
+ /** replay over deps. Internal: the seam the unit tests use. Throws O11yError INVALID_OPTION for invalid options. */
43
+ export declare function replayWith(deps: ReplayDeps | (() => ReplayDeps), options?: ReplayOptions): RumCollector;
44
+ /**
45
+ * Session replay for `@libo11y/rum`: records the page with rrweb at its strictest, scrubs every event
46
+ * against libo11y's privacy rules before it is kept, and uploads self-contained segments of kept
47
+ * sessions to the gateway. Text is masked unless privacy.unmask lists it; input values and
48
+ * editable content are never recorded. Throws O11yError INVALID_OPTION for invalid options.
49
+ */
50
+ export declare function replay(options?: ReplayOptions): RumCollector;
51
+ export {};