# SafeScript: 사용자 코드용 JavaScript
# SafeScript: JavaScript for user code

- Site: https://select1.dev/2026-11-10 (English), https://select1.dev/ko/2026-11-10 (Korean)
- Entry: 031
- Published: 2026-11-10 (KST). Launch date: 2026-11-09
- Pick: SafeScript <https://github.com/SafeScript/safescript> (source: Show HN)
- Verified: ran
- What: SafeScript 는 사용자가 작성한 코드를 서버나 브라우저에서 안전하게 실행하게 하는 프로덕트다. JavaScript 의 일부 문법만 허용하는 언어다.
- What (en): SafeScript is a product that runs users’ code on a server or in a browser and limits what that code can reach. It is a language that accepts only part of JavaScript.
- Why: 오늘의 픽으로 선정한 이유는 사용자 코드의 위험한 문법을 실행 전에 거부할 수 있기 때문이다.
- Why (en): It is today’s pick because it rejects dangerous syntax in user code before the code runs.
- Verdict: 작동한다. 오늘 시도한 객체 접근을 모두 막았다.
- Verdict (en): It works. It blocked every attempt I made to reach objects the host did not pass in.
- Tags: javascript, sandbox, compiler, security, node, untrusted-code

## Checked against the README

- [fail] run() 은 언제나 Promise 를 반환한다(run() always returns a Promise) — 컴파일 단계에서 거부되는 코드(constructor 접근)를 넘기자 run() 이 Promise 를 반환하지 않고 SyntaxError 를 바로 던졌다. Promise 의 .then 이나 .catch 로는 이 오류를 잡을 수 없다. 그래서 호출부에 try 없이 .then 만 붙인 시험 하네스는 처리되지 않은 예외로 종료됐다
- [fail] 기다리지 않은 Promise 가 스크립트의 값으로 쓰이지 않는다(No unresolved Promises can leak through) — [1, 2, 3].map(function (x) { return x * 2; }) 의 결과가 Promise 3개였고, reduce 의 결과는 "[object Promise]3" 이었다
- [pass] 무한 루프와 무한 재귀를 막는다(preventing infinite loops and infinite recursion) — timeout 2000 으로 while (true) {} 를 실행하자 2,007 ms 에 execution timed out 오류로 끝났다. 무한 재귀는 23 ms 에 RangeError(스택 초과)로 끝났다. 정렬 비교 함수 안의 무한 루프는 멈췄지만, 처리되지 않은 timeout 오류로 호스트 프로세스가 종료됐다(실행해 보니 5)

## Measured

- run() 한 번의 시간(return x + y, 컴파일 포함): 0.10 ms (new Function 은 0.0013 ms) (Node 22.22.0 에서 run() 과 new Function 을 각각 1,000번 반복해 평균을 냈다. 이 측정을 세 번 반복했을 때 run() 의 평균은 0.098~0.102 ms 사이였다)

## Progress (days after launch; full history https://select1.dev/2026-11-10/progress)

- day 3 (checked 2026-11-12) [active] commits since launch 3, stars 25, releases 1, contributors 1, last commit 2026-11-10
  - A debug runtime, an execution journal, time travel and development tools were added (v2.0).
  - The `new` keyword works only with constructors on an allowlist, and return values are sanitized (v1.4.0).
  - DOM wiring through `@uses`, six new built-in types and `load()` bundles were added, and some types were renamed (v1.3.0).
- day 7 (checked 2026-11-16) [quiet] commits since launch 3, stars 27, releases 1, contributors 1, last commit 2026-11-10
- day 15 (checked 2026-11-24) [active] commits since launch 6, stars 28, releases 3, contributors 1, last commit 2026-11-18
  - Added a new runtime (v2.0.0). It records a script’s changes separately and applies them only when you commit.
  - Added a debug mode, SafeScript.debug(), that lets you step through the run. An outside tool such as an IDE can control the run (v2.0.0).
  - The `new` operator is now allowed for whitelisted constructors such as Map, Set and Date (v2.0.0).
  - In debug mode, the session used to stop with a ReferenceError when the debugger listed a variable that was not initialized yet. That variable is now left out of the list (v2.1.0).

