@eliceio/cdk-cli 0.1.0-alpha.5 → 0.1.0-alpha.7
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 +110 -84
- package/es/cli.js +7 -22
- package/es/commands/build/index.d.ts +5 -3
- package/es/commands/build/index.js +20 -11
- package/es/commands/create/scaffold.d.ts +2 -0
- package/es/commands/create/scaffold.js +15 -1
- package/es/commands/dev/index.d.ts +1 -1
- package/es/commands/dev/index.js +1 -1
- package/es/commands/doctor/index.d.ts +1 -1
- package/es/commands/doctor/index.js +5 -6
- package/es/commands/setup/index.d.ts +4 -7
- package/es/commands/setup/index.js +41 -70
- package/es/commands/uninstall/index.d.ts +9 -8
- package/es/commands/uninstall/index.js +41 -47
- package/es/commands/update/index.d.ts +4 -2
- package/es/commands/update/index.js +27 -18
- package/es/core/collect.js +1 -1
- package/es/core/config.d.ts +1 -1
- package/es/core/config.js +3 -3
- package/es/{commands/mcp/index.d.ts → core/mcp.d.ts} +11 -18
- package/es/{commands/mcp/index.js → core/mcp.js} +29 -51
- package/es/core/minify.js +31 -2
- package/es/core/prepare.js +1 -1
- package/es/core/sandbox.d.ts +25 -0
- package/es/core/sandbox.js +110 -8
- package/es/{commands/skill/index.d.ts → core/skills.d.ts} +1 -17
- package/es/{commands/skill/index.js → core/skills.js} +6 -22
- package/es/dev/grading.d.ts +1 -1
- package/es/dev/grading.js +1 -1
- package/es/dev/host-page.js +20 -5
- package/es/dev/inject.d.ts +6 -0
- package/es/dev/inject.js +16 -1
- package/es/dev/mock-api.js +0 -16
- package/es/dev/server.d.ts +4 -2
- package/es/dev/server.js +11 -3
- package/es/rules/check.js +71 -8
- package/es/rules/csp.d.ts +26 -0
- package/es/rules/csp.js +42 -0
- package/es/rules/index.d.ts +2 -1
- package/es/rules/index.js +2 -1
- package/es/rules/refs.d.ts +12 -2
- package/es/rules/refs.js +50 -18
- package/es/rules/types.d.ts +5 -0
- package/es/rules/unused.d.ts +2 -0
- package/es/rules/unused.js +4 -3
- package/es/rules.json.js +2 -2
- package/package.json +2 -2
- package/rules.json +37 -15
- package/skills/_shared/always.md +2 -1
- package/skills/elice-content-create/SKILL.md +2 -1
- package/skills/elice-content-guide/SKILL.md +1 -1
- package/skills/elice-content-guide/topics/01-check-the-environment.md +2 -2
- package/skills/elice-content-guide/topics/02-design-the-material.md +2 -0
- package/skills/elice-content-guide/topics/03-create-the-project.md +2 -2
- package/skills/elice-content-guide/topics/04-rules.md +3 -1
- package/skills/elice-content-guide/topics/05-screen-code.md +44 -13
- package/skills/elice-content-guide/topics/07-move-existing-html.md +1 -1
- package/skills/elice-content-guide/topics/08-fix-check-errors.md +21 -18
- package/skills/elice-content-guide/topics/09-check.md +1 -0
- package/skills/elice-content-guide/topics/10-build.md +1 -1
- package/skills/elice-content-guide/topics/12-upload-with-the-material-mcp.md +2 -2
- package/skills/elice-content-migrate/SKILL.md +4 -3
- package/skills/elice-content-publish/SKILL.md +1 -1
- package/templates/_shared/lib/cdk-mock.js +3 -3
- package/templates/_shared/lib/elice-content-editor.d.ts +80 -0
- package/templates/_shared/lib/elice-content-editor.js +1062 -0
- package/templates/_shared/lib/elice-content.css +354 -1
- package/templates/_shared/lib/elice-content.js +10 -3
- package/templates/blank/README.md +27 -2
- package/templates/blank/commentary.txt +5 -0
- package/templates/blank/screens/edit.js +38 -17
- package/templates/blank/screens/instructor.js +20 -8
- package/templates/blank/screens/learn.js +151 -13
- package/templates/blank/styles.css +171 -0
- package/templates/blank/template.json +2 -2
- package/templates/quiz/README.md +2 -2
- package/templates/quiz/core/editor.d.ts +2 -0
- package/templates/quiz/core/editor.js +16 -6
- package/templates/quiz/core/model.js +1 -1
- package/templates/quiz/screens/edit.js +117 -24
- package/templates/quiz/styles.css +86 -12
- package/templates/quiz/template.json +1 -1
- package/templates/quiz/ui/templates/edit.d.ts +4 -0
- package/templates/quiz/ui/templates/edit.js +46 -10
- package/templates/quiz/ui/templates/page.js +1 -2
- package/templates/quiz/ui/templates/text.js +10 -7
- package/templates/quiz/ui/texts.js +13 -9
package/es/dev/inject.js
CHANGED
|
@@ -2,7 +2,13 @@
|
|
|
2
2
|
* dev에서만 콘텐츠 HTML의 <head> 맨 앞에 넣는 스크립트 (zip에는 들어가지 않음).
|
|
3
3
|
* - 키트가 흉내 서버를 쓰도록 API 주소를, 콘텐츠 주소를 직접 열어 mock으로 돌 때 쓸 로컬 채점 설정 주소를 알려 줌 (window.__ECDK_DEV__)
|
|
4
4
|
* - 콘솔 오류 · 처리 안 된 예외 · 불러오지 못한 파일을 터미널로 보냄
|
|
5
|
+
* - 콘텐츠 CSP(rules/csp.ts)가 막은 요청(securitypolicyviolation)을 dev 화면(부모 창, 호스트 출처로만)과 터미널에 알림.
|
|
6
|
+
* 키트가 아니라 여기서 듣는 이유: 이 스크립트는 ecdk dev 응답에만 들어가 운영 LXP에서는 돌지 않고, 다른 스크립트보다
|
|
7
|
+
* 먼저 돌아 HTML의 <img> · CSS 글꼴처럼 키트(모듈 스크립트)가 뜨기 전에 막힌 요청도 놓치지 않으며, 키트를 쓰지 않는
|
|
8
|
+
* 옮겨 온 HTML에서도 동작한다
|
|
5
9
|
*/
|
|
10
|
+
/** dev 스크립트 → dev 화면 메시지 (SDK 메시지 source와 다름) */
|
|
11
|
+
const DEV_MESSAGE_SOURCE = 'ecdk-dev';
|
|
6
12
|
function devScript(hostOrigin) {
|
|
7
13
|
const api = `${hostOrigin}/api`;
|
|
8
14
|
const log = `${hostOrigin}/__ecdk/log`;
|
|
@@ -23,6 +29,15 @@ function devScript(hostOrigin) {
|
|
|
23
29
|
else send('error', (e.error && e.error.stack) || e.message);
|
|
24
30
|
}, true);
|
|
25
31
|
addEventListener('unhandledrejection', (e) => send('error', 'Promise 오류: ' + ((e.reason && e.reason.stack) || e.reason)));
|
|
32
|
+
const blocked = new Set();
|
|
33
|
+
addEventListener('securitypolicyviolation', (e) => {
|
|
34
|
+
const payload = { blockedURI: e.blockedURI || '(알 수 없음)', violatedDirective: e.effectiveDirective || e.violatedDirective };
|
|
35
|
+
const key = payload.blockedURI + ' ' + payload.violatedDirective;
|
|
36
|
+
if (blocked.has(key)) return;
|
|
37
|
+
blocked.add(key);
|
|
38
|
+
try { parent.postMessage({ source: ${JSON.stringify(DEV_MESSAGE_SOURCE)}, type: 'csp-violation', payload }, ${JSON.stringify(hostOrigin)}); } catch (err) {}
|
|
39
|
+
send('warn', '막힌 외부 요청: ' + payload.blockedURI + ' (' + payload.violatedDirective + ')');
|
|
40
|
+
});
|
|
26
41
|
})();
|
|
27
42
|
</script>`;
|
|
28
43
|
}
|
|
@@ -35,4 +50,4 @@ function injectDevScript(html, hostOrigin) {
|
|
|
35
50
|
return html.slice(0, at) + script + html.slice(at);
|
|
36
51
|
}
|
|
37
52
|
|
|
38
|
-
export { devScript, injectDevScript };
|
|
53
|
+
export { DEV_MESSAGE_SOURCE, devScript, injectDevScript };
|
package/es/dev/mock-api.js
CHANGED
|
@@ -36,7 +36,6 @@ const TOKEN_SCENARIOS = Object.freeze({
|
|
|
36
36
|
});
|
|
37
37
|
const isTokenScenario = v => typeof v === 'string' && Object.hasOwn(TOKEN_SCENARIOS, v);
|
|
38
38
|
const TOKEN_TTL_SECONDS = 7200;
|
|
39
|
-
const SESSION_SECONDS = 12 * 3600;
|
|
40
39
|
const b64url = s => Buffer.from(s).toString('base64url');
|
|
41
40
|
const nowSeconds = () => Math.floor(Date.now() / 1000);
|
|
42
41
|
/** SDK는 서명을 검사하지 않고 claim만 읽는다. 흉내 서버도 서명은 보지 않는다 */
|
|
@@ -143,21 +142,6 @@ async function handleMockApi(req, res, path, opts) {
|
|
|
143
142
|
} = opts;
|
|
144
143
|
const method = req.method ?? 'GET';
|
|
145
144
|
const log = m => opts.onEvent?.(m);
|
|
146
|
-
if (method === 'POST' && path === '/auth/token/refresh') {
|
|
147
|
-
const claims = readClaims(req);
|
|
148
|
-
if (!claims) return fail(res, 401, 'AUTHENTICATION_INVALID', 'token expired (dev)');
|
|
149
|
-
if (nowSeconds() - claims.session_started_at > SESSION_SECONDS) return fail(res, 401, 'AUTHENTICATION_INVALID', 'session expired (dev)', [{
|
|
150
|
-
reason: 'session_expired'
|
|
151
|
-
}]);
|
|
152
|
-
const exp = nowSeconds() + TOKEN_TTL_SECONDS;
|
|
153
|
-
return send(res, 200, {
|
|
154
|
-
access_token: sign({
|
|
155
|
-
...claims,
|
|
156
|
-
exp
|
|
157
|
-
}),
|
|
158
|
-
expires_at: new Date(exp * 1000).toISOString()
|
|
159
|
-
});
|
|
160
|
-
}
|
|
161
145
|
const m = path.match(/^\/materials\/([0-9a-f-]{36})(\/me|\/draft|\/submissions|\/submissions\/me)?$/);
|
|
162
146
|
if (!m) return fail(res, 404, 'RESOURCE_NOT_FOUND', `no route: ${method} ${path}`);
|
|
163
147
|
const claims = readClaims(req);
|
package/es/dev/server.d.ts
CHANGED
|
@@ -25,8 +25,10 @@ export declare class DevPortError extends Error {
|
|
|
25
25
|
/**
|
|
26
26
|
* 로컬에서 운영과 같은 조건으로 콘텐츠를 띄운다.
|
|
27
27
|
* - 호스트(localhost): LXP 흉내 화면 + elice-material 흉내 API(/api) + 콘솔 수집
|
|
28
|
-
* - 콘텐츠(127.0.0.1, 다른 출처): build와 같은 파일(모듈 묶기 포함)을 운영
|
|
29
|
-
*
|
|
28
|
+
* - 콘텐츠(127.0.0.1, 다른 출처): build와 같은 파일(모듈 묶기 포함)을 운영 콘텐츠 CSP 초안(rules/csp.ts,
|
|
29
|
+
* 서버 수정 제안 1번과 같은 값, sandbox allow-scripts allow-same-origin)으로. 콘텐츠는 제 출처(127.0.0.1:<port+1>)로 돌아
|
|
30
|
+
* 저장소는 호스트와 따로 쓰고, 제 파일 요청은 같은 출처라 막히지 않는다. 외부 이미지 · 글꼴 · fetch 등은 LXP에서처럼
|
|
31
|
+
* 막히고, 막힌 요청은 dev 스크립트가 화면 기록 · 터미널에 "막힌 외부 요청"으로 알린다. LXP 자료 파일 서버처럼 CORS 헤더는 주지 않는다
|
|
30
32
|
* - 원본이 바뀌면 다시 준비 · 검사 → 호스트가 iframe을 다시 띄움
|
|
31
33
|
*/
|
|
32
34
|
export declare function startDevServer(opts: DevServerOptions): Promise<DevServer>;
|
package/es/dev/server.js
CHANGED
|
@@ -8,6 +8,7 @@ import { projectCheckOptions } from '../core/project-check.js';
|
|
|
8
8
|
import { inlineModuleScripts } from '../core/sandbox.js';
|
|
9
9
|
import { missingSdkMessage } from '../core/sdk.js';
|
|
10
10
|
import { checkFiles } from '../rules/check.js';
|
|
11
|
+
import { contentCsp } from '../rules/csp.js';
|
|
11
12
|
import '../rules/spec.js';
|
|
12
13
|
import 'fflate';
|
|
13
14
|
import { hostPage } from './host-page.js';
|
|
@@ -85,8 +86,10 @@ async function servedFiles(prepared, log) {
|
|
|
85
86
|
/**
|
|
86
87
|
* 로컬에서 운영과 같은 조건으로 콘텐츠를 띄운다.
|
|
87
88
|
* - 호스트(localhost): LXP 흉내 화면 + elice-material 흉내 API(/api) + 콘솔 수집
|
|
88
|
-
* - 콘텐츠(127.0.0.1, 다른 출처): build와 같은 파일(모듈 묶기 포함)을 운영
|
|
89
|
-
*
|
|
89
|
+
* - 콘텐츠(127.0.0.1, 다른 출처): build와 같은 파일(모듈 묶기 포함)을 운영 콘텐츠 CSP 초안(rules/csp.ts,
|
|
90
|
+
* 서버 수정 제안 1번과 같은 값, sandbox allow-scripts allow-same-origin)으로. 콘텐츠는 제 출처(127.0.0.1:<port+1>)로 돌아
|
|
91
|
+
* 저장소는 호스트와 따로 쓰고, 제 파일 요청은 같은 출처라 막히지 않는다. 외부 이미지 · 글꼴 · fetch 등은 LXP에서처럼
|
|
92
|
+
* 막히고, 막힌 요청은 dev 스크립트가 화면 기록 · 터미널에 "막힌 외부 요청"으로 알린다. LXP 자료 파일 서버처럼 CORS 헤더는 주지 않는다
|
|
90
93
|
* - 원본이 바뀌면 다시 준비 · 검사 → 호스트가 iframe을 다시 띄움
|
|
91
94
|
*/
|
|
92
95
|
async function startDevServer(opts) {
|
|
@@ -141,8 +144,13 @@ async function startDevServer(opts) {
|
|
|
141
144
|
// 콘텐츠 서버
|
|
142
145
|
const content = createServer((req, res) => {
|
|
143
146
|
const url = new URL(req.url ?? '/', 'http://x');
|
|
147
|
+
// CONTENT_HOST: 콘텐츠 출처, MATERIAL_API: 흉내 API · dev 기록이 있는 호스트 출처, LXP_ORIGINS: 흉내 화면 출처
|
|
144
148
|
const headers = {
|
|
145
|
-
'Content-Security-Policy':
|
|
149
|
+
'Content-Security-Policy': contentCsp({
|
|
150
|
+
contentHost: contentOrigin,
|
|
151
|
+
materialApi: hostOrigin,
|
|
152
|
+
lxpOrigins: hostOrigin
|
|
153
|
+
}),
|
|
146
154
|
'X-Content-Type-Options': 'nosniff',
|
|
147
155
|
'Referrer-Policy': 'no-referrer',
|
|
148
156
|
'Cache-Control': 'no-store'
|
package/es/rules/check.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { zipSync } from 'fflate';
|
|
2
|
+
import { isAllowedExternal, allowedOrigins } from './csp.js';
|
|
2
3
|
import { parseManifest } from './manifest.js';
|
|
3
4
|
import { isUnsafePath, extname, globToRegExp, resolveRef } from './path.js';
|
|
4
|
-
import { lineAt, parseTags, extractRefs, classifyRef } from './refs.js';
|
|
5
|
+
import { lineAt, parseTags, extractRefs, classifyRef, FRAME_TAGS } from './refs.js';
|
|
5
6
|
import { compareVersions } from './semver.js';
|
|
6
7
|
import { lineSkipper } from './skip.js';
|
|
7
8
|
import { rules } from './spec.js';
|
|
@@ -105,7 +106,7 @@ function checkLegacyFiles(opts, add) {
|
|
|
105
106
|
const SDK_UPDATE_COMMAND = 'npm update @eliceio/cdk';
|
|
106
107
|
/**
|
|
107
108
|
* SDK 버전 (ADR 0010). metadata.json build.sdk가 rules.json minVersions.sdk보다 낮으면 오류:
|
|
108
|
-
* LXP 프로토콜과 맞지 않아 저장 · 제출이 안 될 수 있다 (
|
|
109
|
+
* LXP 프로토콜과 맞지 않아 저장 · 제출이 안 될 수 있다 (alpha.3 이하는 LXP 편집 화면 초안 저장이 422). 옛 lib/cdk.js 복사본 프로젝트는 sdk.lib-copy 경고로 알린다
|
|
109
110
|
*/
|
|
110
111
|
function checkSdk(manifest, spec, opts, add) {
|
|
111
112
|
// 옛 머리말은 "1.0.0 (브랜치@커밋)"일 수 있어 첫 낱말만 비교한다
|
|
@@ -125,6 +126,54 @@ function checkSdk(manifest, spec, opts, add) {
|
|
|
125
126
|
function blankBundles(html) {
|
|
126
127
|
return html.replace(/(<script\b[^>]*\sdata-ecdk-bundle\b[^>]*>)([\s\S]*?)(<\/script\s*>)/gi, (_, open, body, close) => open + body.replace(/[^\n]/g, '') + close);
|
|
127
128
|
}
|
|
129
|
+
/** ecdk가 넣는 lib/ 파일 (SDK · 키트). 작성자가 넣은 라이브러리가 아니라 ref.vendor-external-url에서 뺀다 */
|
|
130
|
+
const ECDK_LIB_FILES = new Set(['lib/cdk.js', 'lib/elice-content.js', 'lib/elice-content-editor.js', 'lib/cdk-mock.js']);
|
|
131
|
+
/** 작성자가 내려받아 넣은 라이브러리로 보는 폴더 · 파일 이름 */
|
|
132
|
+
const VENDOR_DIR = /^(?:vendors?|libs?|third[-_]?party|external|plugins?)$/i;
|
|
133
|
+
const VENDOR_FILE = /[.-]min\.m?js$/i;
|
|
134
|
+
function isVendorFile(path) {
|
|
135
|
+
if (ECDK_LIB_FILES.has(path) || !/\.m?js$/i.test(path)) return false;
|
|
136
|
+
return VENDOR_FILE.test(path) || path.split('/').slice(0, -1).some(seg => VENDOR_DIR.test(seg));
|
|
137
|
+
}
|
|
138
|
+
const ABSOLUTE_URL = /\bhttps?:\/\/[A-Za-z0-9][^\s'"`<>()\\]*/g;
|
|
139
|
+
/**
|
|
140
|
+
* 라이브러리가 실행 중 부르지 않는 주소: 라이선스 · 문서 · 오류 안내 링크, XML 이름공간, 로컬 주소.
|
|
141
|
+
* 너무 넓히면 실제 호출을 놓치므로 흔한 것만 (example.com 등은 남김)
|
|
142
|
+
*/
|
|
143
|
+
const IGNORED_URL_HOST = /^(?:(?:[\w-]+\.)*(?:github\.com|github\.io|gitlab\.com|githubusercontent\.com|opensource\.org|mit-license\.org|apache\.org|gnu\.org|creativecommons\.org|spdx\.org|w3\.org|whatwg\.org|ietf\.org|ecma-international\.org|mozilla\.org|npmjs\.(?:com|org)|stackoverflow\.com|wikipedia\.org|jquery\.(?:com|org)|reactjs\.org|react\.dev|fb\.me|vuejs\.org|angular\.io|svelte\.dev|lodash\.com|underscorejs\.org|momentjs\.com|feross\.org|purl\.org|schema\.org|xmlsoap\.org|adobe\.com|microsoft\.com|openxmlformats\.org|goo\.gl|bit\.ly)|localhost|127\.0\.0\.1)$/i;
|
|
144
|
+
/** 라이브러리 파일 안의 실행 중 부를 수 있는 외부 주소 (호스트별 처음 하나) */
|
|
145
|
+
function vendorExternalUrls(text, spec) {
|
|
146
|
+
const allowed = new Set(allowedOrigins(spec));
|
|
147
|
+
const seen = new Set();
|
|
148
|
+
const out = [];
|
|
149
|
+
for (const m of text.matchAll(ABSOLUTE_URL)) {
|
|
150
|
+
const before = text.slice(Math.max(0, m.index - 40), m.index);
|
|
151
|
+
// sourceMappingURL · xmlns="…" · 주석 안 라이선스 줄(@license · @see · @link)
|
|
152
|
+
if (/(?:sourceMappingURL=|xmlns(?::\w+)?\s*[=:,]\s*['"]?|@(?:license|see|link|author|homepage)\b[^\n*]*)$/i.test(before)) continue;
|
|
153
|
+
let url;
|
|
154
|
+
try {
|
|
155
|
+
url = new URL(m[0]);
|
|
156
|
+
} catch {
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (IGNORED_URL_HOST.test(url.hostname) || allowed.has(url.origin) || seen.has(url.hostname)) continue;
|
|
160
|
+
seen.add(url.hostname);
|
|
161
|
+
out.push({
|
|
162
|
+
url: m[0],
|
|
163
|
+
line: lineAt(text, m.index)
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* html.iframe 대상인지. object · embed는 늘. iframe · frame은 src로 무엇을 띄울 때만: src가 없거나 빈 값 ·
|
|
170
|
+
* about:blank · about:srcdoc이면 통과 (srcdoc · JS로 채우는 미리보기는 frame-src 'none'에 걸리지 않음, Chromium 확인)
|
|
171
|
+
*/
|
|
172
|
+
function framesSomething(t) {
|
|
173
|
+
if (t.name === 'object' || t.name === 'embed') return true;
|
|
174
|
+
const src = t.attrs.get('src')?.trim().toLowerCase();
|
|
175
|
+
return src !== undefined && src !== '' && src !== 'about:blank' && src !== 'about:srcdoc';
|
|
176
|
+
}
|
|
128
177
|
function textKind(path) {
|
|
129
178
|
const ext = extname(path);
|
|
130
179
|
if (ext === 'html' || ext === 'htm') return 'html';
|
|
@@ -182,7 +231,7 @@ function checkFiles(input, opts = {}) {
|
|
|
182
231
|
if (!exact.has(file)) add('manifest.entry-missing', `${spec.manifest.file}에 적은 ${mode} 화면 파일이 없습니다: ${file}`, spec.manifest.file);
|
|
183
232
|
}
|
|
184
233
|
const commentaryFile = manifest.commentary === undefined ? undefined : files.find(f => f.path === manifest.commentary);
|
|
185
|
-
// LXP 업로드는 학습 참고 내용이 없는 자료 본문을 거절한다 (
|
|
234
|
+
// LXP 업로드는 학습 참고 내용이 없는 자료 본문을 거절한다 (실제 업로드로 확인. 스펙은 선택이었음)
|
|
186
235
|
if ((manifest.kind ?? spec.manifest.defaultKind) !== 'description' && manifest.commentary === undefined) add('manifest.commentary-missing', `학습 참고 내용 파일이 없어 LXP 업로드가 거절됩니다. 프로젝트 맨 위에 ${spec.manifest.commentaryFile}(이 자료의 핵심 개념 · 활동 · 문제 의도, 정답 제외)을 만들고 ${spec.manifest.file}에 "commentary": "${spec.manifest.commentaryFile}"를 적어 주세요.`, spec.manifest.file);
|
|
187
236
|
if (manifest.commentary !== undefined && !commentaryFile) add('manifest.entry-missing', `${spec.manifest.file}에 적은 학습 참고 내용 파일이 없습니다: ${manifest.commentary}`, spec.manifest.file);
|
|
188
237
|
// LXP 학습 참고 내용 칸으로 옮길 텍스트라 UTF-8이어야 한다 (메모장 ANSI · EUC-KR 저장이면 깨짐)
|
|
@@ -257,7 +306,8 @@ function checkFiles(input, opts = {}) {
|
|
|
257
306
|
const type = classifyRef(ref.value);
|
|
258
307
|
if (type === 'skip') return;
|
|
259
308
|
if (type === 'external') {
|
|
260
|
-
|
|
309
|
+
const font = ref.role === 'resource' && (ref.as === 'style' ? isAllowedExternal(ref.value, 'style-src', spec) : /\.(?:woff2?|ttf|otf|eot)(?:[?#]|$)/i.test(ref.value) && isAllowedExternal(ref.value, 'font-src', spec));
|
|
310
|
+
if (ref.role === 'script') add('ref.external-script', `외부 스크립트를 불러옵니다: ${ref.value}. 스크립트 파일을 zip 안에 넣고 상대경로로 불러와 주세요.`, from, ref.line);else if (ref.role === 'resource' && /^http:/i.test(ref.value)) add('ref.insecure', `http:// 리소스는 https 페이지와 콘텐츠 CSP가 막습니다: ${ref.value}. 파일을 zip 안에 넣고 상대경로로 불러와 주세요.`, from, ref.line);else if (font) add('ref.external-font', `허용 목록의 외부 글꼴을 불러옵니다: ${ref.value}. 망분리 기관에서는 받지 못해 기본 글꼴로 보일 수 있습니다. 꼭 필요한 글꼴이면 zip에 넣어 주세요 (글꼴 파일 또는 CSS data URI).`, from, ref.line);else if (ref.role === 'resource') add('ref.external-request', `zip 밖 리소스를 불러옵니다: ${ref.value}. LXP 콘텐츠 CSP가 외부 이미지 · 글꼴 · 영상 · CSS를 막아 보이지 않습니다. 파일을 zip 안에 넣고 상대경로로 불러와 주세요 (글꼴은 파일 또는 data URI).`, from, ref.line);
|
|
261
311
|
return;
|
|
262
312
|
}
|
|
263
313
|
if (type === 'root') add('ref.root-absolute', `/로 시작하는 경로는 배포 주소에서 깨집니다. 상대경로로 바꿔 주세요: ${ref.value}`, from, ref.line);
|
|
@@ -300,18 +350,31 @@ function checkFiles(input, opts = {}) {
|
|
|
300
350
|
if (!kindOf || matchExclude(f.path, spec.excluded.dev)) continue;
|
|
301
351
|
const text = decoder.decode(f.data);
|
|
302
352
|
const tags = kindOf === 'html' ? parseTags(text) : [];
|
|
303
|
-
|
|
353
|
+
const vendor = isVendorFile(f.path);
|
|
354
|
+
// ecdk build가 묶은 모듈 본문(npm 라이브러리 포함)은 원본으로 이미 검사했다 (줄 번호는 그대로)
|
|
355
|
+
const refText = kindOf === 'html' ? blankBundles(text) : text;
|
|
356
|
+
for (const ref of extractRefs(kindOf, refText, tags, {
|
|
357
|
+
jsResources: !vendor
|
|
358
|
+
})) checkRef(f.path, ref);
|
|
359
|
+
if (vendor) {
|
|
360
|
+
const skipVendor = lineSkipper(text);
|
|
361
|
+
const urls = vendorExternalUrls(text, spec).filter(u => !skipVendor.isSkipped(u.line, 'ref.vendor-external-url'));
|
|
362
|
+
const first = urls[0];
|
|
363
|
+
if (first) add('ref.vendor-external-url', `라이브러리 파일에 외부 주소가 있습니다: ${urls.slice(0, 3).map(u => u.url).join(', ')}${urls.length > 3 ? ` 외 ${urls.length - 3}곳` : ''}. 라이브러리가 실행 중 외부(글꼴 · wasm · 지도 타일 · API)를 부르면 LXP 콘텐츠 CSP가 막습니다. ecdk dev로 열어 "막힌 외부 요청" 로그를 확인하고, 필요한 파일은 zip에 넣어 라이브러리 설정으로 상대경로를 주세요.`, f.path, first.line);
|
|
364
|
+
}
|
|
304
365
|
for (const t of tags) {
|
|
305
366
|
// <base href>는 그 페이지 모든 상대경로의 기준을 바꾼다. 페이지 자기 폴더(./)만 허용한다:
|
|
306
367
|
// /·외부 주소·zip 밖(../)은 배포 주소(/s/{서명}/) 밖으로 나가고, 하위 폴더는 참조 검사(파일 위치 기준)와 어긋난다
|
|
307
368
|
const baseHref = t.name === 'base' ? t.attrs.get('href')?.trim() : undefined;
|
|
308
369
|
const baseError = baseHref === undefined ? null : baseHrefError(f.path, baseHref);
|
|
309
370
|
if (baseHref !== undefined && baseError) add('ref.root-absolute', `<base href="${baseHref}">${baseError}`, f.path, t.line);
|
|
310
|
-
//
|
|
371
|
+
// 콘텐츠 서버의 sandbox 헤더에 allow-same-origin이 없으면 콘텐츠 출처가 null이고 파일 서버가 CORS 헤더를 주지 않아,
|
|
372
|
+
// 모듈 스크립트 파일을 받지 못한다
|
|
311
373
|
const src = t.name === 'script' ? t.attrs.get('src')?.trim() : undefined;
|
|
312
|
-
if (src !== undefined && t.attrs.get('type')?.trim().toLowerCase() === 'module' && classifyRef(src) === 'local' && kind !== 'dir' && !opts.bundlesModules) add('sandbox.module-src', `<script type="module" src="${src}">는 LXP에서 막혀(CORS) 화면이 "불러오는 중"에서 멈춥니다. ecdk build로 만들면 HTML 안에 묶어 넣습니다. 직접 묶으려면 본문을 넣은 <script type="module">이나 일반 <script src>로 바꿔 주세요.`, f.path, t.line);
|
|
374
|
+
if (src !== undefined && t.attrs.get('type')?.trim().toLowerCase() === 'module' && classifyRef(src) === 'local' && kind !== 'dir' && !opts.bundlesModules) add('sandbox.module-src', `<script type="module" src="${src}">는 콘텐츠 서버의 sandbox 헤더에 allow-same-origin이 없는 LXP에서 막혀(CORS) 화면이 "불러오는 중"에서 멈춥니다. ecdk build로 만들면 HTML 안에 묶어 넣습니다. 직접 묶으려면 본문을 넣은 <script type="module">이나 일반 <script src>로 바꿔 주세요.`, f.path, t.line);
|
|
313
375
|
if (t.name === 'img' && !t.attrs.has('alt')) add('html.img-alt', `대체 텍스트(alt)가 없는 이미지입니다.`, f.path, t.line);
|
|
314
|
-
if (t.name
|
|
376
|
+
if (FRAME_TAGS.has(t.name) && framesSomething(t)) add('html.iframe', t.name === 'iframe' || t.name === 'frame' ? `<${t.name} src="${t.attrs.get('src')?.trim()}">: 외부 페이지 · 파일을 iframe으로 띄우면 CSP(frame-src 'none')가 막음 (zip 안 파일도). 영상은 Elice 비디오 자료로 따로 올리고, 다른 내용은 이 HTML 안에 넣어 주세요. 코드 미리보기는 srcdoc 사용 가능.` : `<${t.name}>는 LXP 콘텐츠 CSP(object-src 'none')가 막아 빈 칸으로 보입니다. 영상은 Elice 비디오 자료로 따로 올리고, 다른 문서는 내용을 이 HTML 안에 넣어 주세요.`, f.path, t.line);
|
|
377
|
+
if (t.name === 'form') add('html.form', 'form 제출은 sandbox · 콘텐츠 CSP(form-action)가 막습니다. 버튼 click 처리와 SDK 제출을 써 주세요.', f.path, t.line);
|
|
315
378
|
}
|
|
316
379
|
if (kindOf === 'css') continue;
|
|
317
380
|
const skip = lineSkipper(text);
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { RulesSpec } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* 운영 콘텐츠 응답 CSP 초안 (서버에 제안한 값).
|
|
4
|
+
* 서버 CSP가 확정되면 이 목록을 맞춘다. `ecdk dev` 콘텐츠 서버가 이 값으로 응답하고, CLI README가 같은 글을 보인다
|
|
5
|
+
* (`docs.test.ts`가 대조). 허용 외부 출처는 rules.json `externalAllow` 한 곳에서 해당 지시어에 더한다.
|
|
6
|
+
* - sandbox는 `allow-same-origin`까지 (LXP iframe 속성과 같게, 콘텐츠는 제 하위 도메인 출처로 돈다)
|
|
7
|
+
* - `'self'` 대신 호스트를 직접 적는다 (헤더에 allow-same-origin이 없는 서버에서는 출처가 null이라 'self' 해석이 브라우저마다 다를 수 있음)
|
|
8
|
+
* - `webrtc 'block'`은 지원하는 브라우저에서만 (모르는 브라우저는 무시)
|
|
9
|
+
*/
|
|
10
|
+
export declare const CONTENT_CSP: readonly (readonly [string, ...string[]])[];
|
|
11
|
+
export interface CspValues {
|
|
12
|
+
/** 콘텐츠를 내주는 출처 (dev: http://127.0.0.1:<포트+1>) */
|
|
13
|
+
contentHost: string;
|
|
14
|
+
/** SDK가 부르는 material API 출처 (dev: 흉내 서버 http://localhost:<포트>) */
|
|
15
|
+
materialApi: string;
|
|
16
|
+
/** 콘텐츠를 iframe으로 띄우는 LXP 출처 (dev: 흉내 화면 http://localhost:<포트>) */
|
|
17
|
+
lxpOrigins: string;
|
|
18
|
+
}
|
|
19
|
+
/** 콘텐츠 CSP 헤더 값. values가 없으면 자리표시({CONTENT_HOST} 등) 그대로 (문서용) */
|
|
20
|
+
export declare function contentCsp(values?: CspValues, spec?: RulesSpec): string;
|
|
21
|
+
/**
|
|
22
|
+
* 외부 주소가 rules.json `externalAllow`의 그 지시어 출처인지. `//host`(프로토콜 생략)는 https로 본다
|
|
23
|
+
*/
|
|
24
|
+
export declare function isAllowedExternal(url: string, directive: keyof NonNullable<RulesSpec['externalAllow']>, spec?: RulesSpec): boolean;
|
|
25
|
+
/** 허용 목록의 모든 출처 (라이브러리 외부 주소 경고에서 뺄 때) */
|
|
26
|
+
export declare function allowedOrigins(spec?: RulesSpec): string[];
|
package/es/rules/csp.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { rules } from './spec.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 운영 콘텐츠 응답 CSP 초안 (서버에 제안한 값).
|
|
5
|
+
* 서버 CSP가 확정되면 이 목록을 맞춘다. `ecdk dev` 콘텐츠 서버가 이 값으로 응답하고, CLI README가 같은 글을 보인다
|
|
6
|
+
* (`docs.test.ts`가 대조). 허용 외부 출처는 rules.json `externalAllow` 한 곳에서 해당 지시어에 더한다.
|
|
7
|
+
* - sandbox는 `allow-same-origin`까지 (LXP iframe 속성과 같게, 콘텐츠는 제 하위 도메인 출처로 돈다)
|
|
8
|
+
* - `'self'` 대신 호스트를 직접 적는다 (헤더에 allow-same-origin이 없는 서버에서는 출처가 null이라 'self' 해석이 브라우저마다 다를 수 있음)
|
|
9
|
+
* - `webrtc 'block'`은 지원하는 브라우저에서만 (모르는 브라우저는 무시)
|
|
10
|
+
*/
|
|
11
|
+
const CONTENT_CSP = [['sandbox', 'allow-scripts', 'allow-same-origin'], ['default-src', "'none'"], ['script-src', '{CONTENT_HOST}', "'unsafe-inline'", "'unsafe-eval'", 'blob:'], ['style-src', '{CONTENT_HOST}', "'unsafe-inline'"], ['img-src', '{CONTENT_HOST}', 'data:', 'blob:'], ['font-src', '{CONTENT_HOST}', 'data:'], ['media-src', '{CONTENT_HOST}', 'data:', 'blob:'], ['connect-src', '{MATERIAL_API}'], ['worker-src', 'blob:'], ['frame-src', "'none'"], ['form-action', "'none'"], ['object-src', "'none'"], ['base-uri', '{CONTENT_HOST}'], ['webrtc', "'block'"], ['frame-ancestors', '{LXP_ORIGINS}']];
|
|
12
|
+
/** 콘텐츠 CSP 헤더 값. values가 없으면 자리표시({CONTENT_HOST} 등) 그대로 (문서용) */
|
|
13
|
+
function contentCsp(values, spec = rules) {
|
|
14
|
+
const fill = values ? {
|
|
15
|
+
'{CONTENT_HOST}': values.contentHost,
|
|
16
|
+
'{MATERIAL_API}': values.materialApi,
|
|
17
|
+
'{LXP_ORIGINS}': values.lxpOrigins
|
|
18
|
+
} : {};
|
|
19
|
+
const allow = spec.externalAllow ?? {};
|
|
20
|
+
return CONTENT_CSP.map(([name, ...sources]) => {
|
|
21
|
+
const extra = allow[name] ?? [];
|
|
22
|
+
return [name, ...sources.map(s => fill[s] ?? s), ...extra].join(' ');
|
|
23
|
+
}).join('; ');
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* 외부 주소가 rules.json `externalAllow`의 그 지시어 출처인지. `//host`(프로토콜 생략)는 https로 본다
|
|
27
|
+
*/
|
|
28
|
+
function isAllowedExternal(url, directive, spec = rules) {
|
|
29
|
+
const list = spec.externalAllow?.[directive] ?? [];
|
|
30
|
+
try {
|
|
31
|
+
const origin = new URL(url.startsWith('//') ? `https:${url}` : url).origin;
|
|
32
|
+
return list.includes(origin);
|
|
33
|
+
} catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** 허용 목록의 모든 출처 (라이브러리 외부 주소 경고에서 뺄 때) */
|
|
38
|
+
function allowedOrigins(spec = rules) {
|
|
39
|
+
return Object.values(spec.externalAllow ?? {}).flat();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export { CONTENT_CSP, allowedOrigins, contentCsp, isAllowedExternal };
|
package/es/rules/index.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
export { checkFiles } from './check.js';
|
|
2
|
+
export { allowedOrigins, CONTENT_CSP, contentCsp, type CspValues, isAllowedExternal, } from './csp.js';
|
|
2
3
|
export { COMPLETION_POLICIES_IGNORED, graderTypeError, LEGACY_COMPLETION_FIELDS, LEGACY_COMPLETION_SCREENS, type ManifestWarning, parseManifest, serializeManifest, stripCompletionPolicy, } from './manifest.js';
|
|
3
4
|
export { globToRegExp } from './path.js';
|
|
4
5
|
export { commentOnlyLines, lineSkipper } from './skip.js';
|
|
5
6
|
export { rules, RULES_VERSION } from './spec.js';
|
|
6
|
-
export { findUnreferenced } from './unused.js';
|
|
7
|
+
export { findUnreferenced, TEXT_FILE } from './unused.js';
|
|
7
8
|
export { filesFromHtml, filesFromZip, ZipLimitError } from './zip.js';
|
|
8
9
|
export type * from './types.js';
|
package/es/rules/index.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
export { checkFiles } from './check.js';
|
|
2
|
+
export { CONTENT_CSP, allowedOrigins, contentCsp, isAllowedExternal } from './csp.js';
|
|
2
3
|
export { COMPLETION_POLICIES_IGNORED, LEGACY_COMPLETION_FIELDS, LEGACY_COMPLETION_SCREENS, graderTypeError, parseManifest, serializeManifest, stripCompletionPolicy } from './manifest.js';
|
|
3
4
|
export { globToRegExp } from './path.js';
|
|
4
5
|
export { commentOnlyLines, lineSkipper } from './skip.js';
|
|
5
6
|
export { RULES_VERSION, rules } from './spec.js';
|
|
6
|
-
export { findUnreferenced } from './unused.js';
|
|
7
|
+
export { TEXT_FILE, findUnreferenced } from './unused.js';
|
|
7
8
|
export { ZipLimitError, filesFromHtml, filesFromZip } from './zip.js';
|
package/es/rules/refs.d.ts
CHANGED
|
@@ -4,16 +4,26 @@ export interface Ref {
|
|
|
4
4
|
value: string;
|
|
5
5
|
line: number;
|
|
6
6
|
role: RefRole;
|
|
7
|
+
/** 스타일시트로 불러옴 (`<link rel="stylesheet">` · CSS `@import`): CSP style-src 허용 목록과 비교 */
|
|
8
|
+
as?: 'style';
|
|
7
9
|
}
|
|
8
10
|
export interface HtmlTag {
|
|
9
11
|
name: string;
|
|
10
12
|
attrs: Map<string, string>;
|
|
11
13
|
line: number;
|
|
12
14
|
}
|
|
15
|
+
/** 다른 문서를 안에 띄우는 태그: 외부 주소는 html.iframe이 따로 알린다 (안 파일은 ref.missing만 봄) */
|
|
16
|
+
export declare const FRAME_TAGS: Set<string>;
|
|
13
17
|
declare function lineAt(text: string, index: number): number;
|
|
14
18
|
export declare function parseTags(html: string): HtmlTag[];
|
|
15
|
-
/**
|
|
16
|
-
|
|
19
|
+
/**
|
|
20
|
+
* HTML 태그 속성, CSS url()·@import, JS 정적·동적 import의 문자열 리터럴 참조, JS가 외부 리소스를 넣는 흔한 모양
|
|
21
|
+
* (JS_RESOURCE, 외부 주소만). 스크립트가 만든 경로(fetch 등)는 못 잡는다.
|
|
22
|
+
* `jsResources: false`: 라이브러리 파일은 외부 리소스 모양을 보지 않는다 (ref.vendor-external-url 경고가 맡음)
|
|
23
|
+
*/
|
|
24
|
+
export declare function extractRefs(kind: 'html' | 'css' | 'js', text: string, tags?: HtmlTag[], { jsResources }?: {
|
|
25
|
+
jsResources?: boolean | undefined;
|
|
26
|
+
}): Ref[];
|
|
17
27
|
export type RefKind = 'local' | 'root' | 'external' | 'skip';
|
|
18
28
|
export declare function classifyRef(value: string): RefKind;
|
|
19
29
|
export { lineAt };
|
package/es/rules/refs.js
CHANGED
|
@@ -1,23 +1,41 @@
|
|
|
1
1
|
const TAG = /<([a-zA-Z][\w-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>/g;
|
|
2
2
|
const ATTR = /([^\s"'=<>/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;
|
|
3
3
|
const RAW_BLOCK = /<(script|style)\b[^>]*>([\s\S]*?)<\/\1\s*>/gi;
|
|
4
|
-
const CSS_URL = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"\s]+))\s*\)
|
|
4
|
+
const CSS_URL = /(?<!@import\s*)url\(\s*(?:"([^"]*)"|'([^']*)'|([^)'"\s]+))\s*\)/g;
|
|
5
|
+
const CSS_IMPORT = /@import\s+(?:url\(\s*)?(?:"([^"]*)"|'([^']*)'|([^)'"\s;]+))/g;
|
|
6
|
+
/**
|
|
7
|
+
* JS가 외부 리소스를 불러오는 흔한 모양 (외부 주소만): `.src = 'https://…'` · `setAttribute('src', 'https://…')` ·
|
|
8
|
+
* `new Audio('https://…')` · 문자열 안 CSS `url(https://…)`. 이동 링크(`.href`)와 fetch(api.external-send)는 뺀다
|
|
9
|
+
*/
|
|
10
|
+
const JS_RESOURCE = /(?:\.(?:src|poster)\s*=\s*|\bsetAttribute\(\s*['"](?:src|poster)['"]\s*,\s*|\bnew\s+Audio\(\s*)['"`]((?:https?:)?\/\/[^'"`\s]+)|\burl\(\s*['"]?((?:https?:)?\/\/[^'"`\s)]+)/g;
|
|
11
|
+
/** 다른 문서를 안에 띄우는 태그: 외부 주소는 html.iframe이 따로 알린다 (안 파일은 ref.missing만 봄) */
|
|
12
|
+
const FRAME_TAGS = new Set(['iframe', 'frame', 'object', 'embed']);
|
|
13
|
+
/** `<link rel>` 중 연결만 미리 여는 힌트 (리소스를 받지 않음) */
|
|
14
|
+
const CONNECTION_HINTS = new Set(['preconnect', 'dns-prefetch']);
|
|
5
15
|
const JS_IMPORT = /\b(?:import|export)\b[^'"`;]*?\bfrom\s*(?:"([^"]*)"|'([^']*)')|\bimport\s+(?:"([^"]*)"|'([^']*)')|\bimport\s*\(\s*(?:"([^"]*)"|'([^']*)')\s*\)/g;
|
|
6
16
|
function lineAt(text, index) {
|
|
7
17
|
let n = 1;
|
|
8
18
|
for (let i = 0; i < index; i++) if (text.charCodeAt(i) === 10) n++;
|
|
9
19
|
return n;
|
|
10
20
|
}
|
|
11
|
-
function collect(text, re, role, out, lineBase = 0) {
|
|
21
|
+
function collect(text, re, role, out, lineBase = 0, as) {
|
|
12
22
|
for (const m of text.matchAll(re)) {
|
|
13
23
|
const raw = m.slice(1).find(g => g !== undefined);
|
|
14
24
|
if (raw !== undefined) out.push({
|
|
15
25
|
value: raw.trim(),
|
|
16
26
|
line: lineAt(text, m.index) + lineBase,
|
|
17
|
-
role
|
|
27
|
+
role,
|
|
28
|
+
...(as ? {
|
|
29
|
+
as
|
|
30
|
+
} : {})
|
|
18
31
|
});
|
|
19
32
|
}
|
|
20
33
|
}
|
|
34
|
+
/** CSS의 url() · @import */
|
|
35
|
+
function cssRefs(text, out, lineBase = 0) {
|
|
36
|
+
collect(text, CSS_URL, 'resource', out, lineBase);
|
|
37
|
+
collect(text, CSS_IMPORT, 'resource', out, lineBase, 'style');
|
|
38
|
+
}
|
|
21
39
|
/** <script>·<style> 본문을 같은 줄 수의 빈 칸으로 바꾼다. 스크립트 안의 `a<b` 같은 글자를 태그로 읽지 않도록. */
|
|
22
40
|
function blankRawBlocks(html) {
|
|
23
41
|
return html.replace(RAW_BLOCK, (all, _tag, body) => all.replace(body, body.replace(/[^\n]/g, ' ')));
|
|
@@ -41,10 +59,13 @@ function parseTags(html) {
|
|
|
41
59
|
const RESOURCE_ATTRS = ['src', 'poster', 'data'];
|
|
42
60
|
function tagRefs(tags, out) {
|
|
43
61
|
for (const t of tags) {
|
|
44
|
-
const push = (value, role) => out.push({
|
|
62
|
+
const push = (value, role, as) => out.push({
|
|
45
63
|
value: value.trim(),
|
|
46
64
|
line: t.line,
|
|
47
|
-
role
|
|
65
|
+
role,
|
|
66
|
+
...(as ? {
|
|
67
|
+
as
|
|
68
|
+
} : {})
|
|
48
69
|
});
|
|
49
70
|
if (t.name === 'script') {
|
|
50
71
|
const src = t.attrs.get('src');
|
|
@@ -55,12 +76,15 @@ function tagRefs(tags, out) {
|
|
|
55
76
|
if (href !== undefined) {
|
|
56
77
|
if (t.name === 'a' || t.name === 'area') push(href, 'link');else if (t.name === 'link') {
|
|
57
78
|
const rel = t.attrs.get('rel') ?? '';
|
|
58
|
-
|
|
79
|
+
const rels = rel.toLowerCase().split(/\s+/).filter(Boolean);
|
|
80
|
+
// 연결 힌트(preconnect · dns-prefetch)는 리소스를 받지 않는다: 참조로 보지 않음 (Google Fonts 스니펫 등)
|
|
81
|
+
if (rels.length > 0 && rels.every(r => CONNECTION_HINTS.has(r))) continue;
|
|
82
|
+
if (/\bmodulepreload\b/i.test(rel)) push(href, 'script');else push(href, 'resource', /\bstylesheet\b/i.test(rel) ? 'style' : undefined);
|
|
59
83
|
}
|
|
60
84
|
}
|
|
61
85
|
for (const a of RESOURCE_ATTRS) {
|
|
62
86
|
const v = t.attrs.get(a);
|
|
63
|
-
if (v !== undefined) push(v, 'resource');
|
|
87
|
+
if (v !== undefined) push(v, FRAME_TAGS.has(t.name) ? 'link' : 'resource');
|
|
64
88
|
}
|
|
65
89
|
const srcset = t.attrs.get('srcset');
|
|
66
90
|
if (srcset !== undefined) {
|
|
@@ -69,7 +93,7 @@ function tagRefs(tags, out) {
|
|
|
69
93
|
const style = t.attrs.get('style');
|
|
70
94
|
if (style !== undefined) {
|
|
71
95
|
const inner = [];
|
|
72
|
-
|
|
96
|
+
cssRefs(style, inner);
|
|
73
97
|
out.push(...inner.map(r => ({
|
|
74
98
|
...r,
|
|
75
99
|
line: t.line
|
|
@@ -77,28 +101,36 @@ function tagRefs(tags, out) {
|
|
|
77
101
|
}
|
|
78
102
|
}
|
|
79
103
|
}
|
|
80
|
-
/**
|
|
81
|
-
|
|
104
|
+
/**
|
|
105
|
+
* HTML 태그 속성, CSS url()·@import, JS 정적·동적 import의 문자열 리터럴 참조, JS가 외부 리소스를 넣는 흔한 모양
|
|
106
|
+
* (JS_RESOURCE, 외부 주소만). 스크립트가 만든 경로(fetch 등)는 못 잡는다.
|
|
107
|
+
* `jsResources: false`: 라이브러리 파일은 외부 리소스 모양을 보지 않는다 (ref.vendor-external-url 경고가 맡음)
|
|
108
|
+
*/
|
|
109
|
+
function extractRefs(kind, text, tags, {
|
|
110
|
+
jsResources = true
|
|
111
|
+
} = {}) {
|
|
82
112
|
const out = [];
|
|
83
113
|
if (kind === 'css') {
|
|
84
|
-
|
|
114
|
+
cssRefs(text, out);
|
|
85
115
|
return out;
|
|
86
116
|
}
|
|
87
|
-
if (kind === 'js') return jsRefs(text, 0);
|
|
117
|
+
if (kind === 'js') return jsRefs(text, 0, jsResources);
|
|
88
118
|
tagRefs(tags ?? parseTags(text), out);
|
|
89
119
|
for (const m of text.matchAll(RAW_BLOCK)) {
|
|
90
120
|
const [all, tag, body] = m;
|
|
91
121
|
if (body === undefined) continue;
|
|
92
122
|
const base = lineAt(text, m.index + all.indexOf(body)) - 1;
|
|
93
|
-
if (tag?.toLowerCase() === 'style')
|
|
123
|
+
if (tag?.toLowerCase() === 'style') cssRefs(body, out, base);else out.push(...jsRefs(body, base, jsResources));
|
|
94
124
|
}
|
|
95
125
|
return out;
|
|
96
126
|
}
|
|
97
127
|
/** 상대경로와 외부 주소 import만. bare specifier('lodash')는 import map이 있을 수 있어 건너뜀 */
|
|
98
|
-
function jsRefs(text, lineBase) {
|
|
99
|
-
const
|
|
100
|
-
collect(text, JS_IMPORT, 'script',
|
|
101
|
-
|
|
128
|
+
function jsRefs(text, lineBase, resources = true) {
|
|
129
|
+
const imports = [];
|
|
130
|
+
collect(text, JS_IMPORT, 'script', imports, lineBase);
|
|
131
|
+
const out = imports.filter(r => /^(?:\.{0,2}\/|https?:)/i.test(r.value));
|
|
132
|
+
if (resources) collect(text, JS_RESOURCE, 'resource', out, lineBase);
|
|
133
|
+
return out;
|
|
102
134
|
}
|
|
103
135
|
function classifyRef(value) {
|
|
104
136
|
if (value === '' || value.startsWith('#') || value.includes('{{') || value.includes('${')) return 'skip';
|
|
@@ -108,4 +140,4 @@ function classifyRef(value) {
|
|
|
108
140
|
return 'local';
|
|
109
141
|
}
|
|
110
142
|
|
|
111
|
-
export { classifyRef, extractRefs, lineAt, parseTags };
|
|
143
|
+
export { FRAME_TAGS, classifyRef, extractRefs, lineAt, parseTags };
|
package/es/rules/types.d.ts
CHANGED
|
@@ -63,6 +63,11 @@ export interface RulesSpec {
|
|
|
63
63
|
minVersions: {
|
|
64
64
|
sdk: string;
|
|
65
65
|
};
|
|
66
|
+
/**
|
|
67
|
+
* 콘텐츠 CSP가 허용하는 외부 출처 (지시어 → 출처 목록, 서버 CSP 허용 목록과 같게 유지). 검사는 여기 있는 출처를
|
|
68
|
+
* 오류(ref.external-request) 대신 경고(ref.external-font)로, `ecdk dev`는 CSP 해당 지시어에 더한다 (csp.ts)
|
|
69
|
+
*/
|
|
70
|
+
externalAllow?: Partial<Record<'style-src' | 'font-src', string[]>>;
|
|
66
71
|
}
|
|
67
72
|
/**
|
|
68
73
|
* 비밀 값 탐지 (`sec.secret`). 사내 SAST(semgrep p/secrets + security/semgrep custom)를 옮긴 것.
|
package/es/rules/unused.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { ContentFile, Manifest } from './types.js';
|
|
2
|
+
/** 다른 파일 이름을 담을 수 있는 텍스트 파일 */
|
|
3
|
+
export declare const TEXT_FILE: RegExp;
|
|
2
4
|
/**
|
|
3
5
|
* 어디서도 이름이 나오지 않는 파일 (용량을 줄일 후보). 다른 텍스트 파일에 경로나 파일 이름이 한 번이라도
|
|
4
6
|
* 나오면 쓰는 것으로 본다: JS에서 `img/${n}.png`처럼 이름을 조합하면 못 찾으므로 일부러 넓게 본다.
|
package/es/rules/unused.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
/** 다른 파일 이름을 담을 수 있는 텍스트 파일 */
|
|
2
|
+
const TEXT_FILE = /\.(?:html?|css|m?js|json|svg)$/i;
|
|
2
3
|
/**
|
|
3
4
|
* 어디서도 이름이 나오지 않는 파일 (용량을 줄일 후보). 다른 텍스트 파일에 경로나 파일 이름이 한 번이라도
|
|
4
5
|
* 나오면 쓰는 것으로 본다: JS에서 `img/${n}.png`처럼 이름을 조합하면 못 찾으므로 일부러 넓게 본다.
|
|
@@ -8,7 +9,7 @@ function findUnreferenced(files, manifest) {
|
|
|
8
9
|
const real = files.filter(f => !f.dir);
|
|
9
10
|
const entries = new Set(Object.values(manifest?.entries ?? {}));
|
|
10
11
|
const decoder = new TextDecoder();
|
|
11
|
-
const texts = real.filter(f =>
|
|
12
|
+
const texts = real.filter(f => TEXT_FILE.test(f.path)).map(f => ({
|
|
12
13
|
path: f.path,
|
|
13
14
|
text: decoder.decode(f.data)
|
|
14
15
|
}));
|
|
@@ -18,4 +19,4 @@ function findUnreferenced(files, manifest) {
|
|
|
18
19
|
}).map(f => f.path).sort();
|
|
19
20
|
}
|
|
20
21
|
|
|
21
|
-
export { findUnreferenced };
|
|
22
|
+
export { TEXT_FILE, findUnreferenced };
|