Skip to content

Commit

Permalink
fix taint canvas
Browse files Browse the repository at this point in the history
  • Loading branch information
rutan committed Oct 1, 2024
1 parent 0c4a86a commit f0c2e6c
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 21 deletions.
47 changes: 29 additions & 18 deletions src/functions/pinp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,11 @@ export function handleVideo(): void {
const supporterCanvas = document.querySelector<HTMLCanvasElement>(
SUPPORTER_VIEW_CANVAS_SELECTOR,
);
const akashicCanvas = document.querySelector<HTMLCanvasElement>(

let akashicCanvas = document.querySelector<HTMLCanvasElement>(
AKASHIC_CANVAS_SELECTOR,
);
const akashicCanvasContext = akashicCanvas?.getContext('2d');

function update() {
if (!comment || !targetVideo || !context || myId !== uid) {
Expand Down Expand Up @@ -149,23 +151,32 @@ export function handleVideo(): void {

// akashic
if (akashicCanvas) {
const size = calcSize(
akashicCanvas.width,
akashicCanvas.height,
canvas.width,
canvas.height,
);
context.drawImage(
akashicCanvas,
0,
0,
akashicCanvas.width,
akashicCanvas.height,
(canvas.width - size.width) / 2,
(canvas.height - size.height) / 2,
size.width,
size.height,
);
try {
// 外部リソースの読み込みによって canvas が汚染されていないかを確認
akashicCanvasContext?.getImageData(0, 0, 1, 1);

const size = calcSize(
akashicCanvas.width,
akashicCanvas.height,
canvas.width,
canvas.height,
);
context.drawImage(
akashicCanvas,
0,
0,
akashicCanvas.width,
akashicCanvas.height,
(canvas.width - size.width) / 2,
(canvas.height - size.height) / 2,
size.width,
size.height,
);
} catch (e) {
// canvas が汚染されたいる場合は AkashicCanvas をPinP対象から削除
console.error(e);
akashicCanvas = null;
}
}

// comment
Expand Down
17 changes: 14 additions & 3 deletions src/inject.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
// ニコ生のギフト描画用
// AkashicのCanvasが汚染されることを防ぐため、必要に応じて自動的に corssOrigin="anonymous" を付与する
(() => {
const cdnNimgJpPattern = /^https:\/\/[^.]+\.cdn\.nimg\.jp\//;
const resourceAkashicCoePrefix = 'https://resource.akashic.coe.nicovideo.jp/';
const irCdnNimgJpPrefix = 'https://ir.cdn.nimg.jp/';
const secureDcdnPrefix = 'https://secure-dcdn.cdn.nimg.jp/';

class AutoAnonymousImage extends Image {
get src() {
Expand All @@ -8,13 +12,20 @@

set src(value: string) {
super.src = value;
if (value?.match(cdnNimgJpPattern)) {
if (
// Akashic
value?.startsWith(resourceAkashicCoePrefix) ||
// ギフト
value?.startsWith(irCdnNimgJpPrefix) ||
// エモーション
value?.startsWith(secureDcdnPrefix)
) {
this.crossOrigin = 'anonymous';
}
}
}

window.Image = new Proxy(window.Image, {
construct: (target, args) => new AutoAnonymousImage(...args),
construct: (_target, args) => new AutoAnonymousImage(...args),
});
})();

0 comments on commit f0c2e6c

Please sign in to comment.