## 한국어

## 무엇이 문제인가

서비스는 가격 규칙, 검증 규칙, 스프레드시트 수식, 플러그인처럼 사용자가 작성한 코드를 받기도 한다. 이런 코드를 eval 이나 new Function 으로 실행하면, 그 코드가 서버의 파일과 환경 변수에 접근할 수 있다.

Node.js 에는 코드를 별도 컨텍스트에서 실행하는 vm 모듈이 있다. 하지만 Node.js 문서에는 vm 모듈이 보안 메커니즘이 아니므로 신뢰할 수 없는 코드를 실행하는 데 쓰지 말라고 적혀 있다. 그래서 이런 코드는 보통 별도 프로세스나 컨테이너 같은 격리 환경에서 실행한다.

## 어떻게 해결했나

SafeScript 는 2026년 11월 9일 Hacker News 에 Show HN 글로 올라왔다. 제작자 Gregory Magarshak 은 README 에서, JSON 으로 데이터를 안전하게 주고받듯 SafeScript 로 실행할 코드를 안전하게 주고받게 하려 한다고 밝혔다.

SafeScript 는 eval, new, 프로토타입 접근, globalThis 나 process 같은 전역 객체를 컴파일 단계에서 허용하지 않는다. Math, JSON 같은 안전한 내장 객체는 기본으로 제공한다. 컴파일러는 소스를 AST로 바꾼 뒤 허용된 노드만으로 코드를 다시 만든다. 출력은 일반 JavaScript 코드와 PHP 코드다. run() 을 호출하는 프로그램이 객체를 넘기면, 스크립트는 그 객체만 사용할 수 있다. 이 글에서는 이 프로그램을 호스트라고 부른다. 컴파일러는 모든 함수의 첫머리와 반복문마다 검사 코드를 넣는다. 검사 코드는 실행 시간과 연산 횟수를 확인한다.

## 무엇이 다른가

첫째, 막는 시점이 다르다. Node.js 의 vm 은 JavaScript 를 그대로 실행하고, 별도 컨텍스트로 전역 객체만 분리한다. SafeScript 는 실행하기 전에 문법을 검사한다. constructor 나 arguments 로는 호스트가 넘기지 않은 객체에 접근할 수 있어, 이런 문법은 컴파일 오류로 처리한다. 트레이드오프는 쓸 수 있는 문법이 줄어든다는 점이다. new, class, 템플릿 리터럴, async 와 await 는 쓸 수 없다.

둘째, 실행을 멈추는 방식이 다르다. Node.js 문서에 따르면 vm 의 timeout 은 시간이 지나면 실행 자체를 종료한다. SafeScript 에서는 함수 첫머리와 반복문에 들어간 검사 코드가 실행 중에 시간을 확인하고, 제한 시간을 넘기면 오류를 던진다. 컴파일러는 또 모든 함수를 async 로 바꾸고 함수 호출마다 await 를 붙인다. 그래서 호스트가 넘긴 함수가 Promise 를 반환해도, 스크립트를 동기 코드처럼 작성할 수 있다. 트레이드오프는 sort 나 map 같은 내장 메서드에 넘긴 함수가 제대로 작동하지 않는다는 점이다. 이 메서드들은 함수가 반환한 Promise 를 기다리지 않아 결과가 잘못된다. 그 함수 안에서 검사 코드가 던진 오류는 스크립트 밖의 호스트로 전달된다.

## 어떻게 만들었나

- 저장소의 커밋 4개는 2026년 10월 23일부터 25일 사이에 작성됐다. Co-authored-by 트레일러가 있는 커밋은 없다.
- 컴파일러와 런타임은 src 폴더의 JavaScript 3,226줄이다.
- CHANGELOG 1.1.0 에는 test-battle.js 와 test-compiler.js 를 test.js 로 합쳐 지웠다고 적혀 있다. 하지만 test-battle.js 와 test-compiler.js 는 저장소에 남아 있다. npm test 도 이 파일들을 실행한다.

## 실행해 보니

