Protecting a TypeScript library you publish: ship typings, hide the implementation
本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。
If you publish a TypeScript library — especially a paid SDK — you want two things that look like they conflict. Consumers should get excellent typings: autocomplete, jump-to-definition on the public API, no any leaking into their project. They should not get a readable copy of your implementation.
如果您发布一个 TypeScript 库(尤其是付费 SDK),您会想要两样看起来相互冲突的东西。用户应该获得出色的类型定义:自动补全、公共 API 的跳转定义,且项目中不会有任何 any 类型泄露。同时,他们不应该获得您实现代码的可读副本。
Those goals do not conflict if you treat .d.ts as the product surface and the runtime JavaScript as a different artifact. The typings describe what can be called. The published JavaScript is how it runs. You can ship the first in the clear and make the second much harder to casually copy.
如果您将 .d.ts 文件视为产品表面,将运行时 JavaScript 视为不同的产物,那么这些目标并不冲突。类型定义描述了可以调用的内容,而发布的 JavaScript 则是运行方式。您可以明文发布前者,并使后者难以被随意复制。
You cannot make the runtime secret — consumers have to execute it — and you should not use this technique to hide malware or to dodge a package registry’s rules. You can, however, stop shipping your src/ tree by accident, and you can stop a one-line if (licensed) from being the entire paid gate.
您无法让运行时代码成为秘密(因为用户必须执行它),也不应使用此技术来隐藏恶意软件或规避包注册表的规则。然而,您可以防止意外发布 src/ 目录,并防止仅靠一行 if (licensed) 这种简单的逻辑就成为付费门槛。
What to put in the package
包中应包含什么
A clean package.json for a library that ships typings and hidden-enough JavaScript looks like this:
一个用于发布类型定义和足够隐蔽的 JavaScript 的库,其整洁的 package.json 如下所示:
{
"name": "@acme/sdk",
"version": "2.4.0",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
}
},
"files": [
"dist/index.js",
"dist/index.mjs",
"dist/index.d.ts",
"README.md",
"LICENSE"
],
"sideEffects": false
}
The important parts: types (and the types condition in exports) points at declaration files only. main / module (and import / require) point at compiled JavaScript, not at TypeScript source. files is an allowlist. If you omit it, you are one forgotten .gitignore or npm config away from publishing src/, tests, internal docs, and .env.example. There is no *.map in files. There is no src/ in files.
关键点在于:types(以及 exports 中的 types 条件)仅指向声明文件。main / module(以及 import / require)指向编译后的 JavaScript,而非 TypeScript 源码。files 是一个白名单。如果您忽略它,一旦忘记配置 .gitignore 或 npm 配置,就可能导致 src/、测试文件、内部文档和 .env.example 被发布出去。files 中不应包含 *.map,也不应包含 src/。
Confirm what you are about to publish before you do it:
npm pack --dry-run
# or npm pack && tar -tf acme-sdk-2.4.0.tgz
If src/engine.ts or dist/index.js.map is in that list, stop.
在发布之前,请确认您即将发布的内容:
npm pack --dry-run
# 或 npm pack && tar -tf acme-sdk-2.4.0.tgz
如果列表中包含 src/engine.ts 或 dist/index.js.map,请立即停止。
Declaration maps and source maps leak the original declaration: true is what you want. declarationMap: true is not — not for a published tarball. A .d.ts.map tells the consumer’s editor how to jump from a declaration to the original .ts file. If that original file is also in the package (or is reachable via a relative path that exists after install), “Go to Definition” becomes “open the implementation.”
声明映射(declaration maps)和源映射(source maps)会泄露原始声明:您需要的是 declaration: true。对于发布的压缩包而言,declarationMap: true 是不合适的。.d.ts.map 会告诉用户的编辑器如何从声明跳转到原始的 .ts 文件。如果该原始文件也包含在包中(或者在安装后可以通过相对路径访问),那么“转到定义”就会变成“打开实现代码”。
Source maps for the JavaScript have the same problem in a slightly different place. A dist/index.js.map with sourcesContent, or a //# sourceMappingURL comment that points at a file you also published, is an undo button for minification and obfuscation.
JavaScript 的源映射在不同层面存在同样的问题。带有 sourcesContent 的 dist/index.js.map,或者指向您已发布文件的 //# sourceMappingURL 注释,相当于为代码压缩和混淆提供了一个“撤销”按钮。
Use a publish-time tsconfig that emits typings and does not emit maps:
请使用一个在发布时使用的 tsconfig,它只生成类型定义而不生成映射文件:
{
"compilerOptions": {
"declaration": true,
"declarationMap": false,
"sourceMap": false,
"inlineSources": false,
"inlineSourceMap": false
}
}
If you need maps for your own debugging of the SDK, keep them in a private artifact store, not in the npm tarball. After the build, a last check:
find dist -name "*.map" -o -name "*.d.ts.map"
grep -R "sourceMappingURL" dist || true
Both should be empty for the files you publish.
如果您需要映射文件来调试 SDK,请将它们保存在私有的制品库中,而不是 npm 压缩包里。构建完成后,进行最后一次检查:
find dist -name "*.map" -o -name "*.d.ts.map"
grep -R "sourceMappingURL" dist || true
对于您发布的文件,这两项检查的结果都应为空。
Types describe the API, not the algorithm
类型定义描述的是 API,而非算法
A .d.ts file contains signatures, exported types, and maybe JSDoc. It does not (in normal emit) contain function bodies. That is the split you want:
.d.ts 文件包含签名、导出的类型以及可能的 JSDoc。它(在正常生成时)不包含函数体。这正是您想要的拆分方式:
// dist/index.d.ts — this is supposed to be public
export interface QuoteInput {
seats: number;
plan: "free" | "pro";
coupon?: string;
}
export function quote(input: QuoteInput): Promise<Quote>;
export function verifyLicense(token: string): Promise<boolean>;
Consumers get a precise contract. They do not get quote’s internals from the typings. Be careful not to undo that by: publishing src/ “for reference,” inlining implementation notes into JSDoc that you would not put in a README, exporting internal types that name hidden states, magic constants, or unpublished plans, bundling a “debug build” next to the production file.
用户获得的是精确的契约。他们无法从类型定义中获取 quote 的内部实现。请注意不要通过以下方式破坏这一点:为了“参考”而发布 src/;将不应放入 README 的实现细节写入 JSDoc;导出包含隐藏状态、魔术常量或未发布计划名称的内部类型;在生产文件旁边捆绑“调试版本”。
The typings will reveal the shape of the API. That is their job. The algorithm, the heuristics, and the license check belong in the runtime file.
类型定义会揭示 API 的结构,这是它们的职责。算法、启发式逻辑和许可证检查应保留在运行时文件中。
Consumers can still hook what you export
用户仍然可以挂钩您导出的内容
Anyone who installs the package can import it, wrap it, and inspect values at the edges:
任何安装了该包的人都可以导入它、包装它,并在边界处检查值:
import { quote } from "@acme/sdk";
const original = quote;
export async function quoteWrapped(input: QuoteInput) {
const result = await original(input);
console.log("quote", input, result);
return result;
}
They can also read the published JavaScript. Minification already helps against a casual glance. Ordinary obfuscation (renaming, string encoding, light control-flow changes) makes wholesale copy-paste less pleasant.
他们也可以阅读已发布的 JavaScript。代码压缩有助于防止随意浏览。普通的混淆(重命名、字符串编码、轻微的控制流更改)会使大规模的复制粘贴变得不那么容易。
For a paid SDK, the internals that actually hurt to lose — a solver, a ranking function, a non-trivial license or entitlement check — are a fit for VM-style protection: selected functions compiled to a custom bytecode and run by a small interpreter, so the original control flow is not sitting in dist/index.js waiting to be pretty-printed.
对于付费 SDK,那些丢失后会造成实际损失的内部逻辑(如求解器、排名函数、复杂的许可证或授权检查)适合采用虚拟机(VM)式的保护:将选定的函数编译为自定义字节码,并由一个小型的解释器运行,这样原始的控制流就不会直接暴露在 dist/index.js 中等待被格式化。
In particular, do not let a paid gate collapse to a one-line if. A check like if (payload.plan === "pro") return true will be found and patched, typings or not. Keep license and auth decisions as far from a single obvious branch as you can on the client, and still have a server confirm anything that grants access to your backend.
特别要注意,不要让付费门槛简化为一行 if 语句。像 if (payload.plan === "pro") return true 这样的检查,无论是否有类型定义,都会被发现并被破解。在客户端,尽量让许可证和授权决策远离单一的明显分支,并始终通过服务器来确认任何授予后端访问权限的操作。
VEILVM is a browser-based JSVMP workspace you can point at one of those internal functions before you add a CI step. Interpreted code is slower, so protect the core of the SDK, not every helper, and run your package tests against the protected build.
VEILVM 是一个基于浏览器的 JSVMP 工作区,您可以在添加 CI 步骤之前将其指向这些内部函数之一。解释执行的代码速度较慢,因此请保护 SDK 的核心部分,而不是每一个辅助函数,并针对受保护的构建版本运行您的包测试。
Be honest with registries and with users
对注册表和用户保持诚实
Package managers and hosted registries have policies about malware, unexpected network behavior, and (in some places) heavy obfuscation that conceals what a package does. Do not use protection to hide malicious or surprising behavior. Do not ship an SDK that phones home in a way the typings and README do not describe. A reasonable paid library is explicit: the public API is documented and typed; the runtime…
包管理器和托管注册表对于恶意软件、意外的网络行为以及(在某些地方)掩盖包功能的深度混淆都有相关政策。不要使用保护技术来隐藏恶意或令人惊讶的行为。不要发布一个以类型定义和 README 中未描述的方式向外发送数据的 SDK。一个合理的付费库应该是明确的:公共 API 有文档和类型定义;运行时……