Electron

보안과 안정적 통신을 위해 preload.js 스크립트 설정하기

vamosdev12 2025. 4. 24. 17:41

 취지 

보안과 안정적 통신

 

 preload.js의 역할 

1. 보안을 유지하면서 Node.js 기능 사용 가능

 

  • Electron에서는 렌더러 프로세스(브라우저 환경)에서 require, fs, path 등 Node API를 직접 사용하는 건 매우 위험해요 (XSS, remote code injection 등의 보안 위협).
  • 그래서 일반적으로 nodeIntegration: false, contextIsolation: true로 설정함
  • ➡ 이때 preload.js는 Node.js와 브라우저의 중간 지점 역할
// preload.js
const { contextBridge, ipcRenderer } = require('electron');

// 렌더러에서 electron 객체를 사용할 수 있게 함
contextBridge.exposeInMainWorld('electron', {
  sendMessage: (msg) => ipcRenderer.send('msg', msg),
  onReceive: (callback) => ipcRenderer.on('reply', (_, data) => callback(data))
});

// renderer.js
window.electron.sendMessage('hello!');
// => 렌더러는 노출(preload에 등록)된 안전한 API만 사용 가능

 

✅ typeScript를 사용할 경우 electron 객체를 인식시키기 위해 type 선언도 해주어야 함.

//global.d.ts
interface Window {
	electron: {
		ipcRenderer: {
			send(channel: string, data?: any): void;
			on(channel: string, listener: (event: any, ...args: any[]) => void): void;
			once(channel: string, listener: (event: any, ...args: any[]) => void): void;
			removeAllListeners(channel: string): void;
		};
	};
}

 

2. Renderer <-> Main 간 통신 구조 정리가능

  • preload.js를 통해 모든 IPC 통신을 한 곳에 정의할 수 있어, 유지보수와 디버깅이 쉬워짐

 3. contextIsolation: true 설정에서도 통신 가능

  • contextIsolation: true는 브라우저 JS 환경과 Electron JS 환경을 완전히 격리하는 설정
  • 이 설정이 true일 경우, window.require, window.fs 등은 작동하지 않음
  • 대신 preload.js에서 contextBridge를 통해 안전한 bridge를 만들어야 함 

4. 전역 오염 방지 + 최소한의 API 노출

  • 렌더러에서 require('electron') 같은 위험한 코드 제거
  • 오직 필요한 기능만 노출 → 예: window.electron.sendMessage() 같은 안전한 인터페이스

 

🚫 preload 없이 직접 사용하는 건 위험해?

✔ 가능은 하지만 nodeIntegration: true, contextIsolation: false 설정이 필요해요.
이건 보안상 매우 위험하며 실제 배포 앱에서는 거의 금지 수준입니다.

 

공격예시 :

렌더러는 외부 입력을 받을 수 있는 곳!

렌더러에서 require('electron')을 허용하면 결국 이걸 통해 다음도 다 가능해집니다.

거기에 스크립트 삽입이 되면 악의적인 자바스크립트가 실행될 수 있고, 그 JS에서 require()를 사용할 수 있다면?

const fs = require('fs');
fs.writeFileSync('/etc/passwd', '바꿔치기'); // 💣

 

 

'Electron' 카테고리의 다른 글

Electron 이벤트 리스너 - .on() / .once()  (0) 2025.04.22
일렉트론 구조 - main.js / index.js / on() / send()  (0) 2025.03.18
require()  (0) 2025.03.06
audio 태그 대신 Audio 객체로 조작하기  (0) 2025.03.06
ReturnType<T>  (0) 2025.03.06