SafeScript 1.2.0 저장소를 클론해 Node.js 22.22.0 에서 테스트를 실행했다. 이어서 스크립트 20개를 작성해 run() 으로 실행했다.

1. 설치와 테스트. `npm ci --ignore-scripts` 는 2.1초 만에 끝났다. test.js 의 테스트 155개는 모두 통과했다. npm test 는 test-compiler.js 에서 4개가 실패해 멈췄다. 실패한 4개는 Object 같은 전역 객체가 undefined 인지 검사한다. README 에 따르면 이 객체들은 기본으로 제공된다.
2. 탈출 시도. constructor 로 Function 에 접근하는 코드, 유니코드 이스케이프로 쓴 `\u0063onstructor`, arguments 는 컴파일 단계에서 거부됐다. __proto__ 키가 든 JSON 문자열을 JSON.parse 로 읽자, 결과 객체에서 그 키가 지워졌다. 다만 run() 은 이 컴파일 오류를 Promise 로 반환하지 않고 바로 던졌다.
3. 무한 루프와 무한 재귀. timeout 을 2초로 지정하자 while (true) {} 는 2,007 ms 에 멈췄다. 무한 재귀는 23 ms 만에 스택 초과 오류로 끝났다. 배열에 원소 20,000,000개를 넣는 반복문도 2초에 멈췄다. 그사이 메모리 사용량은 323 MB 까지 올랐다. 메모리 상한 옵션은 없다.
4. 내장 메서드에 넘긴 함수. [3, 1, 2] 를 비교 함수로 정렬하자 순서가 그대로였다. `[1, 2, 3].map(function (x) { return x * 2; })` 는 [2, 4, 6] 대신 Promise 3개를 반환했다. 1부터 3까지 더하는 reduce 는 6 대신 "[object Promise]3" 을 반환했다.
5. 비교 함수 안의 무한 루프. 비교 함수에 while (true) {} 를 넣자, 정렬은 비교 함수가 반환한 Promise 를 기다리지 않고 끝났다. run() 은 다음 줄의 'done' 을 반환했다. 그 직후 처리되지 않은 timeout 오류로 Node.js 프로세스가 종료 코드 1로 끝났다. 비교 함수 안에 50번 반복하는 루프를 넣고 원소 2,000,000개를 정렬하자, timeout 을 2초로 지정했는데도 정렬이 10.4초 뒤에 끝났다. 메모리 사용량은 1,106 MB 까지 올랐다. 이어서 같은 timeout 오류로 프로세스가 종료됐다.
6. 속도. `return x + y` 를 1,000번 실행한 평균은 run() 이 컴파일을 포함해 0.10 ms, `new Function` 이 0.0013 ms 였다.

```
$ node one.js app t19-crash.safe '{"timeout":1000}'
RESULT "done" ms 1006 maxRssMB 51
/tmp/run/app/src/runtime.js:649
        throw new Error('SafeScript: execution timed out after ' + timeout + 'ms');
              ^

Error: SafeScript: execution timed out after 1000ms
```

## 판정

작동한다. 오늘 시도한 객체 접근을 모두 막았다. 다만 1.2.0 에서 sort 나 map 에 넘긴 함수는 Promise 를 반환해 결과가 잘못된다. 오늘 실행에서는 그 함수 안에서 시간 제한에 걸리자 호스트의 Node.js 프로세스가 종료됐다. 사용자가 작성한 짧은 계산식이나 검증 규칙을 실행하는 경우에 써 볼 만하다.

## 얻어갈 것

- 함수를 async 로 바꾸는 컴파일러를 만든다면, 내장 메서드가 호출하는 콜백도 시험해 보자. 오늘 sort 와 map 은 async 함수가 반환한 Promise 를 값으로 사용했다.
- 신뢰할 수 없는 코드를 Node.js 에서 실행한다면, 호스트 프로세스에 `unhandledRejection` 핸들러를 등록하자. 기본 설정의 Node.js 는 거부된 Promise 를 처리하는 코드가 없으면 프로세스를 종료한다. 이 핸들러를 등록해 두면 프로세스를 종료하지 않고 핸들러를 호출한다.

