diff --git a/README.md b/README.md index b123cff..3dc3776 100644 --- a/README.md +++ b/README.md @@ -50,8 +50,11 @@ import { BASE_LINK, parseCoursesFromDOM, scrapeCourseData, type FetchHtml } from const moodleSession = process.env.MOODLE_SESSION!; const fetchHtml: FetchHtml = async (url) => { - const res = await fetch(url, { headers: { Cookie: `MoodleSession=${moodleSession}` } }); - if (!res.ok) throw new Error(`HTTP ${res.status}: ${url}`); + // 세션 쿠키가 LMS 밖(파싱된 외부 링크·리다이렉트)으로 새지 않도록 호스트를 고정한다 + const target = new URL(url, BASE_LINK); + if (target.origin !== 'https://learn.hansung.ac.kr') throw new Error('LMS 외부 URL 요청 거부'); + const res = await fetch(target, { headers: { Cookie: `MoodleSession=${moodleSession}` }, redirect: 'manual' }); + if (!res.ok) throw new Error(`HTTP ${res.status}: ${target}`); return new DOMParser().parseFromString(await res.text(), 'text/html') as unknown as Document; }; @@ -64,7 +67,7 @@ for (const course of courses) { ``` - 타입 선언이 DOM 타입(`Document`)을 쓰므로 TypeScript 프로젝트는 `tsconfig`의 `lib`에 `"DOM"`을 추가하세요. -- 세션이 만료되면 LMS가 로그인 페이지로 리다이렉트하므로 결과가 빈 배열로 나올 수 있습니다. +- 세션이 만료되면 LMS가 로그인 페이지로 리다이렉트하는데, `redirect: 'manual'` 이므로 3xx 응답이 `HTTP 3xx` 에러로 드러납니다. ## API diff --git a/src/dom.ts b/src/dom.ts index 696da25..df259da 100644 --- a/src/dom.ts +++ b/src/dom.ts @@ -6,7 +6,7 @@ export function getText(parent: ParentNode, selector: string): string | null { } /** - * 셀렉터로 a 태그의 href를 절대 URL로 추출. 없으면 null + * 셀렉터로 a 태그의 href를 절대 URL로 추출. 없거나 LMS 출처가 아니면 null * 브라우저는 a.href가 문서 URL 기준으로 절대화되지만 linkedom은 속성값을 그대로 주므로 * 같은 결과를 내도록 요청한 페이지 URL(base) 기준으로 직접 절대화한다. */ @@ -15,7 +15,9 @@ export function getHref(parent: ParentNode, selector: string, base: string = BAS if (!href) return null; // URL.parse는 Chrome 126·Node 22.1부터라 생성자 + try/catch로 호환 범위를 넓힌다 try { - return new URL(href, base).href; + const url = new URL(href, base); + // 스크래핑한 링크로 요청을 보내므로 다른 호스트·javascript:·data: 는 버린다 + return url.origin === new URL(BASE_LINK).origin ? url.href : null; } catch { return null; } diff --git a/test/dom.test.ts b/test/dom.test.ts index d8e2394..d6435d7 100644 --- a/test/dom.test.ts +++ b/test/dom.test.ts @@ -46,9 +46,8 @@ describe('getText', () => { describe('getHref', () => { it('a 태그의 href 추출', () => { - const parent = el('Link'); - const result = getHref(parent, '.link'); - expect(result).toContain('example.com'); + const parent = el('Link'); + expect(getHref(parent, '.link')).toBe('https://learn.hansung.ac.kr/course/view.php?id=1'); }); it('셀렉터가 매칭 안 되면 null', () => { @@ -94,4 +93,18 @@ describe('getHref', () => { expect(getHref(parent, '.link', pageUrl)).toBeNull(); }); }); + + describe('LMS 출처가 아니면 null', () => { + it.each([ + 'https://evil.com/mod/quiz/view.php?id=1', + 'https://learn.hansung.ac.kr.evil.com/', + 'http://learn.hansung.ac.kr/mod/quiz/view.php?id=1', + '//evil.com/path', + 'javascript:alert(1)', + 'data:text/html,', + ])('%s', (href) => { + const parent = el(`Link`); + expect(getHref(parent, '.link')).toBeNull(); + }); + }); });