@geolonia/embed 5.2.2 → 5.2.3
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/.github/workflows/build.yml +39 -10
- package/CHANGELOG.md +8 -0
- package/README.md +27 -0
- package/dist/embed +1 -1
- package/dist/embed-core.js +1 -1
- package/dist/embed-core.js.LICENSE.txt +1 -1
- package/dist/embed.js +1 -1
- package/dist/embed.js.LICENSE.txt +1 -1
- package/dist/lib/geolonia-map.d.ts +6 -0
- package/dist/lib/sanitize-attribution.d.ts +15 -0
- package/dist/lib/util.d.ts +16 -1
- package/dist/types.d.ts +6 -0
- package/dist/version.d.ts +1 -1
- package/e2e/webgl-error.spec.ts +105 -0
- package/package.json +2 -2
- package/src/lib/CustomAttributionControl.ts +7 -2
- package/src/lib/geolonia-map.ts +22 -2
- package/src/lib/parse-atts.test.ts +1 -0
- package/src/lib/parse-atts.ts +1 -0
- package/src/lib/sanitize-attribution.test.ts +122 -0
- package/src/lib/sanitize-attribution.ts +192 -0
- package/src/lib/util.test.ts +85 -0
- package/src/lib/util.ts +76 -7
- package/src/style.css +69 -4
- package/src/types.ts +6 -0
- package/src/version.ts +1 -1
|
@@ -2,6 +2,12 @@ import maplibregl, { MapOptions, StyleOptions, StyleSpecification, StyleSwapOpti
|
|
|
2
2
|
import { GetImageCallback } from './util';
|
|
3
3
|
export type GeoloniaMapOptions = MapOptions & {
|
|
4
4
|
interactive?: boolean;
|
|
5
|
+
/**
|
|
6
|
+
* 地図の初期化に失敗したときに表示する文言。`false` または `'off'` を
|
|
7
|
+
* 指定するとエラー表示自体を行わない。
|
|
8
|
+
* 未指定のときは Embed 既定の案内を表示する。
|
|
9
|
+
*/
|
|
10
|
+
errorMessage?: string | false;
|
|
5
11
|
};
|
|
6
12
|
/**
|
|
7
13
|
* Render the map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* アトリビューション HTML の無害化。
|
|
3
|
+
* maplibre-gl 5.24.1 の DOM.sanitize (許可リスト方式) と同じ方針で、
|
|
4
|
+
* CustomAttributionControl が使う。
|
|
5
|
+
* https://github.com/maplibre/maplibre-gl-js/blob/v5.24.1/src/util/dom.ts
|
|
6
|
+
*
|
|
7
|
+
* 文字列ではなく DocumentFragment を返す。シリアライズして再パースすると、
|
|
8
|
+
* 入れ子の組み立て次第で無害化済みの木が別の木に変わるため。
|
|
9
|
+
*/
|
|
10
|
+
export declare const sanitizeAttribution: (html: string) => DocumentFragment;
|
|
11
|
+
/**
|
|
12
|
+
* アトリビューションごとに無害化し、中身が空になったものを除いて ` | ` で区切って並べる。
|
|
13
|
+
* 1 つも残らなければ空の DocumentFragment を返す。
|
|
14
|
+
*/
|
|
15
|
+
export declare const buildAttributionFragment: (attributions: string[]) => DocumentFragment;
|
package/dist/lib/util.d.ts
CHANGED
|
@@ -55,7 +55,22 @@ export declare function parseControlOption(att: any): {
|
|
|
55
55
|
export declare const getSessionId: (digit: any) => string;
|
|
56
56
|
export declare const parseSimpleVector: (attributeValue: any) => any;
|
|
57
57
|
export declare const handleRestrictedMode: (map: any) => void;
|
|
58
|
-
|
|
58
|
+
/**
|
|
59
|
+
* 地図の初期化に失敗したときのエラー表示。
|
|
60
|
+
*
|
|
61
|
+
* 既定では「WebGL が使えない状態かもしれない」という原因と、利用者が自分で試せる
|
|
62
|
+
* 復旧手順を描画する。手順を書き切った版と 1 行の短縮版の両方を DOM に入れておき、
|
|
63
|
+
* どちらを見せるかは地図コンテナの広さに応じて CSS(コンテナクエリ)が決める。
|
|
64
|
+
* 消費側で文言を差し替えたい場合は `data-error-message` に文字列を、
|
|
65
|
+
* エラー表示自体を止めたい場合は `data-error-message="off"`(プログラム API では
|
|
66
|
+
* `errorMessage: false`)を指定する。
|
|
67
|
+
*
|
|
68
|
+
* @param container 地図コンテナ
|
|
69
|
+
* @param options `message` に差し替え文言、`false` / `'off'` で表示しない
|
|
70
|
+
*/
|
|
71
|
+
export declare const handleErrorMode: (container: HTMLElement, options?: {
|
|
72
|
+
message?: string | false;
|
|
73
|
+
}) => void;
|
|
59
74
|
export declare const sanitizeDescription: (description: any) => Promise<any>;
|
|
60
75
|
export declare const random: (max: number) => number;
|
|
61
76
|
export declare function loadImageCompatibility(promise: Promise<GetResourceResponse<HTMLImageElement | ImageBitmap>>, callback: GetImageCallback): void;
|
package/dist/types.d.ts
CHANGED
|
@@ -26,6 +26,12 @@ export type EmbedAttributes = {
|
|
|
26
26
|
key: string;
|
|
27
27
|
apiUrl: string;
|
|
28
28
|
loader: string;
|
|
29
|
+
/**
|
|
30
|
+
* `data-error-message`:地図の初期化に失敗したときの表示。
|
|
31
|
+
* 文字列を指定するとその文言に差し替え、`'off'` を指定するとエラー表示自体を行わない。
|
|
32
|
+
* 未指定のときは Embed 既定の案内(復旧手順つき)を表示する。
|
|
33
|
+
*/
|
|
34
|
+
errorMessage: string;
|
|
29
35
|
minZoom: string | number;
|
|
30
36
|
maxZoom: string | number;
|
|
31
37
|
'3d': string;
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "5.2.
|
|
1
|
+
export declare const VERSION = "5.2.3";
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { test, expect } from '@playwright/test';
|
|
2
|
+
import { TEST_URL } from './helper';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* WebGL が使えない端末での表示。
|
|
6
|
+
* フィクスチャ側で `getContext('webgl')` を null にして初期化を必ず失敗させている。
|
|
7
|
+
*/
|
|
8
|
+
test.describe('WebGL 初期化失敗時のエラー表示', () => {
|
|
9
|
+
test.beforeEach(async ({ page }) => {
|
|
10
|
+
await page.goto(`${TEST_URL}/webgl-error.html`);
|
|
11
|
+
await page.waitForSelector('#map-large .geolonia__error-container');
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
test('広い地図では復旧手順まで表示する', async ({ page }) => {
|
|
15
|
+
const container = page.locator('#map-large');
|
|
16
|
+
await expect(
|
|
17
|
+
container.locator('.geolonia__error-message-title'),
|
|
18
|
+
).toHaveText('地図を表示できませんでした');
|
|
19
|
+
await expect(
|
|
20
|
+
container.locator('.geolonia__error-message-lead'),
|
|
21
|
+
).toBeVisible();
|
|
22
|
+
await expect(
|
|
23
|
+
container.locator('.geolonia__error-message-steps li'),
|
|
24
|
+
).toHaveCount(4);
|
|
25
|
+
await expect(
|
|
26
|
+
container.locator('.geolonia__error-message-contact'),
|
|
27
|
+
).toBeVisible();
|
|
28
|
+
await expect(
|
|
29
|
+
container.locator('.geolonia__error-message-brief'),
|
|
30
|
+
).toBeHidden();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test('開発者向けの案内文を表示しない', async ({ page }) => {
|
|
34
|
+
await expect(page.locator('#map-large')).not.toContainText('開発者ツール');
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test('中くらいの地図では短縮版に切り替わる', async ({ page }) => {
|
|
38
|
+
const container = page.locator('#map-medium');
|
|
39
|
+
await expect(
|
|
40
|
+
container.locator('.geolonia__error-message-title'),
|
|
41
|
+
).toBeVisible();
|
|
42
|
+
await expect(
|
|
43
|
+
container.locator('.geolonia__error-message-brief'),
|
|
44
|
+
).toBeVisible();
|
|
45
|
+
await expect(
|
|
46
|
+
container.locator('.geolonia__error-message-steps'),
|
|
47
|
+
).toBeHidden();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('小さい地図では見出しだけを表示する', async ({ page }) => {
|
|
51
|
+
const container = page.locator('#map-small');
|
|
52
|
+
await expect(
|
|
53
|
+
container.locator('.geolonia__error-message-title'),
|
|
54
|
+
).toBeVisible();
|
|
55
|
+
await expect(
|
|
56
|
+
container.locator('.geolonia__error-message-brief'),
|
|
57
|
+
).toBeHidden();
|
|
58
|
+
await expect(
|
|
59
|
+
container.locator('.geolonia__error-message-steps'),
|
|
60
|
+
).toBeHidden();
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
test('エラー表示が地図コンテナからはみ出さない', async ({ page }) => {
|
|
64
|
+
for (const id of ['#map-large', '#map-medium', '#map-small']) {
|
|
65
|
+
const container = await page.locator(id).boundingBox();
|
|
66
|
+
const message = await page
|
|
67
|
+
.locator(`${id} .geolonia__error-message`)
|
|
68
|
+
.boundingBox();
|
|
69
|
+
expect(message.x).toBeGreaterThanOrEqual(container.x - 1);
|
|
70
|
+
expect(message.y).toBeGreaterThanOrEqual(container.y - 1);
|
|
71
|
+
expect(message.x + message.width).toBeLessThanOrEqual(
|
|
72
|
+
container.x + container.width + 1,
|
|
73
|
+
);
|
|
74
|
+
expect(message.y + message.height).toBeLessThanOrEqual(
|
|
75
|
+
container.y + container.height + 1,
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test('data-error-message で文言を差し替えられる', async ({ page }) => {
|
|
81
|
+
const container = page.locator('#map-custom');
|
|
82
|
+
await expect(
|
|
83
|
+
container.locator('.geolonia__error-message-description'),
|
|
84
|
+
).toHaveText(
|
|
85
|
+
'地図を表示できませんでした。お手数ですが 0120-000-000 までご連絡ください。',
|
|
86
|
+
);
|
|
87
|
+
await expect(
|
|
88
|
+
container.locator('.geolonia__error-message-steps'),
|
|
89
|
+
).toHaveCount(0);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test('data-error-message="off" でエラー表示を無効にできる', async ({
|
|
93
|
+
page,
|
|
94
|
+
}) => {
|
|
95
|
+
await expect(
|
|
96
|
+
page.locator('#map-off .geolonia__error-container'),
|
|
97
|
+
).toHaveCount(0);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test('初期化に失敗したらローディング表示を止める', async ({ page }) => {
|
|
101
|
+
for (const id of ['#map-large', '#map-off']) {
|
|
102
|
+
await expect(page.locator(`${id} .loading-geolonia-map`)).toHaveCount(0);
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@geolonia/embed",
|
|
3
|
-
"version": "5.2.
|
|
3
|
+
"version": "5.2.3",
|
|
4
4
|
"description": "Geolonia embed JS API",
|
|
5
5
|
"main": "dist/embed.js",
|
|
6
6
|
"types": "dist/src/embed.d.ts",
|
|
@@ -71,7 +71,7 @@
|
|
|
71
71
|
"@mapbox/point-geometry": "^0.1.0",
|
|
72
72
|
"@playwright/test": "^1.53.1",
|
|
73
73
|
"@turf/center": "^6.0.1",
|
|
74
|
-
"maplibre-gl": "5.
|
|
74
|
+
"maplibre-gl": "5.24.1",
|
|
75
75
|
"pmtiles": "^3.0.6",
|
|
76
76
|
"sanitize-html": "^2.8.0",
|
|
77
77
|
"tinycolor2": "^1.4.1"
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { DOM, bindAll } from './maplibre-util';
|
|
2
|
+
import { buildAttributionFragment } from './sanitize-attribution';
|
|
2
3
|
import type { ControlPosition, IControl } from 'maplibre-gl';
|
|
3
4
|
|
|
4
5
|
/**
|
|
@@ -346,10 +347,14 @@ class CustomAttributionControl implements IControl {
|
|
|
346
347
|
|
|
347
348
|
this._attribHTML = attribHTML;
|
|
348
349
|
|
|
349
|
-
|
|
350
|
-
|
|
350
|
+
// 外部由来の HTML なので、アトリビューションごとに無害化して DOM ノードとして挿入する。
|
|
351
|
+
const fragment = buildAttributionFragment(attributions);
|
|
352
|
+
if (fragment.hasChildNodes()) {
|
|
353
|
+
this._innerContainer.replaceChildren(fragment);
|
|
351
354
|
this._shadowContainer.classList.remove('maplibregl-attrib-empty');
|
|
352
355
|
} else {
|
|
356
|
+
// 無害化の結果すべて空になった場合も、空の帯を出さない。
|
|
357
|
+
this._innerContainer.replaceChildren();
|
|
353
358
|
this._shadowContainer.classList.add('maplibregl-attrib-empty');
|
|
354
359
|
}
|
|
355
360
|
this._updateCompact();
|
package/src/lib/geolonia-map.ts
CHANGED
|
@@ -35,7 +35,15 @@ import {
|
|
|
35
35
|
isGeoloniaTilesHost,
|
|
36
36
|
} from './util';
|
|
37
37
|
|
|
38
|
-
export type GeoloniaMapOptions = MapOptions & {
|
|
38
|
+
export type GeoloniaMapOptions = MapOptions & {
|
|
39
|
+
interactive?: boolean;
|
|
40
|
+
/**
|
|
41
|
+
* 地図の初期化に失敗したときに表示する文言。`false` または `'off'` を
|
|
42
|
+
* 指定するとエラー表示自体を行わない。
|
|
43
|
+
* 未指定のときは Embed 既定の案内を表示する。
|
|
44
|
+
*/
|
|
45
|
+
errorMessage?: string | false;
|
|
46
|
+
};
|
|
39
47
|
|
|
40
48
|
type Container = HTMLElement & {
|
|
41
49
|
geoloniaMap: GeoloniaMap;
|
|
@@ -189,7 +197,19 @@ export default class GeoloniaMap extends maplibregl.Map {
|
|
|
189
197
|
// Generate Map
|
|
190
198
|
super(options);
|
|
191
199
|
} catch (error) {
|
|
192
|
-
|
|
200
|
+
// 初期化に失敗した以上ローディングは終わらないので、先に消す。
|
|
201
|
+
// 消さないと `errorMessage: 'off'` のとき「読み込み中」のまま見えてしまう。
|
|
202
|
+
container.querySelector('.loading-geolonia-map')?.remove();
|
|
203
|
+
// `data-error-message` / コンストラクタの `errorMessage` で
|
|
204
|
+
// 文言の差し替えと表示の無効化(`'off'` または `false`)ができる。
|
|
205
|
+
const attErrorMessage = atts.errorMessage
|
|
206
|
+
? String(atts.errorMessage)
|
|
207
|
+
: undefined;
|
|
208
|
+
const optionErrorMessage =
|
|
209
|
+
typeof params === 'object' ? params.errorMessage : undefined;
|
|
210
|
+
handleErrorMode(container, {
|
|
211
|
+
message: attErrorMessage ?? optionErrorMessage,
|
|
212
|
+
});
|
|
193
213
|
throw error;
|
|
194
214
|
}
|
|
195
215
|
|
package/src/lib/parse-atts.ts
CHANGED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
sanitizeAttribution,
|
|
4
|
+
buildAttributionFragment,
|
|
5
|
+
} from './sanitize-attribution';
|
|
6
|
+
|
|
7
|
+
const render = (html: string) => {
|
|
8
|
+
const div = document.createElement('div');
|
|
9
|
+
div.append(sanitizeAttribution(html));
|
|
10
|
+
return div;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
describe('sanitizeAttribution', () => {
|
|
14
|
+
it('通常のアトリビューションのリンクを残す', () => {
|
|
15
|
+
const div = render(
|
|
16
|
+
'<a href="https://example.com/c" target="_blank" rel="noopener">© Example</a>',
|
|
17
|
+
);
|
|
18
|
+
const a = div.querySelector('a');
|
|
19
|
+
expect(a?.getAttribute('href')).toBe('https://example.com/c');
|
|
20
|
+
expect(a?.getAttribute('target')).toBe('_blank');
|
|
21
|
+
expect(a?.textContent).toBe('© Example');
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
// GHSA-jrc7-96c5-q579: 連続する危険な属性の 2 つ目が残った
|
|
25
|
+
it('連続する危険な属性をすべて消す', () => {
|
|
26
|
+
const div = render(
|
|
27
|
+
'<details open onload="1" ontoggle="alert(1)" onclick="alert(2)">x</details>',
|
|
28
|
+
);
|
|
29
|
+
expect(div.querySelector('details')).toBeNull();
|
|
30
|
+
expect(div.innerHTML).not.toMatch(/on(load|toggle|click)/);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('許可リストにない属性を連続していても全て消す', () => {
|
|
34
|
+
const div = render(
|
|
35
|
+
'<a href="https://example.com" onclick="1" onmouseover="2" style="x:y" id="a">t</a>',
|
|
36
|
+
);
|
|
37
|
+
const a = div.querySelector('a');
|
|
38
|
+
expect(a?.getAttributeNames()).toEqual(['href']);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it.each([
|
|
42
|
+
'<script>alert(1)</script>',
|
|
43
|
+
'<iframe srcdoc="<script>alert(1)</script>"></iframe>',
|
|
44
|
+
'<svg onload="alert(1)"></svg>',
|
|
45
|
+
'<math><mi>x</mi></math>',
|
|
46
|
+
'<style>a{}</style>',
|
|
47
|
+
'<form><input name="remove"></form>',
|
|
48
|
+
])('許可リストにない要素を消す: %s', (html) => {
|
|
49
|
+
const div = render(html);
|
|
50
|
+
expect(
|
|
51
|
+
div.querySelector('script,iframe,svg,math,style,form,input'),
|
|
52
|
+
).toBeNull();
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it.each([
|
|
56
|
+
'javascript:alert(1)',
|
|
57
|
+
' JaVaScRiPt:alert(1)',
|
|
58
|
+
'java\tscript:alert(1)',
|
|
59
|
+
'data:text/html,<script>alert(1)</script>',
|
|
60
|
+
])('href の危険なプロトコルを消す: %s', (href) => {
|
|
61
|
+
const div = render(`<a href="${href}">t</a>`);
|
|
62
|
+
expect(div.querySelector('a')?.hasAttribute('href')).toBe(false);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it('img の src は http(s) だけ許可する', () => {
|
|
66
|
+
const ok = render('<img src="https://example.com/a.png" alt="a">');
|
|
67
|
+
expect(ok.querySelector('img')?.getAttribute('src')).toBe(
|
|
68
|
+
'https://example.com/a.png',
|
|
69
|
+
);
|
|
70
|
+
const ng = render('<img src="javascript:alert(1)" onerror="alert(1)">');
|
|
71
|
+
expect(ng.querySelector('img')?.getAttributeNames()).toEqual([]);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it('許可されない要素は子ごと消し、前後の許可された内容は残す', () => {
|
|
75
|
+
const div = render(
|
|
76
|
+
'<a href="https://example.com">a</a><script>x</script>b',
|
|
77
|
+
);
|
|
78
|
+
expect(div.textContent).toBe('ab');
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('doc.body を名前付き要素で隠そうとしても無害化される', () => {
|
|
82
|
+
const div = render(
|
|
83
|
+
'<img name="body"><img name="body"><a href="https://a.example" onclick="1">A</a><script>x</script>',
|
|
84
|
+
);
|
|
85
|
+
expect(div.querySelector('script')).toBeNull();
|
|
86
|
+
expect(div.querySelector('a')?.getAttributeNames()).toEqual(['href']);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('未閉じの許可されない要素があっても空の文字列で壊れない', () => {
|
|
90
|
+
expect(sanitizeAttribution('').hasChildNodes()).toBe(false);
|
|
91
|
+
expect(() => sanitizeAttribution('<script>')).not.toThrow();
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe('buildAttributionFragment', () => {
|
|
96
|
+
const text = (list: string[]) => {
|
|
97
|
+
const div = document.createElement('div');
|
|
98
|
+
div.append(buildAttributionFragment(list));
|
|
99
|
+
return div.textContent;
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
it('アトリビューションを " | " で区切って並べる', () => {
|
|
103
|
+
expect(text(['<a href="https://a.example">A</a>', 'B'])).toBe('A | B');
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('無害化の結果が空になったものは区切りごと除く', () => {
|
|
107
|
+
expect(text(['<script>x</script>', 'A', '<script>y</script>', 'B'])).toBe(
|
|
108
|
+
'A | B',
|
|
109
|
+
);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it('すべて空になれば何も残さない', () => {
|
|
113
|
+
expect(
|
|
114
|
+
buildAttributionFragment(['<script>x</script>']).hasChildNodes(),
|
|
115
|
+
).toBe(false);
|
|
116
|
+
expect(buildAttributionFragment([]).hasChildNodes()).toBe(false);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it('あるアトリビューションの未閉じの許可外タグが他を消さない', () => {
|
|
120
|
+
expect(text(['<script>', 'A'])).toBe('A');
|
|
121
|
+
});
|
|
122
|
+
});
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* アトリビューション HTML の無害化。
|
|
3
|
+
* maplibre-gl 5.24.1 の DOM.sanitize (許可リスト方式) と同じ方針で、
|
|
4
|
+
* CustomAttributionControl が使う。
|
|
5
|
+
* https://github.com/maplibre/maplibre-gl-js/blob/v5.24.1/src/util/dom.ts
|
|
6
|
+
*
|
|
7
|
+
* 文字列ではなく DocumentFragment を返す。シリアライズして再パースすると、
|
|
8
|
+
* 入れ子の組み立て次第で無害化済みの木が別の木に変わるため。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';
|
|
12
|
+
|
|
13
|
+
const ALLOWED_TAGS = new Set([
|
|
14
|
+
'a',
|
|
15
|
+
'abbr',
|
|
16
|
+
'b',
|
|
17
|
+
'bdi',
|
|
18
|
+
'bdo',
|
|
19
|
+
'br',
|
|
20
|
+
'cite',
|
|
21
|
+
'code',
|
|
22
|
+
'del',
|
|
23
|
+
'div',
|
|
24
|
+
'em',
|
|
25
|
+
'i',
|
|
26
|
+
'img',
|
|
27
|
+
'ins',
|
|
28
|
+
'kbd',
|
|
29
|
+
'li',
|
|
30
|
+
'mark',
|
|
31
|
+
'ol',
|
|
32
|
+
'p',
|
|
33
|
+
'q',
|
|
34
|
+
's',
|
|
35
|
+
'samp',
|
|
36
|
+
'small',
|
|
37
|
+
'span',
|
|
38
|
+
'strong',
|
|
39
|
+
'sub',
|
|
40
|
+
'sup',
|
|
41
|
+
'time',
|
|
42
|
+
'u',
|
|
43
|
+
'ul',
|
|
44
|
+
'var',
|
|
45
|
+
'wbr',
|
|
46
|
+
]);
|
|
47
|
+
|
|
48
|
+
const ALLOWED_ATTRIBUTES = new Set([
|
|
49
|
+
'alt',
|
|
50
|
+
'class',
|
|
51
|
+
'datetime',
|
|
52
|
+
'dir',
|
|
53
|
+
'height',
|
|
54
|
+
'href',
|
|
55
|
+
'hreflang',
|
|
56
|
+
'lang',
|
|
57
|
+
'referrerpolicy',
|
|
58
|
+
'rel',
|
|
59
|
+
'role',
|
|
60
|
+
'src',
|
|
61
|
+
'target',
|
|
62
|
+
'title',
|
|
63
|
+
'translate',
|
|
64
|
+
'type',
|
|
65
|
+
'width',
|
|
66
|
+
]);
|
|
67
|
+
|
|
68
|
+
const URL_ATTRIBUTES = new Set(['href', 'src']);
|
|
69
|
+
const ALLOWED_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);
|
|
70
|
+
|
|
71
|
+
// 相対 URL もプロトコルを読むために何かに解決する。結果のプロトコルだけを使い、
|
|
72
|
+
// ベースは出力に残らない。
|
|
73
|
+
const RELATIVE_URL_BASE = 'https://geolonia.invalid/';
|
|
74
|
+
|
|
75
|
+
type ElementInternals = {
|
|
76
|
+
getAttribute: Element['getAttribute'];
|
|
77
|
+
getAttributeNames: Element['getAttributeNames'];
|
|
78
|
+
querySelectorAll: Element['querySelectorAll'];
|
|
79
|
+
remove: Element['remove'];
|
|
80
|
+
removeAttribute: Element['removeAttribute'];
|
|
81
|
+
localName: () => string;
|
|
82
|
+
namespaceURI: () => string | null;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
let elementInternals: ElementInternals | undefined;
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 無害化に使う Element のメンバーは、対象の要素ではなくプロトタイプから読む。
|
|
89
|
+
* `children` `remove` `localName` などの名前を持つフォーム部品は、
|
|
90
|
+
* 自身の form 要素の同名プロパティを隠してしまい、入力側が無害化の見る木を選べてしまう。
|
|
91
|
+
* モジュール読み込み時に DOM が無い環境 (SSR) もあるので、初回利用時に読む。
|
|
92
|
+
*/
|
|
93
|
+
const getElementInternals = (): ElementInternals => {
|
|
94
|
+
if (!elementInternals) {
|
|
95
|
+
const getter = (name: string) =>
|
|
96
|
+
(
|
|
97
|
+
Object.getOwnPropertyDescriptor(Element.prototype, name) as {
|
|
98
|
+
get: () => unknown;
|
|
99
|
+
}
|
|
100
|
+
).get;
|
|
101
|
+
elementInternals = {
|
|
102
|
+
getAttribute: Element.prototype.getAttribute,
|
|
103
|
+
getAttributeNames: Element.prototype.getAttributeNames,
|
|
104
|
+
querySelectorAll: Element.prototype.querySelectorAll,
|
|
105
|
+
remove: Element.prototype.remove,
|
|
106
|
+
removeAttribute: Element.prototype.removeAttribute,
|
|
107
|
+
localName: getter('localName') as () => string,
|
|
108
|
+
namespaceURI: getter('namespaceURI') as () => string | null,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
return elementInternals;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* `<img name="body">` などの名前付き要素が `doc.body` を隠す実装があるため、
|
|
116
|
+
* body も Document.prototype の getter から読む。
|
|
117
|
+
*/
|
|
118
|
+
const getDocumentBody = (doc: Document): HTMLElement => {
|
|
119
|
+
const get = (
|
|
120
|
+
Object.getOwnPropertyDescriptor(Document.prototype, 'body') as {
|
|
121
|
+
get: () => HTMLElement;
|
|
122
|
+
}
|
|
123
|
+
).get;
|
|
124
|
+
return get.call(doc);
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
const isAllowedElement = (element: Element): boolean => {
|
|
128
|
+
const { namespaceURI, localName } = getElementInternals();
|
|
129
|
+
return (
|
|
130
|
+
namespaceURI.call(element) === HTML_NAMESPACE &&
|
|
131
|
+
ALLOWED_TAGS.has(localName.call(element))
|
|
132
|
+
);
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
const isAllowedAttribute = (name: string, value: string): boolean => {
|
|
136
|
+
if (!ALLOWED_ATTRIBUTES.has(name) && !name.startsWith('aria-')) return false;
|
|
137
|
+
if (!URL_ATTRIBUTES.has(name)) return true;
|
|
138
|
+
try {
|
|
139
|
+
return ALLOWED_PROTOCOLS.has(new URL(value, RELATIVE_URL_BASE).protocol);
|
|
140
|
+
} catch {
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const removeDisallowedAttributes = (element: Element): void => {
|
|
146
|
+
const { getAttributeNames, getAttribute, removeAttribute } =
|
|
147
|
+
getElementInternals();
|
|
148
|
+
// getAttributeNames は静的な配列を返すので、削除しながら回しても飛ばさない。
|
|
149
|
+
for (const name of getAttributeNames.call(element)) {
|
|
150
|
+
if (isAllowedAttribute(name, getAttribute.call(element, name) ?? '')) {
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
removeAttribute.call(element, name);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
export const sanitizeAttribution = (html: string): DocumentFragment => {
|
|
158
|
+
const doc = new DOMParser().parseFromString(html, 'text/html');
|
|
159
|
+
const body = getDocumentBody(doc);
|
|
160
|
+
const { querySelectorAll, remove } = getElementInternals();
|
|
161
|
+
for (const element of Array.from(
|
|
162
|
+
querySelectorAll.call(body, '*') as NodeListOf<Element>,
|
|
163
|
+
)) {
|
|
164
|
+
if (isAllowedElement(element)) {
|
|
165
|
+
removeDisallowedAttributes(element);
|
|
166
|
+
} else {
|
|
167
|
+
remove.call(element);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
const fragment = document.createDocumentFragment();
|
|
171
|
+
fragment.append(...Array.from(body.childNodes));
|
|
172
|
+
return fragment;
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* アトリビューションごとに無害化し、中身が空になったものを除いて ` | ` で区切って並べる。
|
|
177
|
+
* 1 つも残らなければ空の DocumentFragment を返す。
|
|
178
|
+
*/
|
|
179
|
+
export const buildAttributionFragment = (
|
|
180
|
+
attributions: string[],
|
|
181
|
+
): DocumentFragment => {
|
|
182
|
+
const fragment = document.createDocumentFragment();
|
|
183
|
+
let isFirst = true;
|
|
184
|
+
for (const attribution of attributions) {
|
|
185
|
+
const sanitized = sanitizeAttribution(attribution);
|
|
186
|
+
if (!sanitized.hasChildNodes()) continue;
|
|
187
|
+
if (!isFirst) fragment.append(' | ');
|
|
188
|
+
fragment.append(sanitized);
|
|
189
|
+
isFirst = false;
|
|
190
|
+
}
|
|
191
|
+
return fragment;
|
|
192
|
+
};
|