Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
};

Expand All @@ -64,7 +67,7 @@ for (const course of courses) {
```

- 타입 선언이 DOM 타입(`Document`)을 쓰므로 TypeScript 프로젝트는 `tsconfig`의 `lib`에 `"DOM"`을 추가하세요.
- 세션이 만료되면 LMS가 로그인 페이지로 리다이렉트하므로 결과가 빈 배열로 나올 수 있습니다.
- 세션이 만료되면 LMS가 로그인 페이지로 리다이렉트하는데, `redirect: 'manual'` 이므로 3xx 응답이 `HTTP 3xx` 에러로 드러납니다.

## API

Expand Down
6 changes: 4 additions & 2 deletions src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) 기준으로 직접 절대화한다.
*/
Expand All @@ -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;
}
Expand Down
19 changes: 16 additions & 3 deletions test/dom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,8 @@ describe('getText', () => {

describe('getHref', () => {
it('a 태그의 href 추출', () => {
const parent = el('<a class="link" href="https://example.com">Link</a>');
const result = getHref(parent, '.link');
expect(result).toContain('example.com');
const parent = el('<a class="link" href="https://learn.hansung.ac.kr/course/view.php?id=1">Link</a>');
expect(getHref(parent, '.link')).toBe('https://learn.hansung.ac.kr/course/view.php?id=1');
});

it('셀렉터가 매칭 안 되면 null', () => {
Expand Down Expand Up @@ -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,<script>alert(1)</script>',
])('%s', (href) => {
const parent = el(`<a class="link" href="${href}">Link</a>`);
expect(getHref(parent, '.link')).toBeNull();
});
});
});
Loading