Add rrweb-based session recording feature.
Implements full session recording with rrweb for DOM capture and rrweb-player for playback. Includes: Prisma schema for SessionRecording model, chunked gzip-compressed storage, recorder script built via Rollup, collection API endpoint, recordings list/playback UI pages, website recording settings, and cascade delete support. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
b9eb5f9800
commit
72b5c658e2
36 files changed
+1131
-21
No files matched your search
@@ -0,0 +1,104 @@
|
||||
import { gzipSync } from 'node:zlib';
|
||||
import { isbot } from 'isbot';
|
||||
import { serializeError } from 'serialize-error';
|
||||
import { z } from 'zod';
|
||||
import { secret } from '@/lib/crypto';
|
||||
import { getClientInfo, hasBlockedIp } from '@/lib/detect';
|
||||
import { parseToken } from '@/lib/jwt';
|
||||
import { parseRequest } from '@/lib/request';
|
||||
import { badRequest, forbidden, json, serverError } from '@/lib/response';
|
||||
import { getWebsite } from '@/queries/prisma';
|
||||
import { saveRecordingChunk } from '@/queries/sql';
|
||||
|
||||
const schema = z.object({
|
||||
website: z.uuid(),
|
||||
events: z.array(z.any()).max(200),
|
||||
timestamp: z.coerce.number().int().optional(),
|
||||
});
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const { body, error } = await parseRequest(request, schema, { skipAuth: true });
|
||||
|
||||
if (error) {
|
||||
return error();
|
||||
}
|
||||
|
||||
const { website: websiteId, events, timestamp } = body;
|
||||
|
||||
if (!events?.length) {
|
||||
return json({ ok: true });
|
||||
}
|
||||
|
||||
// Parse cache token to get session info
|
||||
const cacheHeader = request.headers.get('x-umami-cache');
|
||||
|
||||
if (!cacheHeader) {
|
||||
return badRequest({ message: 'Missing session token.' });
|
||||
}
|
||||
|
||||
const cache = await parseToken(cacheHeader, secret());
|
||||
|
||||
if (!cache || !cache.sessionId) {
|
||||
return badRequest({ message: 'Invalid session token.' });
|
||||
}
|
||||
|
||||
const { sessionId } = cache;
|
||||
|
||||
// Query directly to avoid stale Redis cache for recordingEnabled
|
||||
const website = await getWebsite(websiteId);
|
||||
|
||||
if (!website) {
|
||||
return badRequest({ message: 'Website not found.' });
|
||||
}
|
||||
|
||||
if (!website.recordingEnabled) {
|
||||
return json({ ok: false, reason: 'recording_disabled' });
|
||||
}
|
||||
|
||||
// Client info for bot/IP checks
|
||||
const { ip, userAgent } = await getClientInfo(request, {});
|
||||
|
||||
if (!process.env.DISABLE_BOT_CHECK && isbot(userAgent)) {
|
||||
return json({ beep: 'boop' });
|
||||
}
|
||||
|
||||
if (hasBlockedIp(ip)) {
|
||||
return forbidden();
|
||||
}
|
||||
|
||||
// Compute timestamps from events
|
||||
const eventTimestamps = events
|
||||
.map((e: any) => e.timestamp)
|
||||
.filter((t: any) => typeof t === 'number');
|
||||
|
||||
const startedAt = new Date(Math.min(...eventTimestamps));
|
||||
const endedAt = new Date(Math.max(...eventTimestamps));
|
||||
|
||||
// Compress events
|
||||
const eventsJson = JSON.stringify(events);
|
||||
const compressed = gzipSync(Buffer.from(eventsJson, 'utf-8'));
|
||||
|
||||
// Use timestamp-based chunk index for ordering
|
||||
const chunkIndex = timestamp || Math.floor(Date.now() / 1000);
|
||||
|
||||
await saveRecordingChunk({
|
||||
websiteId,
|
||||
sessionId,
|
||||
chunkIndex,
|
||||
events: compressed,
|
||||
eventCount: events.length,
|
||||
startedAt,
|
||||
endedAt,
|
||||
});
|
||||
|
||||
return json({ ok: true });
|
||||
} catch (e) {
|
||||
const error = serializeError(e);
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(error);
|
||||
|
||||
return serverError({ errorObject: error });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { gunzipSync } from 'node:zlib';
|
||||
import { parseRequest } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import { getRecordingChunks } from '@/queries/sql';
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ websiteId: string; sessionId: string }> },
|
||||
) {
|
||||
const { auth, error } = await parseRequest(request);
|
||||
|
||||
if (error) {
|
||||
return error();
|
||||
}
|
||||
|
||||
const { websiteId, sessionId } = await params;
|
||||
|
||||
if (!(await canViewWebsite(auth, websiteId))) {
|
||||
return unauthorized();
|
||||
}
|
||||
|
||||
const chunks = await getRecordingChunks(websiteId, sessionId);
|
||||
|
||||
// Decompress and concatenate all chunks
|
||||
const allEvents = chunks.flatMap(chunk => {
|
||||
const decompressed = gunzipSync(Buffer.from(chunk.events));
|
||||
return JSON.parse(decompressed.toString('utf-8'));
|
||||
});
|
||||
|
||||
const startedAt = chunks.length > 0 ? chunks[0].startedAt : null;
|
||||
const endedAt = chunks.length > 0 ? chunks[chunks.length - 1].endedAt : null;
|
||||
|
||||
return json({
|
||||
events: allEvents,
|
||||
startedAt,
|
||||
endedAt,
|
||||
eventCount: allEvents.length,
|
||||
chunkCount: chunks.length,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { z } from 'zod';
|
||||
import { getQueryFilters, parseRequest } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { dateRangeParams, pagingParams, searchParams } from '@/lib/schema';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import { getSessionRecordings } from '@/queries/sql';
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ websiteId: string }> },
|
||||
) {
|
||||
const schema = z.object({
|
||||
...dateRangeParams,
|
||||
...pagingParams,
|
||||
...searchParams,
|
||||
});
|
||||
|
||||
const { auth, query, error } = await parseRequest(request, schema);
|
||||
|
||||
if (error) {
|
||||
return error();
|
||||
}
|
||||
|
||||
const { websiteId } = await params;
|
||||
|
||||
if (!(await canViewWebsite(auth, websiteId))) {
|
||||
return unauthorized();
|
||||
}
|
||||
|
||||
const filters = await getQueryFilters(query, websiteId);
|
||||
|
||||
const data = await getSessionRecordings(websiteId, filters);
|
||||
|
||||
return json(data);
|
||||
}
|
||||
@@ -42,6 +42,17 @@ export async function POST(
|
||||
name: z.string().optional(),
|
||||
domain: z.string().optional(),
|
||||
shareId: z.string().max(50).nullable().optional(),
|
||||
recordingEnabled: z.boolean().optional(),
|
||||
recordingConfig: z
|
||||
.object({
|
||||
sampleRate: z.number().min(0).max(1).optional(),
|
||||
maskLevel: z.enum(['strict', 'moderate', 'relaxed']).optional(),
|
||||
maxDuration: z.number().int().positive().optional(),
|
||||
blockSelector: z.string().optional(),
|
||||
retentionDays: z.number().int().positive().optional(),
|
||||
})
|
||||
.nullable()
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const { auth, body, error } = await parseRequest(request, schema);
|
||||
@@ -51,14 +62,19 @@ export async function POST(
|
||||
}
|
||||
|
||||
const { websiteId } = await params;
|
||||
const { name, domain, shareId } = body;
|
||||
const { name, domain, shareId, recordingEnabled, recordingConfig } = body;
|
||||
|
||||
if (!(await canUpdateWebsite(auth, websiteId))) {
|
||||
return unauthorized();
|
||||
}
|
||||
|
||||
try {
|
||||
const website = await updateWebsite(websiteId, { name, domain });
|
||||
const website = await updateWebsite(websiteId, {
|
||||
name,
|
||||
domain,
|
||||
...(recordingEnabled !== undefined && { recordingEnabled }),
|
||||
...(recordingConfig !== undefined && { recordingConfig }),
|
||||
});
|
||||
|
||||
if (shareId === null) {
|
||||
await deleteSharesByEntityId(website.id);
|
||||
|
||||
Reference in new issue
Block a user