SafeScript 发布:可安全执行不可信代码的 JavaScript 子集

原标题:Show HN: SafeScript, a safe version of JavaScript for executing untrusted code
62AI 研判分

SafeScript 是 JavaScript 的严格安全子集,移除 eval、new、全局对象与原型访问,可编译为原生 JS 与 PHP,编译器仅约 48 KB(gzip 后约 12 KB)。它面向网页处理器、事件回调、插件脚本、公式表达式以及 AI 智能体可调用工具等场景,让用户提交的逻辑在沙箱内安全运行。

报道正文

本文目录7 个章节

SafeScript

JSON for code. A safe computational subset of JavaScript.

JSON gave the world a safe way to exchange data. SafeScript does the same for computation. It's a strict subset of JavaScript — no eval, no new, no globals, no prototype access — that compiles to plain JS and PHP. Open a .safe file and you see code that's safe to run. The compiler is ~48 KB minified (~12 KB gzipped). Ship it anywhere, verify locally, no trust needed.

Use Cases

SafeScript starts small, the same way JSON did. Anywhere you need a safe handler for data or events:

  • Webserver handlers — route logic, request transforms, validation rules submitted by users or tenants
  • onclick and event handlers — user-authored browser event handlers that can't escape their sandbox
  • Plugin scripts — extend an app with user-submitted logic without risking the host
  • Formulas and expressions — spreadsheet-style computed fields, pricing rules, scoring functions
  • Bot and agent tools — callable tools for AI agents that are safe by construction (see Safebots)
  • Config with logic — when JSON isn't enough but arbitrary JS is too much

Quick Start

JAVASCRIPT
// Node.js
const SafeScript = require('safescript');

const result = await SafeScript.run('return x + y;', { x: 10, y: 20 });
// → 30

// Safe globals are available by default — no injection needed
await SafeScript.run('return Math.floor(3.7);');     // → 3
await SafeScript.run('return JSON.parse("{}");');     // → {} (null-prototype, __proto__ stripped)
await SafeScript.run('return Object.keys({a:1});');   // → ['a']

// Math.random is deterministic by default (mulberry32 PRNG, seed 0)
await SafeScript.run('return Math.random();');  // → same value every time
HTML

<script src="safescript.min.js"></script>
<script>
  SafeScript.run('return n * 2;', { n: 21 }).then(function(result) {
    // → 42
  });
</script>

The .safe File Format

SafeScript files use the .safe extension and application/safescript MIME type. A .safe file is self-contained — it declares what capabilities it needs at the top, and the host provides them.

JAVASCRIPT
/**
 * @safescript 0.2
 * @needs request: Request
 * @needs db: Database
 * @uses logger: Logger
 * @env browser, node
 */
var body = request.json();
if (logger) logger.log('received', body);
return db.store(body);

The header is an optional /** */ block comment with five directives:

  • @safescript <version> — language version
  • @needs <name>: <Type> — required capability; the host must provide it or refuse to run the file
  • @uses <name>: <Type> — optional capability; the host provides it if available, the script checks with if (name)
  • @type <TypeName> { method1, method2 } — declares a return type and the methods the script intends to call on it
  • @env <env1>, <env2> — constrains which environments can run this file (optional, comma-separated)

Type Declarations

@type declarations tell the host which methods on return types the script intends to call. They're purely declarative — they don't change runtime enforcement, but they enable pre-flight validation at load() time.

JAVASCRIPT
/**
 * @safescript 0.2
 * @needs fetch: function
 * @needs log: function
 * @type Response { json, text, status }
 * @type Stream { get, set, fields }
 */
var resp = fetch('/api/data');
var data = resp.json();
log(data);

When load() processes this header, it checks:

  1. Every @type name is registered with the host (via SafeScript.lib())
  2. Every declared method is in the host's allowMethods whitelist

This catches mismatches early — before the script runs — rather than failing at the first method call. If a script declares @type Response { json, text, status } but the host only allows json and text, load() throws immediately.

The .safe File as a Trust Unit

A .safe file is a unit of trust — one set of declarations, one sandbox boundary. Everything about its security posture is visible in a single file:

  • What it needs (@needs) — the injected capabilities
  • What it optionally uses (@uses) — degradable capabilities
  • What return types it touches (@type) — methods on host-provided objects
  • What environment it expects (@env) — runtime constraints

If you want two functions with different access patterns, you put them in two .safe files. Each file gets its own scope, its own type declarations, and its own sandbox. The file IS the security boundary.

This is by design. SafeScript protects the host's environment — it ensures that user-submitted code can only call what the host explicitly allows. User protection (ensuring the host acts in the user's interest) comes from a different layer entirely — attestations about the host, not constraints in SafeScript. See Safebots layers for how these layers compose.

Self-Contained by Design

A .safe file declares what it needs. It doesn't import, require, or fetch anything. The host reads the declarations and builds the scope — where the host gets the implementations is its business. A Node host might resolve them from node_modules. A browser host might use an import map or a CDN. A sandboxed environment might draw from a curated whitelist. The .safe file doesn't know or care.

This is a deliberate departure from require() and import. Package managers are an implementation detail of a particular host, not a top-level concept in the language. A .safe file that depends on npm to function is not truly portable. A .safe file that declares @needs fetch: http.Fetch works everywhere a host can provide an HTTP client.

This also avoids inheriting the supply chain attack surface of package managers. SafeScript's security story starts at the file boundary — you read the header, you see what the code can touch, you decide whether to run it.

Host Workflow

JAVASCRIPT
const SafeScript = require('safescript');

// 1. Parse the header
const caps = SafeScript.capabilities(source);
// → { version: '0.2', env: ['browser', 'node'],
//     needs: [{name: 'request', type: 'Request'}, ...],
//     uses: [{name: 'logger', type: 'Logger'}] }

// 2. Check that you can satisfy the requirements
const check = SafeScript.checkScope(source, myScope);
if (!check.ok) throw new Error('Missing: ' + check.missing.join(', '));

// 3. Run with the scope you built
const result = await SafeScript.run(source, myScope);

(注:更多技术实现细节与完整 API 文档请查阅原项目 README)