### 용어

- AST: 소스 코드나 마크다운 같은 텍스트를 문법 구조에 따라 트리로 나타낸 자료 구조다. 컴파일러와 분석 도구가 코드를 읽을 때 만든다.

## English

## The problem

Services sometimes accept code that users wrote, such as pricing rules, validation rules, spreadsheet formulas and plugins. If you run that code with eval or new Function, the code can reach the server’s files and environment variables.

Node.js has the vm module, which runs code in a separate context. But the Node.js docs say the vm module is not a security mechanism and tell you not to use it to run untrusted code. So code like this usually runs in an isolated environment, such as a separate process or a container.

## How it solves it

SafeScript was posted on Hacker News as a Show HN on November 9, 2026. In the README, the maker, Gregory Magarshak, compares it to JSON. JSON became a safe format for exchanging data, and SafeScript aims to be one for exchanging code to run.

SafeScript rejects eval, new, prototype access and global objects such as globalThis and process at compile time. Safe built-in objects such as Math and JSON are provided by default. The compiler turns the source into an AST and rebuilds the code from allowed nodes only. The output is plain JavaScript and PHP code. A script can use only the objects that the program calling run() passes in. I call that program the host. The compiler also inserts check code at the start of every function and loop. This code checks the running time and the number of operations.

## What is different

The first difference is when it blocks code. Node.js’s vm runs JavaScript as it is and only gives it a separate set of global objects. SafeScript checks the syntax before anything runs. Names such as constructor and arguments can reach objects the host did not pass in. Code that uses them fails to compile. The tradeoff is less syntax. You cannot use new, class, template literals, or async and await.

The second difference is how it stops a script. According to the Node.js docs, vm’s timeout terminates execution once the time runs out. In SafeScript, the check code at the start of each function and loop reads the clock while the script runs. It throws an error when time is up. The compiler also makes every function async and adds await to every call. So a script reads like synchronous code even when a function from the host returns a Promise. The tradeoff is that functions passed to built-in methods such as sort and map do not work correctly. Those methods do not wait for the Promise that the function returns, so the results come out wrong. Errors that the check code throws inside those functions bypass the script and reach the host.

## How it was built

- The repository has 4 commits, made between October 23 and 25, 2026. No commit has a Co-authored-by trailer.
- The compiler and runtime are 3,226 lines of JavaScript in the src folder.
- The CHANGELOG for 1.1.0 says test-battle.js and test-compiler.js were merged into test.js and removed. Both files are still in the repository, and npm test runs them.

## Running it

I cloned the SafeScript 1.2.0 repository and ran its tests on Node.js 22.22.0. Then I wrote 20 scripts and ran them through run().

1. Install and tests. `npm ci --ignore-scripts` finished in 2.1 seconds. All 155 tests in test.js passed. npm test stopped at test-compiler.js, where 4 tests failed. Those 4 tests expect global objects such as Object to be undefined. According to the README, these objects are provided by default.
2. Escape attempts. The compiler rejected code that tried to reach Function through constructor, through arguments, or through `\u0063onstructor` written with a Unicode escape. When JSON.parse read a JSON string with a __proto__ key, the key was gone from the result. But run() threw these compile errors right away instead of returning them as a rejected Promise.
3. Infinite loops and infinite recursion. With a 2-second timeout, while (true) {} stopped at 2,007 ms. Infinite recursion ended after 23 ms with a stack overflow error. A loop that pushed 20,000,000 items into an array also stopped at 2 seconds. By then, memory use had reached 323 MB. There is no option for a memory limit.
4. Functions passed to built-in methods. Sorting [3, 1, 2] with a compare function left the order unchanged. `[1, 2, 3].map(function (x) { return x * 2; })` returned 3 Promises instead of [2, 4, 6]. A reduce call that adds up [1, 2, 3] returned "[object Promise]3" instead of 6.
5. An infinite loop inside a compare function. I put while (true) {} inside the sort compare function. The sort did not wait for the Promise from the compare function. It finished, and run() returned 'done' from the next line. Right after that, an uncaught timeout error ended the Node.js process with exit code 1. Then I put a loop that runs 50 times inside the compare function and sorted 2,000,000 items with a 2-second timeout. The sort did not stop at 2 seconds. It finished after 10.4 seconds. Memory reached 1,106 MB, and then the same timeout error ended the process.
6. Speed. Over 1,000 runs of `return x + y`, run() averaged 0.10 ms, including compilation. The same 1,000 runs through `new Function` averaged 0.0013 ms.

