Skip to navigation

Live dynamic watermark for web

Live dynamic watermark for web
Stamp each viewer's identity on a FastPix live stream with a moving, tiled watermark that detects tampering, added from the page around an unmodified fastpix-player.
1. Page head
A standard HTML5 page. The UTF-8 charset matters: the watermark label and tiling use the middle dot character, which garbles without it. The viewport meta makes the player fit phone screens.
2. How it works
3. Capturing native functions
4. Guarded functions and constants
5. Generating a session code
6. Reading the watermark attributes
7. Waiting for the player
8. Attaching to a player
9. Per-player state
10. Two layers in closed shadow roots
11. Locking the layer styles
12. Mounting the layers
13. Sizing the canvases
14. Moving the label
15. Tiling the whole frame
16. Painting video frames
17. Drawing the label
18. Blocked screen
19. The render loop
20. Events and reports
21. Enforcement
22. Detecting hidden or replaced layers
23. Detecting a resized or covered mark
24. Detecting a bypassed frame layer
25. Detecting stalls and casting
26. Checking the label pixels
27. Running the checks
28. Closing escape routes
29. Teardown and start
30. Exposing attach only
31. Loading the player
32. Page styles
33. Configuration form
34. Tamper lab and event log
35. Logging watermark events
36. Loading the player with a watermark
37. Finding the layers as an attacker would
38. The attacks
39. Running an attack
1<!DOCTYPE html>
2<html lang="en">
3
4<head>
5 <meta charset="UTF-8" />
6 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7 <title>Live dynamic watermark - FastPix Player</title>
8
9 <!--
10 ════════════════════════════════════════════════════════════════════════════
11 Dynamic watermark for live playback, implemented entirely from the page.
12 The player source is untouched: this script reaches into the player's open
13 shadow root (wrapper, <video>, hls instance, PiP/cast buttons).
14
15 It MUST be a classic, non-deferred script placed BEFORE the player script:
16 it captures native canvas/DOM functions at parse time, so anything that
17 patches them later (DevTools snippets, extensions injected after load) is
18 detected and bypassed.
19
20 Usage:
21 <fastpix-player playback-id="…" stream-type="live-stream"
22 watermark-text="viewer@example.com"></fastpix-player>
23 FastPixLiveWatermark.attach(document.querySelector("fastpix-player"));
24
25 Attributes read once at attach (later edits are tamper):
26 watermark-text required; the viewer identity (issue it server-side)
27 watermark-mode composite (default) | overlay - drm-token forces overlay
28 watermark-opacity 0.15-0.9, default 0.4
29 watermark-show-time "false" hides the UTC clock line
30 watermark-on-tamper stop (default) | report
31 watermark-report-url POST endpoint for start / tamper / prevented beacons
32
33 Events on the player (bubbling, composed):
34 fp:watermark:start {session, mode}
35 fp:watermark:tamper {reason, count, session} - mark hidden/removed/bypassed
36 fp:watermark:prevented {reason, session} - escape route refused (PiP, iOS fullscreen)
37 fp:watermark:blocked {reason, session} - playback stopped until reload
38
39 LIMITS (state these to the team): this is client-side. A viewer who patches the
40 player BEFORE it loads, or films the screen, defeats any client watermark. The
41 goal is that removal is never casual, never silent and never free. Forensic
42 pixel watermarking at the edge is the only mark a client cannot remove.
43 ════════════════════════════════════════════════════════════════════════════
44 -->
45 <script>
46 (function () {
47 "use strict";
48
49 // ── Native references, captured before any other script on the page runs ──
50 const apply = Reflect.apply;
51 const C2D = CanvasRenderingContext2D.prototype;
52 const N = {
53 fillText: C2D.fillText,
54 strokeText: C2D.strokeText,
55 drawImage: C2D.drawImage,
56 clearRect: C2D.clearRect,
57 fillRect: C2D.fillRect,
58 getImageData: C2D.getImageData,
59 measureText: C2D.measureText,
60 createPattern: C2D.createPattern,
61 getComputedStyle: window.getComputedStyle,
62 requestAnimationFrame: window.requestAnimationFrame,
63 cancelAnimationFrame: window.cancelAnimationFrame,
64 setInterval: window.setInterval,
65 clearInterval: window.clearInterval,
66 getBoundingClientRect: Element.prototype.getBoundingClientRect,
67 attachShadow: Element.prototype.attachShadow,
68 sendBeacon: Navigator.prototype.sendBeacon,
69 MutationObserver: window.MutationObserver,
70 ResizeObserver: window.ResizeObserver,
71 };
72
73 // Only the canvas draw path counts as tamper when swapped. Window-level
74 // functions (rAF, getComputedStyle) are legitimately wrapped by monitoring
75 // tools such as Sentry; the watermark simply keeps calling the originals.
76 const GUARDED = ["fillText", "strokeText", "drawImage", "clearRect", "fillRect"];
77
78 const CONFIG_ATTRS = [
79 "watermark-text", "watermark-mode", "watermark-opacity",
80 "watermark-show-time", "watermark-on-tamper", "watermark-report-url",
81 ];
82 const Z_TOP = 2147483000;
83 const CHECK_MS = 700;
84 const STALL_MS = 4000;
85 const MAX_DPR = 2;
86 const FONT = 'system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif';
87
88 const call = (fn, self, ...args) => apply(fn, self, args);
89 const css = (el) => call(N.getComputedStyle, window, el);
90 const rect = (el) => call(N.getBoundingClientRect, el);
91 const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
92 const pad = (n) => String(n).padStart(2, "0");
93 const utcClock = (d) =>
94 `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())} UTC`;
95
96 function sessionCode() {
97 const alphabet = "abcdefghjkmnpqrstuvwxyz23456789";
98 const bytes = crypto.getRandomValues(new Uint8Array(6));
99 return Array.from(bytes, (b) => alphabet[b % alphabet.length]).join("");
100 }
101
102 function readConfig(player) {
103 const text = (player.getAttribute("watermark-text") || "").trim();
104 if (!text) return null;
105 // Browsers paint EME-protected frames black to script, so DRM cannot composite.
106 const drm = Boolean(player.getAttribute("drm-token"));
107 const opacity = parseFloat(player.getAttribute("watermark-opacity"));
108 return {
109 text: text.slice(0, 120),
110 mode: drm || player.getAttribute("watermark-mode") === "overlay" ? "overlay" : "composite",
111 opacity: Number.isFinite(opacity) ? clamp(opacity, 0.15, 0.9) : 0.4,
112 showTime: player.getAttribute("watermark-show-time") !== "false",
113 onTamper: player.getAttribute("watermark-on-tamper") === "report" ? "report" : "stop",
114 reportUrl: player.getAttribute("watermark-report-url"),
115 };
116 }
117
118 // The player builds its shadow DOM asynchronously (and later still with
119 // enable-lazy-loading), so wait for the <video> and its wrapper.
120 function whenPlayerReady(player, timeoutMs = 30000) {
121 const started = performance.now();
122 return new Promise((resolve, reject) => {
123 const poll = () => {
124 const video = player.shadowRoot && player.shadowRoot.querySelector("video");
125 if (video && video.parentElement) return resolve({ video, wrapper: video.parentElement });
126 if (performance.now() - started > timeoutMs) return reject(new Error("player not ready"));
127 call(N.requestAnimationFrame, window, poll);
128 };
129 poll();
130 });
131 }
132
133 const instances = new WeakSet();
134
135 async function attach(player) {
136 if (!(player instanceof HTMLElement) || instances.has(player)) return;
137 const config = readConfig(player);
138 if (!config) throw new Error("watermark-text is required");
139 instances.add(player);
140 const { video, wrapper } = await whenPlayerReady(player);
141 createWatermark(player, wrapper, video, config);
142 }
143
144 function createWatermark(player, wrapper, video, config) {
145 const session = sessionCode();
146 const snapshot = new Map(CONFIG_ATTRS.map((a) => [a, player.getAttribute(a)]));
147 let mode = config.mode;
148 let blocked = false;
149 let blockReason = "";
150 let destroyed = false;
151 let tamperCount = 0;
152 let hasFrame = false;
153 let frameDirty = true;
154 let lastFrameTime = -1;
155 let lastDraw = performance.now();
156 let rafId = 0;
157 let checkTimer = 0;
158 let checkQueued = false;
159 // A violation is reported once, until a check passes again.
160 let activeViolation = null;
161 let probeEnabled = true;
162 let videoFit = "contain";
163 let dpr = 1;
164 let tile = null;
165 let label = { x: 0, y: 0, w: 0, h: 0 };
166
167 // ── Two layers, each a canvas inside a CLOSED shadow root ──────────────
168 // frame layer: directly above the <video>, below controls and subtitles.
169 // Composite mode paints the video frames here and makes the
170 // raw <video> invisible, so hiding this layer hides the picture.
171 // mark layer: top of the player, transparent, carries the moving label and
172 // the tiled pattern. Present in both modes.
173 function makeLayer() {
174 const host = document.createElement("div");
175 host.setAttribute("aria-hidden", "true");
176 const root = call(N.attachShadow, host, { mode: "closed" });
177 const canvas = document.createElement("canvas");
178 root.appendChild(canvas);
179 return { host, root, canvas, ctx: canvas.getContext("2d") };
180 }
181 const mark = makeLayer();
182 const frame = mode === "composite" ? makeLayer() : null;
183
184 const baseHost = [
185 ["position", "absolute"], ["inset", "0"], ["width", "100%"], ["height", "100%"],
186 ["display", "block"], ["visibility", "visible"], ["opacity", "1"],
187 ["pointer-events", "none"], ["overflow", "hidden"],
188 ["border-radius", "var(--player-border-radius)"],
189 ["filter", "none"], ["transform", "none"], ["clip-path", "none"],
190 ["mix-blend-mode", "normal"], ["margin", "0"],
191 ];
192 const MARK_HOST = baseHost.concat([["z-index", String(Z_TOP)]]);
193 const FRAME_HOST = baseHost.concat([["z-index", "0"]]);
194 const CANVAS = [
195 ["display", "block"], ["width", "100%"], ["height", "100%"],
196 ["visibility", "visible"], ["opacity", "1"], ["filter", "none"],
197 ["transform", "none"], ["clip-path", "none"], ["mix-blend-mode", "normal"],
198 ];
199
200 function setStyle(el, rules) {
201 el.removeAttribute("style");
202 el.removeAttribute("class");
203 el.removeAttribute("hidden");
204 for (const [p, v] of rules) el.style.setProperty(p, v, "important");
205 }
206
207 function mount() {
208 setStyle(mark.host, MARK_HOST);
209 setStyle(mark.canvas, CANVAS);
210 if (mark.canvas.parentNode !== mark.root) mark.root.appendChild(mark.canvas);
211 if (mark.host.parentNode !== wrapper) wrapper.appendChild(mark.host);
212 if (frame) {
213 setStyle(frame.host, FRAME_HOST);
214 setStyle(frame.canvas, CANVAS);
215 if (frame.canvas.parentNode !== frame.root) frame.root.appendChild(frame.canvas);
216 if (frame.host.parentNode !== wrapper || frame.host.previousElementSibling !== video) {
217 wrapper.insertBefore(frame.host, video.nextSibling);
218 }
219 }
220 }
221
222 function hideVideo() {
223 video.style.setProperty("opacity", "0", "important");
224 video.style.setProperty("visibility", "visible", "important");
225 }
226 function unhideVideo() {
227 video.style.removeProperty("opacity");
228 video.style.removeProperty("visibility");
229 }
230
231 function resize() {
232 const r = rect(mark.host);
233 dpr = Math.min(window.devicePixelRatio || 1, MAX_DPR);
234 const w = Math.max(1, Math.round(r.width * dpr));
235 const h = Math.max(1, Math.round(r.height * dpr));
236 for (const layer of [mark, frame]) {
237 if (!layer) continue;
238 if (layer.canvas.width !== w || layer.canvas.height !== h) {
239 layer.canvas.width = w;
240 layer.canvas.height = h;
241 tile = null;
242 frameDirty = true;
243 // Resizing clears the canvas: the pixel check waits for the next paint.
244 label = { x: 0, y: 0, w: 0, h: 0 };
245 }
246 }
247 videoFit = css(video).objectFit || "contain";
248 }
249
250 mount();
251 const resizeObserver = new N.ResizeObserver(resize);
252 resizeObserver.observe(mark.host);
253 resize();
254
255 // ── Motion: drift + bounce, random jump every 8-20 s ──────────────────
256 // A fixed crop or blur box never covers the label for long.
257 const motion = {
258 x: Math.random(), y: Math.random(),
259 vx: (Math.random() < 0.5 ? -1 : 1) * (0.03 + Math.random() * 0.03),
260 vy: (Math.random() < 0.5 ? -1 : 1) * (0.03 + Math.random() * 0.03),
261 nextJump: performance.now() + 8000 + Math.random() * 12000,
262 last: performance.now(),
263 };
264 function step(now) {
265 const dt = Math.min(0.1, (now - motion.last) / 1000);
266 motion.last = now;
267 motion.x += motion.vx * dt;
268 motion.y += motion.vy * dt;
269 if (motion.x < 0 || motion.x > 1) { motion.vx = -motion.vx; motion.x = clamp(motion.x, 0, 1); }
270 if (motion.y < 0 || motion.y > 1) { motion.vy = -motion.vy; motion.y = clamp(motion.y, 0, 1); }
271 if (now >= motion.nextJump) {
272 motion.x = Math.random();
273 motion.y = Math.random();
274 motion.nextJump = now + 8000 + Math.random() * 12000;
275 }
276 }
277
278 // ── Drawing ───────────────────────────────────────────────────────────
279 // Faint diagonal tiling over the whole frame: survives cropping the label.
280 function buildTile() {
281 const t = document.createElement("canvas");
282 t.width = Math.round(260 * dpr);
283 t.height = Math.round(156 * dpr);
284 const tc = t.getContext("2d");
285 tc.translate(t.width / 2, t.height / 2);
286 tc.rotate(-Math.PI / 7);
287 tc.font = `500 ${Math.round(13 * dpr)}px ${FONT}`;
288 tc.textAlign = "center";
289 tc.textBaseline = "middle";
290 tc.fillStyle = "#ffffff";
291 call(N.fillText, tc, `${config.text} · ${session}`, 0, 0);
292 tile = call(N.createPattern, mark.ctx, t, "repeat");
293 }
294
295 function fitBox(cw, ch) {
296 const vw = video.videoWidth, vh = video.videoHeight;
297 if (videoFit === "fill" || !vw || !vh) return { x: 0, y: 0, w: cw, h: ch };
298 const s = videoFit === "cover" ? Math.max(cw / vw, ch / vh) : Math.min(cw / vw, ch / vh);
299 return { x: (cw - vw * s) / 2, y: (ch - vh * s) / 2, w: vw * s, h: vh * s };
300 }
301
302 // Paints a frame only when the video has a new one (or the size changed),
303 // so a stalled live stream keeps its last picture instead of going black.
304 function paintFrame() {
305 if (!frame || video.readyState < 2 || !video.videoWidth) return;
306 if (!frameDirty && video.currentTime === lastFrameTime) return;
307 const { canvas, ctx } = frame;
308 ctx.fillStyle = "#000000";
309 call(N.fillRect, ctx, 0, 0, canvas.width, canvas.height);
310 const b = fitBox(canvas.width, canvas.height);
311 call(N.drawImage, ctx, video, b.x, b.y, b.w, b.h);
312 lastFrameTime = video.currentTime;
313 frameDirty = false;
314 if (!hasFrame) {
315 hasFrame = true;
316 hideVideo();
317 }
318 }
319
320 function paintLabel() {
321 const { canvas, ctx } = mark;
322 const cw = canvas.width, ch = canvas.height;
323 const fontPx = Math.max(12 * dpr, Math.round(ch * 0.032));
324 const lines = [config.text, config.showTime ? `${utcClock(new Date())} · ${session}` : session];
325 ctx.font = `600 ${fontPx}px ${FONT}`;
326 ctx.textBaseline = "top";
327 ctx.textAlign = "left";
328 const lineH = Math.round(fontPx * 1.25);
329 const w = Math.max(...lines.map((l) => call(N.measureText, ctx, l).width));
330 const h = lineH * lines.length;
331 const x = Math.round(motion.x * Math.max(0, cw - w - fontPx) + fontPx / 2);
332 const y = Math.round(motion.y * Math.max(0, ch - h - fontPx) + fontPx / 2);
333 label = { x, y, w: Math.ceil(w), h };
334 ctx.globalAlpha = config.opacity;
335 ctx.lineJoin = "round";
336 ctx.lineWidth = Math.max(2, fontPx * 0.14);
337 ctx.strokeStyle = "rgba(0,0,0,0.55)";
338 ctx.fillStyle = "#ffffff";
339 lines.forEach((line, i) => {
340 call(N.strokeText, ctx, line, x, y + i * lineH);
341 call(N.fillText, ctx, line, x, y + i * lineH);
342 });
343 ctx.globalAlpha = 1;
344 }
345
346 function paintBlocked() {
347 const { canvas, ctx } = mark;
348 const cw = canvas.width, ch = canvas.height;
349 ctx.globalAlpha = 1;
350 ctx.fillStyle = "#000000";
351 call(N.fillRect, ctx, 0, 0, cw, ch);
352 const f = Math.max(14 * dpr, Math.round(ch * 0.045));
353 ctx.textAlign = "center";
354 ctx.textBaseline = "middle";
355 ctx.fillStyle = "#ffffff";
356 ctx.font = `600 ${f}px ${FONT}`;
357 call(N.fillText, ctx, "Playback stopped", cw / 2, ch / 2 - f);
358 ctx.fillStyle = "rgba(255,255,255,0.75)";
359 ctx.font = `400 ${Math.round(f * 0.55)}px ${FONT}`;
360 call(N.fillText, ctx, `Watermark tampering detected (${blockReason}). Reload to continue.`, cw / 2, ch / 2 + f * 0.4);
361 call(N.fillText, ctx, `Session ${session}`, cw / 2, ch / 2 + f * 1.3);
362 }
363
364 function render(now) {
365 if (destroyed) return;
366 rafId = call(N.requestAnimationFrame, window, render);
367 lastDraw = now;
368 const { canvas, ctx } = mark;
369 call(N.clearRect, ctx, 0, 0, canvas.width, canvas.height);
370 if (blocked) return paintBlocked();
371
372 step(now);
373 if (mode === "composite") {
374 try {
375 paintFrame();
376 } catch (e) {
377 // drawImage refused the video (protected or broken media):
378 // show the raw video with the overlay rather than a black frame.
379 mode = "overlay";
380 unhideVideo();
381 frame && frame.host.remove();
382 }
383 }
384 if (!tile) buildTile();
385 if (tile) {
386 ctx.globalAlpha = config.opacity * 0.3;
387 ctx.fillStyle = tile;
388 call(N.fillRect, ctx, 0, 0, canvas.width, canvas.height);
389 ctx.globalAlpha = 1;
390 }
391 paintLabel();
392 }
393
394 // ── Reporting ─────────────────────────────────────────────────────────
395 function emit(name, detail) {
396 player.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true }));
397 }
398 function report(event, reason) {
399 if (!config.reportUrl || !N.sendBeacon) return;
400 try {
401 call(N.sendBeacon, navigator, config.reportUrl, JSON.stringify({
402 event, reason, session, tamperCount,
403 playbackId: player.getAttribute("playback-id"),
404 streamType: player.getAttribute("stream-type"),
405 watermark: config.text,
406 at: new Date().toISOString(),
407 }));
408 } catch (e) { /* best effort; enforcement never depends on it */ }
409 }
410
411 // ── Enforcement ───────────────────────────────────────────────────────
412 function enforcePause() {
413 if (blocked) { try { video.pause(); } catch (e) { } }
414 }
415 function block(reason) {
416 if (blocked) return;
417 blocked = true;
418 blockReason = reason;
419 enforcePause();
420 try { player.hls && player.hls.stopLoad(); } catch (e) { }
421 emit("fp:watermark:blocked", { reason, session });
422 }
423 function restoreNatives() {
424 for (const key of GUARDED) {
425 if (C2D[key] !== N[key]) { try { C2D[key] = N[key]; } catch (e) { } }
426 }
427 }
428 function heal() {
429 restoreNatives();
430 for (const [a, v] of snapshot) {
431 if (player.getAttribute(a) === v) continue;
432 v === null ? player.removeAttribute(a) : player.setAttribute(a, v);
433 }
434 mount();
435 if (mode === "composite" && hasFrame) hideVideo();
436 video.disablePictureInPicture = true;
437 video.disableRemotePlayback = true;
438 }
439 // Hard: the mark was hidden, covered, altered or bypassed.
440 function onTamper(reason) {
441 tamperCount += 1;
442 heal();
443 emit("fp:watermark:tamper", { reason, count: tamperCount, session });
444 report("tamper", reason);
445 if (config.onTamper === "stop") block(reason);
446 }
447 // Soft: an escape route was attempted and refused; playback continues.
448 function onPrevented(reason) {
449 emit("fp:watermark:prevented", { reason, session });
450 report("prevented", reason);
451 }
452
453 // ── Integrity checks ──────────────────────────────────────────────────
454 function altered(s) {
455 return s.display === "none" ||
456 s.visibility !== "visible" ||
457 parseFloat(s.opacity) < 0.99 ||
458 s.filter !== "none" ||
459 s.transform !== "none" ||
460 s.clipPath !== "none" ||
461 s.mixBlendMode !== "normal" ||
462 (s.maskImage && s.maskImage !== "none") ||
463 (s.webkitMaskImage && s.webkitMaskImage !== "none");
464 }
465
466 function findViolation() {
467 for (const key of GUARDED) if (C2D[key] !== N[key]) return "native_patched";
468 for (const [a, v] of snapshot) if (player.getAttribute(a) !== v) return "config_changed";
469
470 if (video.parentElement !== wrapper) return "video_moved";
471 if (!mark.host.isConnected || mark.host.parentNode !== wrapper) return "mark_removed";
472 if (mark.canvas.parentNode !== mark.root) return "mark_canvas_removed";
473 const ms = css(mark.host);
474 if (altered(ms)) return "mark_hidden";
475 if (ms.position !== "absolute" || ms.zIndex !== String(Z_TOP)) return "mark_moved";
476 if (altered(css(mark.canvas))) return "mark_canvas_hidden";
477
478 const wr = rect(wrapper), hr = rect(mark.host);
479 if (wr.width > 0 && wr.height > 0 &&
480 (hr.width < wr.width * 0.95 || hr.height < wr.height * 0.95 ||
481 Math.abs(hr.left - wr.left) > 2 || Math.abs(hr.top - wr.top) > 2)) return "mark_resized";
482
483 // Anything stacked at or above the mark inside the player covers it.
484 for (const child of wrapper.children) {
485 if (child === mark.host || (frame && child === frame.host)) continue;
486 const z = parseInt(css(child).zIndex, 10);
487 if (Number.isFinite(z) && z >= Z_TOP) return "mark_covered";
488 }
489
490 if (mode === "composite" && frame && hasFrame) {
491 if (!frame.host.isConnected || frame.host.parentNode !== wrapper) return "frame_removed";
492 if (frame.canvas.parentNode !== frame.root) return "frame_canvas_removed";
493 if (altered(css(frame.host)) || altered(css(frame.canvas))) return "frame_hidden";
494 const vs = css(video);
495 if (vs.display !== "none" && vs.visibility === "visible" && parseFloat(vs.opacity) > 0.01) {
496 return "video_unhidden";
497 }
498 }
499
500 if (document.visibilityState === "visible" && !video.paused &&
501 performance.now() - lastDraw > STALL_MS) return "render_stalled";
502
503 if (player.currentCastSession) return "cast_active";
504
505 // The label pixels must be clearly stronger than the faint tiling under
506 // them. Catches a draw path that was neutralised some other way.
507 if (probeEnabled && !blocked && label.w > 0) {
508 try {
509 const d = call(N.getImageData, mark.ctx, label.x, label.y, Math.max(1, label.w), Math.max(1, label.h)).data;
510 let max = 0;
511 for (let i = 3; i < d.length; i += 16) if (d[i] > max) max = d[i];
512 if (max < config.opacity * 255 * 0.6) return "mark_not_painted";
513 } catch (e) {
514 probeEnabled = false;
515 }
516 }
517 return null;
518 }
519
520 function runCheck() {
521 checkQueued = false;
522 if (destroyed) return;
523 // Removing the whole player ends playback; nothing left to protect.
524 if (!player.isConnected) return destroy();
525 hideEscapeButtons();
526 if (!video.disablePictureInPicture) {
527 video.disablePictureInPicture = true;
528 onPrevented("pip_reenabled");
529 }
530 const v = findViolation();
531 if (v && v !== activeViolation) onTamper(v);
532 activeViolation = v;
533 }
534 function scheduleCheck() {
535 if (checkQueued || destroyed) return;
536 checkQueued = true;
537 queueMicrotask(runCheck);
538 }
539
540 const watched = [
541 [wrapper, { childList: true }],
542 [mark.host, { attributes: true }],
543 [mark.root, { childList: true, subtree: true, attributes: true }],
544 [video, { attributes: true, attributeFilter: ["style", "class", "hidden"] }],
545 [player, { attributes: true, attributeFilter: CONFIG_ATTRS }],
546 ];
547 if (frame) {
548 watched.push([frame.host, { attributes: true }]);
549 watched.push([frame.root, { childList: true, subtree: true, attributes: true }]);
550 }
551 const observers = watched.map(([target, opts]) => {
552 const mo = new N.MutationObserver(scheduleCheck);
553 mo.observe(target, opts);
554 return mo;
555 });
556
557 // ── Escape routes ─────────────────────────────────────────────────────
558 // PiP, AirPlay/Chromecast and iOS native fullscreen all show the bare
559 // <video> outside the player, i.e. without the mark.
560 video.disablePictureInPicture = true;
561 video.disableRemotePlayback = true;
562 video.setAttribute("x-webkit-airplay", "deny");
563 video.setAttribute("playsinline", "");
564 video.setAttribute("webkit-playsinline", "");
565 // The player re-shows its buttons on layout changes, so this re-runs every check.
566 function hideEscapeButtons() {
567 for (const b of [player.pipButton, player.castButton]) {
568 if (b && b.style.getPropertyValue("display") !== "none") {
569 b.style.setProperty("display", "none", "important");
570 }
571 }
572 }
573 hideEscapeButtons();
574 // captureStream hands out unmarked frames. Shadowed on the instance; a call
575 // through HTMLMediaElement.prototype is still possible (stated limit).
576 for (const key of ["captureStream", "mozCaptureStream"]) {
577 try {
578 Object.defineProperty(video, key, {
579 configurable: false,
580 value: () => {
581 onTamper("capture_stream");
582 throw new DOMException("Not allowed", "NotAllowedError");
583 },
584 });
585 } catch (e) { }
586 }
587
588 const onEnterPip = () => {
589 document.exitPictureInPicture && document.exitPictureInPicture().catch(() => { });
590 onPrevented("pip");
591 };
592 const onIosFullscreen = () => {
593 try { video.webkitExitFullscreen && video.webkitExitFullscreen(); } catch (e) { }
594 onPrevented("ios_native_fullscreen");
595 };
596 const onNewFrame = () => { frameDirty = true; };
597 // Offline, hls.js runs out of segment retries in seconds and the player then
598 // destroys it for good. Stop loading instead; the player restarts it when online.
599 const onOffline = () => {
600 try { player.hls && player.hls.stopLoad(); } catch (e) { }
601 };
602
603 const listeners = [
604 [video, "play", enforcePause, true],
605 [video, "playing", enforcePause, true],
606 [video, "enterpictureinpicture", onEnterPip, false],
607 [video, "webkitbeginfullscreen", onIosFullscreen, false],
608 [video, "loadeddata", onNewFrame, false],
609 [video, "seeked", onNewFrame, false],
610 [video, "resize", onNewFrame, false],
611 [document, "visibilitychange", scheduleCheck, false],
612 [window, "offline", onOffline, false],
613 ];
614 for (const [t, type, fn, cap] of listeners) t.addEventListener(type, fn, cap);
615
616 function destroy() {
617 if (destroyed) return;
618 destroyed = true;
619 call(N.cancelAnimationFrame, window, rafId);
620 call(N.clearInterval, window, checkTimer);
621 resizeObserver.disconnect();
622 observers.forEach((mo) => mo.disconnect());
623 for (const [t, type, fn, cap] of listeners) t.removeEventListener(type, fn, cap);
624 mark.host.remove();
625 frame && frame.host.remove();
626 }
627
628 rafId = call(N.requestAnimationFrame, window, render);
629 checkTimer = call(N.setInterval, window, runCheck, CHECK_MS);
630 report("start");
631 emit("fp:watermark:start", { session, mode });
632 }
633
634 // Exposes attach() only: there is deliberately no stop/disable handle.
635 Object.defineProperty(window, "FastPixLiveWatermark", {
636 value: Object.freeze({ attach }),
637 writable: false,
638 configurable: false,
639 });
640 })();
641 </script>
642
643 <script defer src="https://cdn.jsdelivr.net/npm/@fastpix/fp-player@1.0.24"></script>
644
645 <style>
646 :root {
647 --bg: #ffffff;
648 --fg: #111111;
649 --muted: #555555;
650 --line: #e4e4e7;
651 --panel: #fafafa;
652 --accent: #2563eb;
653 --bad: #b91c1c;
654 --warn: #a16207;
655 --good: #15803d;
656 }
657
658 @media (prefers-color-scheme: dark) {
659 :root {
660 --bg: #0b0b0c;
661 --fg: #ececec;
662 --muted: #a1a1aa;
663 --line: #27272a;
664 --panel: #141416;
665 --accent: #60a5fa;
666 --bad: #f87171;
667 --warn: #fbbf24;
668 --good: #4ade80;
669 }
670 }
671
672 body {
673 font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
674 background: var(--bg);
675 color: var(--fg);
676 max-width: 980px;
677 margin: 20px auto;
678 padding: 0 16px;
679 }
680
681 h1 { font-size: 1.25rem; margin: 0 0 6px; }
682 h2 { font-size: 1rem; margin: 20px 0 8px; }
683 .hint { font-size: 14px; color: var(--muted); line-height: 1.55; margin: 0 0 14px; }
684 code { font-size: 12px; background: var(--panel); border: 1px solid var(--line); padding: 1px 5px; border-radius: 4px; }
685
686 form {
687 display: grid;
688 grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
689 gap: 10px;
690 padding: 12px;
691 border: 1px solid var(--line);
692 border-radius: 8px;
693 background: var(--panel);
694 }
695
696 label { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--muted); }
697 input, select, button { font: inherit; font-size: 14px; }
698 input, select { padding: 6px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--fg); }
699 button { padding: 7px 12px; border-radius: 6px; border: 1px solid var(--line); background: var(--bg); color: var(--fg); cursor: pointer; }
700 button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
701 form button { align-self: end; }
702
703 #stage { margin-top: 14px; aspect-ratio: 16 / 9; background: #000; border-radius: 8px; overflow: hidden; }
704 #stage fastpix-player { width: 100%; height: 100%; display: block; }
705
706 .attacks { display: flex; flex-wrap: wrap; gap: 8px; }
707
708 #log {
709 margin-top: 8px;
710 height: 220px;
711 overflow: auto;
712 border: 1px solid var(--line);
713 border-radius: 8px;
714 background: var(--panel);
715 font: 12px/1.6 ui-monospace, SFMono-Regular, Menlo, monospace;
716 padding: 8px 10px;
717 }
718
719 .tamper { color: var(--bad); }
720 .blocked { color: var(--bad); font-weight: 700; }
721 .prevented { color: var(--warn); }
722 .start { color: var(--good); }
723 </style>
724</head>
725
726<body>
727 <h1>Live dynamic watermark</h1>
728 <p class="hint">
729 A moving, per-viewer watermark with tamper detection, added from the page around an unmodified
730 <code>&lt;fastpix-player&gt;</code>. In production, <code>watermark-text</code> must come from your server
731 for the signed-in viewer, never from user input.
732 </p>
733
734 <form id="config">
735 <label>Playback ID <input name="playbackId" value="2125094c-db43-4748-90e1-18539f2ccf98" required /></label>
736 <label>Stream type
737 <select name="streamType">
738 <option value="live-stream">live-stream</option>
739 <option value="on-demand">on-demand</option>
740 </select>
741 </label>
742 <label>Viewer (watermark text) <input name="text" value="viewer@example.com" required /></label>
743 <label>Mode
744 <select name="mode">
745 <option value="composite">composite</option>
746 <option value="overlay">overlay</option>
747 </select>
748 </label>
749 <label>On tamper
750 <select name="onTamper">
751 <option value="stop">stop</option>
752 <option value="report">report</option>
753 </select>
754 </label>
755 <label>Opacity <input name="opacity" type="number" min="0.15" max="0.9" step="0.05" value="0.4" /></label>
756 <label>DRM token (forces overlay) <input name="drmToken" placeholder="optional" /></label>
757 <button class="primary" type="submit">Load player</button>
758 </form>
759
760 <div id="stage"></div>
761
762 <h2>Tamper lab</h2>
763 <p class="hint">Each button does what an attacker would do from DevTools. With <code>On tamper: stop</code> the
764 first hit stops playback; switch to <code>report</code> to try them all, then reload the player.</p>
765 <div class="attacks">
766 <button data-attack="hideMark">Hide the mark</button>
767 <button data-attack="fadeMark">Fade the mark to 0</button>
768 <button data-attack="removeMark">Remove the mark</button>
769 <button data-attack="coverMark">Cover the mark</button>
770 <button data-attack="unhideVideo">Un-hide raw video</button>
771 <button data-attack="hideFrame">Hide frame layer</button>
772 <button data-attack="patchFillText">No-op fillText</button>
773 <button data-attack="changeText">Edit watermark-text</button>
774 <button data-attack="pip">Picture-in-picture</button>
775 <button data-attack="captureStream">captureStream()</button>
776 </div>
777
778 <h2>Events</h2>
779 <div id="log"></div>
780
781 <script>
782 const stage = document.getElementById("stage");
783 const logEl = document.getElementById("log");
784 let player = null;
785
786 function log(cls, text) {
787 const line = document.createElement("div");
788 line.className = cls;
789 line.textContent = `${new Date().toLocaleTimeString()} ${text}`;
790 logEl.prepend(line);
791 }
792
793 for (const name of ["start", "tamper", "prevented", "blocked"]) {
794 document.addEventListener(`fp:watermark:${name}`, (e) => log(name, `${name} ${JSON.stringify(e.detail)}`));
795 }
796
797 document.getElementById("config").addEventListener("submit", async (e) => {
798 e.preventDefault();
799 const f = new FormData(e.target);
800 await customElements.whenDefined("fastpix-player");
801 stage.replaceChildren();
802 player = document.createElement("fastpix-player");
803 player.setAttribute("playback-id", f.get("playbackId"));
804 player.setAttribute("stream-type", f.get("streamType"));
805 player.setAttribute("auto-play", "");
806 if (f.get("drmToken")) player.setAttribute("drm-token", f.get("drmToken"));
807 player.setAttribute("watermark-text", f.get("text"));
808 player.setAttribute("watermark-mode", f.get("mode"));
809 player.setAttribute("watermark-opacity", f.get("opacity"));
810 player.setAttribute("watermark-on-tamper", f.get("onTamper"));
811 stage.appendChild(player);
812 try {
813 await FastPixLiveWatermark.attach(player);
814 } catch (err) {
815 log("tamper", `attach failed: ${err.message}`);
816 }
817 });
818
819 // What an attacker sees: an open player shadow root and two unnamed divs.
820 function layers() {
821 const root = player?.shadowRoot;
822 const video = root?.querySelector("video");
823 const wrapper = video?.parentElement;
824 const divs = wrapper ? [...wrapper.children] : [];
825 return {
826 video,
827 wrapper,
828 mark: divs.find((d) => getComputedStyle(d).zIndex === "2147483000"),
829 frame: video?.nextElementSibling,
830 };
831 }
832
833 const attacks = {
834 hideMark: () => layers().mark?.style.setProperty("display", "none", "important"),
835 fadeMark: () => layers().mark?.style.setProperty("opacity", "0", "important"),
836 removeMark: () => layers().mark?.remove(),
837 coverMark: () => {
838 const cover = document.createElement("div");
839 cover.style.cssText = "position:absolute;inset:0;z-index:2147483647;background:#000";
840 layers().wrapper?.appendChild(cover);
841 },
842 unhideVideo: () => layers().video?.style.setProperty("opacity", "1", "important"),
843 hideFrame: () => layers().frame?.style.setProperty("display", "none", "important"),
844 patchFillText: () => { CanvasRenderingContext2D.prototype.fillText = function () { }; },
845 changeText: () => player?.setAttribute("watermark-text", "someone-else"),
846 pip: () => layers().video?.requestPictureInPicture().catch((e) => log("prevented", `PiP refused: ${e.message}`)),
847 captureStream: () => {
848 try { layers().video?.captureStream(); } catch (e) { log("prevented", `captureStream refused: ${e.message}`); }
849 },
850 };
851
852 document.querySelector(".attacks").addEventListener("click", (e) => {
853 const name = e.target?.dataset?.attack;
854 if (!name) return;
855 if (!player) return log("prevented", "Load a player first");
856 log("", `attack: ${name}`);
857 attacks[name]();
858 });
859 </script>
860</body>
861
862</html>