// packages/core/src/url-policy.ts // 외부 URL·내비게이션 정책 SSOT. 순수 함수만 둔다 — Electron 어댑터는 데스크톱 main이 맡는다. // // - 앱 밖으로 넘기는 URL(OS 기본 핸들러)은 허용 scheme만 연다. file:, UNC, ms-*, search-ms: 같은 // OS 핸들러는 원격 코드 실행 경로가 되므로 막는다. // - 앱 창은 앱 자신의 오리진 밖으로 이동하지 않는다(원격 페이지가 preload API를 얻지 못하게). // - file: 은 오리진이 'null'이라 오리진 비교로는 앱 번들과 사용자가 드롭한 임의 파일을 구분할 수 없다. // 그래서 앱 렌더러 디렉터리(fileRoot) 아래의 경로만 앱 페이지로 본다. export interface ExternalUrlPolicyOptions { /** 허용할 scheme(콜론 포함, 소문자). 기본 https:·mailto: */ allowSchemes?: readonly string[] /** 추가로 허용할 정확한 오리진(예: 개발용 http://localhost:3000). */ allowOrigins?: readonly string[] } export interface AppOriginOptions { /** * 앱 렌더러가 올라오는 디렉터리의 file URL(예: file:///C:/app/resources/app.asar/out/renderer/). * 지정하면 appOrigins 의 'file://' 항목은 이 디렉터리 아래 경로만 허용한다(호스트까지 일치해야 하므로 * UNC file://host/share/... 도 거부). 지정하지 않으면 모든 file: URL을 허용하는 예전 동작이다 — * 앱 창 가드에서는 반드시 지정한다. */ fileRoot?: string } export const DEFAULT_EXTERNAL_SCHEMES: readonly string[] = ['https:', 'mailto:'] const FILE_ORIGIN = 'file://' function parse(url: string): URL | null { if (typeof url !== 'string' || url.trim() === '' || url.length > 8192) return null // 백슬래시로 시작하는 UNC(\\server\share)는 URL 파서가 상대 경로로 보지 않도록 먼저 거른다. if (url.startsWith('\\\\') || url.startsWith('//')) return null try { return new URL(url) } catch { return null } } /** 퍼센트 인코딩을 풀고 경로 세그먼트로 나눈다. 인코딩으로 숨긴 '..'·'\\'·NUL 이 있으면 null. */ function decodedSegments(pathname: string): string[] | null { let decoded: string try { decoded = decodeURIComponent(pathname) } catch { return null } if (decoded.includes('\\') || decoded.includes('\0')) return null const segments = decoded.split('/') if (segments.some((segment) => segment === '.' || segment === '..')) return null return segments } /** '/C:/...' 처럼 Windows 드라이브 경로면 대소문자를 구분하지 않는다. */ function isWindowsDrivePath(segments: readonly string[]): boolean { return segments.length > 1 && /^[A-Za-z]:$/.test(segments[1] ?? '') } /** * file URL 이 fileRoot 디렉터리 아래(또는 그 자체)를 가리키는지. 호스트(UNC)·경로를 모두 비교한다. * fileRoot 끝의 '/' 유무는 상관없다. */ export function isFileUrlWithinRoot(url: string, fileRoot: string): boolean { const parsed = parse(url) const root = parse(fileRoot) if (!parsed || !root) return false if (parsed.protocol !== 'file:' || root.protocol !== 'file:') return false if (parsed.host.toLowerCase() !== root.host.toLowerCase()) return false const target = decodedSegments(parsed.pathname) const rootSegments = decodedSegments(root.pathname) if (!target || !rootSegments) return false // 끝의 빈 세그먼트('/renderer/' → ['', 'renderer', ''])는 디렉터리 표기일 뿐이다. while (rootSegments.length > 1 && rootSegments[rootSegments.length - 1] === '') rootSegments.pop() if (target.length < rootSegments.length) return false const caseInsensitive = isWindowsDrivePath(rootSegments) return rootSegments.every((segment, index) => { const candidate = target[index] ?? '' return caseInsensitive ? candidate.toLowerCase() === segment.toLowerCase() : candidate === segment }) } /** OS 기본 핸들러(브라우저·메일)로 넘겨도 되는 URL인지. */ export function isAllowedExternalUrl(url: string, options: ExternalUrlPolicyOptions = {}): boolean { const parsed = parse(url) if (!parsed) return false const origin = parsed.origin if (options.allowOrigins?.some((allowed) => allowed === origin)) return true const schemes = options.allowSchemes ?? DEFAULT_EXTERNAL_SCHEMES if (!schemes.includes(parsed.protocol.toLowerCase())) return false if (parsed.protocol === 'https:') { // 자격 증명이 박힌 URL(https://user@evil)이나 호스트 없는 URL은 열지 않는다. if (!parsed.hostname || parsed.username || parsed.password) return false } return true } /** * URL이 앱 자신의 페이지인지. appOrigins는 'file://' 또는 'http://localhost:5173' 같은 오리진. * file: 은 오리진이 'null'이라 scheme으로 비교하고, options.fileRoot 가 있으면 그 디렉터리 아래로 제한한다. */ export function isAppOrigin( url: string, appOrigins: readonly string[], options: AppOriginOptions = {}, ): boolean { const parsed = parse(url) if (!parsed) return false for (const allowed of appOrigins) { if (allowed === FILE_ORIGIN) { if (parsed.protocol !== 'file:') continue if (options.fileRoot === undefined) return true if (isFileUrlWithinRoot(url, options.fileRoot)) return true continue } const allowedParsed = parse(allowed) if (allowedParsed && allowedParsed.origin === parsed.origin) return true } return false } /** * 앱 창이 이 URL로 이동(will-navigate/will-redirect)해도 되는지. * isAppOrigin 에 더해 file: 이면 HTML 문서만 허용한다 — 앱 번들 안이라도 .js·.wasm·리소스 파일로 * 이동하면 UI가 사라지고 frameless 창에서는 복구할 수 없다. */ export function isAppNavigationTarget( url: string, appOrigins: readonly string[], options: AppOriginOptions = {}, ): boolean { if (!isAppOrigin(url, appOrigins, options)) return false const parsed = parse(url) if (!parsed) return false if (parsed.protocol !== 'file:') return true return parsed.pathname.toLowerCase().endsWith('.html') }