```
$ node one.js app t19-crash.safe '{"timeout":1000}'
RESULT "done" ms 1006 maxRssMB 51
/tmp/run/app/src/runtime.js:649
        throw new Error('SafeScript: execution timed out after ' + timeout + 'ms');
              ^

Error: SafeScript: execution timed out after 1000ms
```

## Verdict

It works. It blocked every attempt I made to reach objects the host did not pass in. But in 1.2.0, functions passed to sort or map return Promises, so the results are wrong. In my test, the host’s Node.js process exited when one of them hit the time limit. It is worth trying if you run short formulas or validation rules that users wrote.

## What to take away

- If you build a compiler that turns functions into async ones, also test the callbacks that built-in methods call. Today sort and map used the Promise from an async function as a value.
- If you run untrusted code in Node.js, register an `unhandledRejection` handler in the host process. By default, Node.js ends the process when no code handles a rejected Promise. With the handler registered, it calls the handler instead.

### Terms

- AST: Abstract syntax tree. A tree that shows the structure of source code or text such as Markdown. Compilers and analysis tools build it to read code.

## Launches the same day

- Flide <https://github.com/OmniJev/Flide> (Show HN, 109): 결정 모델용 추론 서버. 같은 입력에 여러 질문을 붙여 한 번에 계산한다.
- SafeScript <https://github.com/SafeScript/safescript> (Show HN, 12): JavaScript 의 안전한 부분집합. 사용자가 작성한 코드에서 위험한 문법을 실행 전에 거부한다.
- Pgxio <https://github.com/mishabunte/pgxio> (Show HN, 9): Nginx 모듈. HTTP 요청으로 PostgreSQL 함수를 직접 호출한다.
- Jot <https://sayjot.xyz/> (Show HN, 9): macOS 앱. 선택한 텍스트를 Shift 두 번으로 Markdown 으로 바꾼다.
- Recto <https://recto.design/> (Show HN, 8): 디자인 편집 도구. 코딩 에이전트가 만든 화면을 직접 고친다.
- GestaltX <https://github.com/huamidev/GestaltX> (GitHub, 1319): iOS 27 기기 설정 편집기. 지역 코드와 기기 사전 설정을 바꾸고 백업한다.
- rewind-for-x <https://github.com/yetone/rewind-for-x> (GitHub, 218): Chrome 확장. X 홈 타임라인에서 지나간 게시물을 다시 확인한다.
- image-to-sculpt <https://github.com/gokayfem/image-to-sculpt> (GitHub, 187): 코딩 에이전트용 스킬. 이미지 한 장으로 Blender 3D 조각을 만든다.
- Product Hunt MCP <https://www.producthunt.com/products/producthunt> (Product Hunt, 288): MCP 서버. AI 어시스턴트 안에서 Product Hunt 의 정보를 찾는다.
- Dageno AI 2.0 <https://www.producthunt.com/products/agent-powered-geo-by-dageno> (Product Hunt, 281): 마케팅 도구. AI 가 경쟁사를 추천하는 이유를 분석한다.
- Databox CLI <https://www.producthunt.com/products/databox> (Product Hunt, 258): 분석 플랫폼의 CLI. 에이전트가 터미널에서 지표를 조회한다.

## Getting started

- Steps: git clone https://github.com/SafeScript/safescript ; npm ci --ignore-scripts ; node test.js
- Needs: Node.js. 계정과 키는 필요 없다.
- Cost: MIT, 무료.
- Note: RegExp 같은 내장 타입의 메서드는 SafeScript.lib() 로 등록해야 사용할 수 있다.
