@spectosh/browser 0.1.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.
- package/README.md +30 -0
- package/dist/specto-browser.cjs +134 -0
- package/dist/specto-browser.js +7413 -0
- package/package.json +32 -0
- package/src/index.js +20 -0
- package/src/recorder.js +261 -0
- package/src/recorder.worker.js +28 -0
package/package.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@spectosh/browser",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Specto session-replay recorder for bundler users — rrweb DOM capture, console/network/error/rage signals, privacy-masked in the browser.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"publishConfig": { "access": "public" },
|
|
7
|
+
"repository": { "type": "git", "url": "git+https://github.com/evigasoft/specto.sh.git", "directory": "packages/browser" },
|
|
8
|
+
"homepage": "https://specto.sh",
|
|
9
|
+
"main": "./dist/specto-browser.cjs",
|
|
10
|
+
"module": "./dist/specto-browser.js",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"import": "./dist/specto-browser.js",
|
|
14
|
+
"require": "./dist/specto-browser.cjs"
|
|
15
|
+
},
|
|
16
|
+
"./recorder": "./src/recorder.js",
|
|
17
|
+
"./recorder-worker": "./src/recorder.worker.js"
|
|
18
|
+
},
|
|
19
|
+
"files": ["dist", "src", "README.md"],
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "vite build -c vite.config.js"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"rrweb": "^2.0.1"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"vite": "^8.1.0"
|
|
29
|
+
},
|
|
30
|
+
"keywords": ["session-replay", "rrweb", "analytics", "self-hosted"],
|
|
31
|
+
"license": "MIT"
|
|
32
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// @spectosh/browser — the recorder for bundler users. Same capture engine as
|
|
2
|
+
// the script-tag snippet; you control when it starts.
|
|
3
|
+
//
|
|
4
|
+
// import { startRecording } from '@spectosh/browser'
|
|
5
|
+
// const rec = startRecording({
|
|
6
|
+
// key: 'pk_your_key',
|
|
7
|
+
// endpoint: 'https://your-specto-host/api/ingest',
|
|
8
|
+
// privacy: 'strict', // optional
|
|
9
|
+
// })
|
|
10
|
+
// rec.stop() // later
|
|
11
|
+
import { startRecording as start } from './recorder.js'
|
|
12
|
+
import RecorderWorker from './recorder.worker.js?worker&inline'
|
|
13
|
+
|
|
14
|
+
export function startRecording(opts = {}) {
|
|
15
|
+
if (!opts.endpoint) throw new Error('@spectosh/browser: opts.endpoint is required (https://<your-specto-host>/api/ingest)')
|
|
16
|
+
if (!opts.key) throw new Error('@spectosh/browser: opts.key is required (your publishable pk_… key)')
|
|
17
|
+
return start({ createWorker: () => new RecorderWorker(), ...opts })
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export default { startRecording }
|
package/src/recorder.js
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
// Specto recorder SDK (first slice).
|
|
2
|
+
//
|
|
3
|
+
// Captures, in one correlated stream:
|
|
4
|
+
// - DOM: rrweb full snapshot + incremental mutations
|
|
5
|
+
// - console: log/info/warn/error
|
|
6
|
+
// - network: fetch + XHR (method, url, status, duration)
|
|
7
|
+
// - events: JS errors, rage clicks
|
|
8
|
+
//
|
|
9
|
+
// Privacy-first: rrweb masks ALL inputs by default; add class `specto-mask`
|
|
10
|
+
// to mask text, `specto-block` to drop an element entirely. (Production turns
|
|
11
|
+
// on maskAllText + attribute scrubbing — see SECURITY.md / the plan.)
|
|
12
|
+
//
|
|
13
|
+
// Batches every 2s and on pagehide (sendBeacon), POSTing to /api/ingest with
|
|
14
|
+
// the publishable write key. Honors Global Privacy Control / DNT.
|
|
15
|
+
import { record } from 'rrweb'
|
|
16
|
+
|
|
17
|
+
const DEFAULT_KEY = 'pk_acme_8f2a91c4'
|
|
18
|
+
|
|
19
|
+
// Attribute scrubbing — rrweb masks text/inputs but NOT element attributes,
|
|
20
|
+
// which routinely carry PII (data-*, title, alt, placeholder, aria-label).
|
|
21
|
+
// We rewrite them to '***' in the serialized node tree before upload, so the
|
|
22
|
+
// PII never leaves the browser. This is the gap most replay tools leave open.
|
|
23
|
+
const SENSITIVE_ATTR = (k) => {
|
|
24
|
+
k = k.toLowerCase()
|
|
25
|
+
return k.startsWith('data-') || k === 'title' || k === 'alt' || k === 'placeholder' || k === 'aria-label'
|
|
26
|
+
}
|
|
27
|
+
function scrubAttrMap(attrs) {
|
|
28
|
+
if (!attrs || typeof attrs !== 'object') return
|
|
29
|
+
for (const k of Object.keys(attrs)) {
|
|
30
|
+
if (SENSITIVE_ATTR(k) && typeof attrs[k] === 'string' && attrs[k]) attrs[k] = '***'
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
function scrubNode(n) {
|
|
34
|
+
if (!n || typeof n !== 'object') return
|
|
35
|
+
if (n.attributes) scrubAttrMap(n.attributes)
|
|
36
|
+
if (Array.isArray(n.childNodes)) n.childNodes.forEach(scrubNode)
|
|
37
|
+
}
|
|
38
|
+
function scrubEvent(e) {
|
|
39
|
+
try {
|
|
40
|
+
if (e.type === 2 && e.data?.node) scrubNode(e.data.node) // FullSnapshot
|
|
41
|
+
else if (e.type === 3 && e.data) { // IncrementalSnapshot (mutations)
|
|
42
|
+
if (Array.isArray(e.data.adds)) e.data.adds.forEach((a) => scrubNode(a.node))
|
|
43
|
+
if (Array.isArray(e.data.attributes)) e.data.attributes.forEach((a) => scrubAttrMap(a.attributes))
|
|
44
|
+
}
|
|
45
|
+
} catch { /* never break capture */ }
|
|
46
|
+
return e
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function newId(prefix = 'rec_') {
|
|
50
|
+
const r = (typeof crypto !== 'undefined' && crypto.getRandomValues)
|
|
51
|
+
? Array.from(crypto.getRandomValues(new Uint8Array(8))).map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
52
|
+
: Math.abs((Date.now() ^ (performance.now() * 1000)) | 0).toString(16)
|
|
53
|
+
return prefix + r
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// stable anonymous visitor id (per browser, per site) — powers retention
|
|
57
|
+
// cohorts. No fingerprinting: just a random id in localStorage.
|
|
58
|
+
function visitorId() {
|
|
59
|
+
try {
|
|
60
|
+
let v = localStorage.getItem('specto-vid')
|
|
61
|
+
if (!v) { v = newId('v_'); localStorage.setItem('specto-vid', v) }
|
|
62
|
+
return v
|
|
63
|
+
} catch { return undefined }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function startRecording(opts = {}) {
|
|
67
|
+
const endpoint = opts.endpoint || '/api/ingest'
|
|
68
|
+
const key = opts.key || DEFAULT_KEY
|
|
69
|
+
const sessionId = opts.sessionId || newId()
|
|
70
|
+
const onUpdate = opts.onUpdate || (() => {})
|
|
71
|
+
|
|
72
|
+
// idempotency: never run two recorders (and two upload workers) at once
|
|
73
|
+
if (typeof window !== 'undefined' && window.__spectoRec) return window.__spectoRec
|
|
74
|
+
|
|
75
|
+
// respect Do-Not-Track / Global Privacy Control
|
|
76
|
+
if (navigator.doNotTrack === '1' || navigator.globalPrivacyControl) {
|
|
77
|
+
return { sessionId, stop() {}, count: () => 0, disabled: true }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
let buffer = []
|
|
81
|
+
let total = 0
|
|
82
|
+
const startedAt = new Date().toISOString()
|
|
83
|
+
const t0 = performance.now()
|
|
84
|
+
const rel = () => Math.round(performance.now() - t0)
|
|
85
|
+
|
|
86
|
+
const push = (kind, payload) => {
|
|
87
|
+
buffer.push({ kind, payload })
|
|
88
|
+
total++
|
|
89
|
+
onUpdate({ total, kind })
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// ---- DOM via rrweb ----
|
|
93
|
+
// Privacy: inputs are ALWAYS masked. privacy:'strict' additionally masks all
|
|
94
|
+
// text nodes (maskTextSelector '*') for maximum redaction. Default 'balanced'
|
|
95
|
+
// keeps text visible (mask via class `specto-mask`, drop via `specto-block`).
|
|
96
|
+
const strict = opts.privacy === 'strict'
|
|
97
|
+
const stopDom = record({
|
|
98
|
+
emit: (e) => push('dom', scrubEvent(e)),
|
|
99
|
+
maskAllInputs: true,
|
|
100
|
+
maskInputOptions: { password: true, email: true, tel: true, color: false },
|
|
101
|
+
maskTextClass: 'specto-mask',
|
|
102
|
+
maskTextSelector: strict ? '*' : undefined,
|
|
103
|
+
blockClass: 'specto-block',
|
|
104
|
+
recordCanvas: false,
|
|
105
|
+
collectFonts: false,
|
|
106
|
+
sampling: { mousemove: 50, scroll: 150, input: 'last' },
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
// ---- console ----
|
|
110
|
+
const origConsole = {}
|
|
111
|
+
for (const level of ['log', 'info', 'warn', 'error']) {
|
|
112
|
+
origConsole[level] = console[level]
|
|
113
|
+
console[level] = (...args) => {
|
|
114
|
+
try {
|
|
115
|
+
push('console', { t: rel(), level, text: args.map(fmt).join(' ').slice(0, 2000) })
|
|
116
|
+
} catch { /* never break the app */ }
|
|
117
|
+
origConsole[level].apply(console, args)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// ---- network: fetch ----
|
|
122
|
+
const origFetch = window.fetch
|
|
123
|
+
window.fetch = async (...args) => {
|
|
124
|
+
const started = performance.now()
|
|
125
|
+
const url = typeof args[0] === 'string' ? args[0] : args[0]?.url || ''
|
|
126
|
+
const method = (args[1]?.method || (typeof args[0] !== 'string' && args[0]?.method) || 'GET').toUpperCase()
|
|
127
|
+
try {
|
|
128
|
+
const res = await origFetch.apply(window, args)
|
|
129
|
+
let traceId
|
|
130
|
+
try { traceId = res.headers.get('x-trace-id') || undefined } catch { /* opaque */ }
|
|
131
|
+
push('network', { t: rel(), method, url: String(url).slice(0, 300), status: res.status, dur: Math.round(performance.now() - started), ...(traceId ? { traceId } : {}) })
|
|
132
|
+
return res
|
|
133
|
+
} catch (err) {
|
|
134
|
+
push('network', { t: rel(), method, url: String(url).slice(0, 300), status: 0, dur: Math.round(performance.now() - started), error: true })
|
|
135
|
+
throw err
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ---- network: XHR ----
|
|
140
|
+
const XHR = window.XMLHttpRequest
|
|
141
|
+
const origOpen = XHR.prototype.open
|
|
142
|
+
const origSend = XHR.prototype.send
|
|
143
|
+
XHR.prototype.open = function (method, url) { this.__specto = { method: String(method).toUpperCase(), url: String(url).slice(0, 300), started: 0 }; return origOpen.apply(this, arguments) }
|
|
144
|
+
XHR.prototype.send = function () {
|
|
145
|
+
if (this.__specto) {
|
|
146
|
+
this.__specto.started = performance.now()
|
|
147
|
+
this.addEventListener('loadend', () => {
|
|
148
|
+
const m = this.__specto
|
|
149
|
+
let traceId
|
|
150
|
+
try { traceId = this.getResponseHeader('x-trace-id') || undefined } catch { /* ignore */ }
|
|
151
|
+
push('network', { t: rel(), method: m.method, url: m.url, status: this.status, dur: Math.round(performance.now() - m.started), ...(traceId ? { traceId } : {}) })
|
|
152
|
+
})
|
|
153
|
+
}
|
|
154
|
+
return origSend.apply(this, arguments)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// ---- JS errors ----
|
|
158
|
+
const onError = (e) => push('event', { t: rel(), type: 'error', message: String(e.message || e.reason || 'error').slice(0, 500) })
|
|
159
|
+
window.addEventListener('error', onError)
|
|
160
|
+
window.addEventListener('unhandledrejection', onError)
|
|
161
|
+
|
|
162
|
+
// ---- SPA navigations (history API + hash) — powers funnels/paths ----
|
|
163
|
+
const pushNav = () => push('event', { t: rel(), type: 'nav', path: (location.pathname + location.hash).slice(0, 300) })
|
|
164
|
+
const origPush = history.pushState, origReplace = history.replaceState
|
|
165
|
+
history.pushState = function (...a) { const r = origPush.apply(this, a); try { pushNav() } catch { /* never break nav */ } return r }
|
|
166
|
+
history.replaceState = function (...a) { const r = origReplace.apply(this, a); try { pushNav() } catch { /* never break nav */ } return r }
|
|
167
|
+
window.addEventListener('popstate', pushNav)
|
|
168
|
+
window.addEventListener('hashchange', pushNav)
|
|
169
|
+
|
|
170
|
+
// ---- rage clicks (>=3 clicks within 800ms near same spot) ----
|
|
171
|
+
let clicks = []
|
|
172
|
+
const onClick = (e) => {
|
|
173
|
+
const now = performance.now()
|
|
174
|
+
clicks = clicks.filter((c) => now - c.t < 800)
|
|
175
|
+
clicks.push({ t: now, x: e.clientX, y: e.clientY })
|
|
176
|
+
if (clicks.length >= 3) {
|
|
177
|
+
const sel = e.target?.tagName ? e.target.tagName.toLowerCase() + (e.target.id ? '#' + e.target.id : '') : 'element'
|
|
178
|
+
push('event', { t: rel(), type: 'rage', target: sel.slice(0, 80), count: clicks.length })
|
|
179
|
+
clicks = []
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
window.addEventListener('click', onClick, true)
|
|
183
|
+
|
|
184
|
+
// ---- upload: off-main-thread serialize + gzip + POST via a Web Worker ----
|
|
185
|
+
// The main thread only buffers (cheap) and hands batches to the worker every
|
|
186
|
+
// 2s. Privacy transforms (input masking, attribute scrubbing) already ran on
|
|
187
|
+
// the main thread before events were buffered, so the worker only sees clean
|
|
188
|
+
// data. On pagehide we sendBeacon the residual directly (workers may be
|
|
189
|
+
// killed on unload), so no tail is lost.
|
|
190
|
+
const meta = { page: location.pathname, userAgent: navigator.userAgent, startedAt, visitorId: visitorId() }
|
|
191
|
+
let worker = null
|
|
192
|
+
try {
|
|
193
|
+
// Callers provide the worker factory: the app passes createDefaultWorker
|
|
194
|
+
// (worker-factory.js), the SDK/npm builds pass an inlined worker. recorder.js
|
|
195
|
+
// itself never references import.meta, so the IIFE/CJS bundles stay valid.
|
|
196
|
+
// No factory → main-thread upload (below).
|
|
197
|
+
worker = opts.createWorker ? opts.createWorker() : null
|
|
198
|
+
if (worker) worker.postMessage({ t: 'init', cfg: { endpoint, key, sessionId, meta } })
|
|
199
|
+
} catch { worker = null /* fall back to main-thread upload below */ }
|
|
200
|
+
|
|
201
|
+
async function mainUpload(batch) {
|
|
202
|
+
let gz = null
|
|
203
|
+
if (typeof CompressionStream !== 'undefined') {
|
|
204
|
+
try { gz = await new Response(new Blob([JSON.stringify({ sessionId, key, meta, events: batch })]).stream().pipeThrough(new CompressionStream('gzip'))).blob() } catch { gz = null }
|
|
205
|
+
}
|
|
206
|
+
const json = JSON.stringify({ sessionId, key, meta, events: batch })
|
|
207
|
+
await origFetch.call(window, endpoint, gz
|
|
208
|
+
? { method: 'POST', headers: { 'Content-Type': 'application/octet-stream', 'x-specto-gzip': '1' }, body: gz, keepalive: true }
|
|
209
|
+
: { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: json, keepalive: true })
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function handoff() {
|
|
213
|
+
if (!buffer.length) return
|
|
214
|
+
const batch = buffer
|
|
215
|
+
buffer = []
|
|
216
|
+
if (worker) worker.postMessage({ t: 'upload', batch })
|
|
217
|
+
else mainUpload(batch).catch(() => { buffer = batch.concat(buffer) })
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const timer = setInterval(handoff, 2000)
|
|
221
|
+
const onHide = () => {
|
|
222
|
+
handoff()
|
|
223
|
+
if (buffer.length && navigator.sendBeacon) { // residual, if any → reliable beacon
|
|
224
|
+
navigator.sendBeacon(endpoint, new Blob([JSON.stringify({ sessionId, key, meta, events: buffer })], { type: 'application/json' }))
|
|
225
|
+
buffer = []
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
window.addEventListener('pagehide', onHide)
|
|
229
|
+
|
|
230
|
+
let stopped = false
|
|
231
|
+
function stop() {
|
|
232
|
+
if (stopped) return
|
|
233
|
+
stopped = true
|
|
234
|
+
stopDom && stopDom()
|
|
235
|
+
for (const level of ['log', 'info', 'warn', 'error']) console[level] = origConsole[level]
|
|
236
|
+
window.fetch = origFetch
|
|
237
|
+
XHR.prototype.open = origOpen
|
|
238
|
+
XHR.prototype.send = origSend
|
|
239
|
+
window.removeEventListener('error', onError)
|
|
240
|
+
window.removeEventListener('unhandledrejection', onError)
|
|
241
|
+
window.removeEventListener('click', onClick, true)
|
|
242
|
+
window.removeEventListener('pagehide', onHide)
|
|
243
|
+
window.removeEventListener('popstate', pushNav)
|
|
244
|
+
window.removeEventListener('hashchange', pushNav)
|
|
245
|
+
history.pushState = origPush
|
|
246
|
+
history.replaceState = origReplace
|
|
247
|
+
clearInterval(timer)
|
|
248
|
+
handoff()
|
|
249
|
+
if (worker) setTimeout(() => worker.terminate(), 1500)
|
|
250
|
+
if (typeof window !== 'undefined' && window.__spectoRec === api) delete window.__spectoRec
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const api = { sessionId, stop, flushNow: handoff, count: () => total }
|
|
254
|
+
if (typeof window !== 'undefined') window.__spectoRec = api
|
|
255
|
+
return api
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function fmt(a) {
|
|
259
|
+
if (typeof a === 'string') return a
|
|
260
|
+
try { return JSON.stringify(a) } catch { return String(a) }
|
|
261
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Specto upload worker — runs off the main thread.
|
|
2
|
+
// Receives already-clean event batches (privacy transforms happen on the main
|
|
3
|
+
// thread before hand-off), serializes, gzip-compresses, and POSTs to /api/ingest.
|
|
4
|
+
let cfg = null
|
|
5
|
+
|
|
6
|
+
self.onmessage = (e) => {
|
|
7
|
+
const m = e.data
|
|
8
|
+
if (m.t === 'init') cfg = m.cfg
|
|
9
|
+
else if (m.t === 'upload') upload(m.batch)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
async function gzip(str) {
|
|
13
|
+
if (typeof CompressionStream === 'undefined') return null
|
|
14
|
+
try {
|
|
15
|
+
return await new Response(new Blob([str]).stream().pipeThrough(new CompressionStream('gzip'))).blob()
|
|
16
|
+
} catch { return null }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function upload(batch) {
|
|
20
|
+
if (!cfg || !batch || !batch.length) return
|
|
21
|
+
const body = JSON.stringify({ sessionId: cfg.sessionId, key: cfg.key, meta: cfg.meta, events: batch })
|
|
22
|
+
const gz = await gzip(body)
|
|
23
|
+
try {
|
|
24
|
+
await fetch(cfg.endpoint, gz
|
|
25
|
+
? { method: 'POST', headers: { 'Content-Type': 'application/octet-stream', 'x-specto-gzip': '1' }, body: gz, keepalive: true }
|
|
26
|
+
: { method: 'POST', headers: { 'Content-Type': 'application/json' }, body, keepalive: true })
|
|
27
|
+
} catch { /* periodic cadence limits loss; tail is beaconed from main thread */ }
|
|
28
|
+
}
|