@afterpack/wasm 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +133 -0
- package/dist/api.d.ts +11 -0
- package/dist/api.js +377 -0
- package/dist/cloud-base.d.ts +2 -0
- package/dist/cloud-base.js +8 -0
- package/dist/contract.d.ts +242 -0
- package/dist/contract.js +16 -0
- package/dist/engine.d.ts +11 -0
- package/dist/engine.js +40 -0
- package/dist/node.d.ts +1 -0
- package/dist/node.js +4 -0
- package/dist/workers.d.ts +1 -0
- package/dist/workers.js +4 -0
- package/engine/afterpack_engine_bg.d.ts +13 -0
- package/engine/afterpack_engine_bg.js +188 -0
- package/engine/afterpack_engine_bg.wasm +0 -0
- package/package.json +64 -0
- package/readme.md +92 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
AfterPack Engine License
|
|
2
|
+
|
|
3
|
+
Copyright 2026 AfterPack (https://www.afterpack.dev)
|
|
4
|
+
|
|
5
|
+
A plain-language summary is at https://www.afterpack.dev/license. The summary
|
|
6
|
+
is for convenience; these terms are the license.
|
|
7
|
+
|
|
8
|
+
## Acceptance
|
|
9
|
+
|
|
10
|
+
By using the software, you agree to all of the terms and conditions below.
|
|
11
|
+
|
|
12
|
+
## Copyright License
|
|
13
|
+
|
|
14
|
+
The licensor grants you a non-exclusive, royalty-free, worldwide,
|
|
15
|
+
non-sublicensable, non-transferable license to use and copy the software, and to
|
|
16
|
+
distribute unmodified copies of it as part of the dependencies of your own
|
|
17
|
+
projects (for example in `node_modules`, lockfiles, build caches and container
|
|
18
|
+
images), in each case subject to the limitations and conditions below. This
|
|
19
|
+
includes commercial use and use in continuous integration and build pipelines.
|
|
20
|
+
There are no usage limits.
|
|
21
|
+
|
|
22
|
+
## Output
|
|
23
|
+
|
|
24
|
+
Code transformed or produced by running the software is yours, subject only
|
|
25
|
+
to any rights others hold in the code you gave it. The licensor claims no
|
|
26
|
+
rights in that output, and no notice, attribution or royalty is required to use
|
|
27
|
+
or distribute it.
|
|
28
|
+
|
|
29
|
+
## Plugins and Integrations
|
|
30
|
+
|
|
31
|
+
You may write plugins, integrations and other tools that call the software's
|
|
32
|
+
documented public API, and license them however you choose. Such works are not
|
|
33
|
+
modifications of the software. They may depend on the software as a package
|
|
34
|
+
dependency, but any copy of the software they carry remains under these terms.
|
|
35
|
+
|
|
36
|
+
## Limitations
|
|
37
|
+
|
|
38
|
+
You may not distribute the software on its own, or as part of a product that
|
|
39
|
+
offers JavaScript obfuscation or code protection and competes with the
|
|
40
|
+
licensor.
|
|
41
|
+
|
|
42
|
+
You may not provide JavaScript obfuscation or code protection to third parties
|
|
43
|
+
as a hosted or managed service that is built on the software. Using the
|
|
44
|
+
software inside your own product or service, where protecting code is not what
|
|
45
|
+
you offer to others, is allowed: for example, protecting the code your product
|
|
46
|
+
ships, or your own users' traffic.
|
|
47
|
+
|
|
48
|
+
You may not modify, translate or create derivative works of the software.
|
|
49
|
+
|
|
50
|
+
You may not reverse engineer, decompile or disassemble the software.
|
|
51
|
+
|
|
52
|
+
You may not use the software for any unlawful purpose, or to create,
|
|
53
|
+
facilitate or distribute malware, spyware or phishing.
|
|
54
|
+
|
|
55
|
+
You may not alter, remove, or obscure any licensing, copyright, or other notices
|
|
56
|
+
of the licensor in the software. Any use of the licensor's trademarks is subject
|
|
57
|
+
to applicable law.
|
|
58
|
+
|
|
59
|
+
## Cloud Services
|
|
60
|
+
|
|
61
|
+
With an AfterPack Pro key, the software sends builds to the licensor's cloud
|
|
62
|
+
service. Use of that service is governed by the Terms of Service at
|
|
63
|
+
https://www.afterpack.dev/terms.
|
|
64
|
+
|
|
65
|
+
## Patents
|
|
66
|
+
|
|
67
|
+
The licensor grants you a license, under any patent claims the licensor can
|
|
68
|
+
license, or becomes able to license, to make, have made, use, sell, offer for
|
|
69
|
+
sale, import and have imported the software, in each case subject to the
|
|
70
|
+
limitations and conditions in this license. If you or your company make any
|
|
71
|
+
written claim that the software infringes or contributes to infringement of any
|
|
72
|
+
patent, your patent license for the software granted under these terms ends
|
|
73
|
+
immediately. If your company makes such a claim, your patent license ends
|
|
74
|
+
immediately for work on behalf of your company.
|
|
75
|
+
|
|
76
|
+
## Notices
|
|
77
|
+
|
|
78
|
+
You must ensure that anyone who gets a copy of any part of the software from you
|
|
79
|
+
also gets a copy of these terms.
|
|
80
|
+
|
|
81
|
+
## No Other Rights
|
|
82
|
+
|
|
83
|
+
These terms do not imply any licenses other than those expressly granted in
|
|
84
|
+
these terms.
|
|
85
|
+
|
|
86
|
+
## Termination
|
|
87
|
+
|
|
88
|
+
If you use the software in violation of these terms, such use is not licensed,
|
|
89
|
+
and your licenses will automatically terminate. If the licensor provides you
|
|
90
|
+
with a notice of your violation, and you cease all violation of this license no
|
|
91
|
+
later than 30 days after you receive that notice, your licenses will be
|
|
92
|
+
reinstated retroactively. However, if you violate these terms after such
|
|
93
|
+
reinstatement, any additional violation of these terms will cause your licenses
|
|
94
|
+
to terminate automatically and permanently. Output you created while licensed
|
|
95
|
+
remains yours.
|
|
96
|
+
|
|
97
|
+
## No Liability
|
|
98
|
+
|
|
99
|
+
AS FAR AS THE LAW ALLOWS, THE SOFTWARE COMES AS IS, WITHOUT ANY WARRANTY OR
|
|
100
|
+
CONDITION, AND THE LICENSOR WILL NOT BE LIABLE TO YOU FOR ANY DAMAGES ARISING
|
|
101
|
+
OUT OF THESE TERMS OR THE USE OR NATURE OF THE SOFTWARE, UNDER ANY KIND OF
|
|
102
|
+
LEGAL CLAIM.
|
|
103
|
+
|
|
104
|
+
## Definitions
|
|
105
|
+
|
|
106
|
+
The **licensor** is AfterPack, and the **software** is the AfterPack engine as
|
|
107
|
+
distributed in compiled form: the `@afterpack/core` and `@afterpack/wasm`
|
|
108
|
+
packages, the platform-specific `@afterpack/core-<platform>` packages that
|
|
109
|
+
carry its native binaries, and any other prebuilt AfterPack engine binary,
|
|
110
|
+
including any portion of them.
|
|
111
|
+
|
|
112
|
+
**you** refers to the individual or entity agreeing to these terms.
|
|
113
|
+
|
|
114
|
+
**your company** is any legal entity, sole proprietorship, or other kind of
|
|
115
|
+
organization that you work for, plus all organizations that have control over,
|
|
116
|
+
are under the control of, or are under common control with that
|
|
117
|
+
organization. **control** means ownership of substantially all the assets of an
|
|
118
|
+
entity, or the power to direct its management and policies by vote, contract, or
|
|
119
|
+
otherwise. Control can be direct or indirect.
|
|
120
|
+
|
|
121
|
+
**your licenses** are all the licenses granted to you for the software under
|
|
122
|
+
these terms.
|
|
123
|
+
|
|
124
|
+
**use** means anything you do with the software requiring one of your licenses.
|
|
125
|
+
|
|
126
|
+
**trademark** means trademarks, service marks, and similar rights.
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
These terms are adapted from the Elastic License 2.0
|
|
131
|
+
(https://www.elastic.co/licensing/elastic-license), whose text is available
|
|
132
|
+
under the Creative Commons Attribution 4.0 International license. This license
|
|
133
|
+
is not the Elastic License and is not endorsed by Elastic.
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { AfterpackConfig, FileInput, Result } from "./contract.js";
|
|
2
|
+
export * from "./contract.js";
|
|
3
|
+
/**
|
|
4
|
+
* Obfuscate several files in one build. Results come back in input order. With `config.key` set,
|
|
5
|
+
* the build runs in AfterPack's cloud. Throws an {@link ObfuscationError} when the build cannot ship.
|
|
6
|
+
*/
|
|
7
|
+
export declare function obfuscateAll(files: FileInput[], config?: AfterpackConfig): Promise<Result[]>;
|
|
8
|
+
/** Obfuscate one file. Throws an {@link ObfuscationError} when the build cannot ship. */
|
|
9
|
+
export declare function obfuscate(input: string | Uint8Array | FileInput, config?: AfterpackConfig): Promise<Result>;
|
|
10
|
+
/** The AfterPack engine version, e.g. `0.1.0`. */
|
|
11
|
+
export declare function version(): Promise<string>;
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
import { cloudApiBase } from "./cloud-base.js";
|
|
2
|
+
import { ObfuscationError } from "./contract.js";
|
|
3
|
+
import { engineVersion, processFile } from "./engine.js";
|
|
4
|
+
export * from "./contract.js";
|
|
5
|
+
const DIAG_OUTPUT_UNPARSEABLE = "DIAG_OUTPUT_UNPARSEABLE";
|
|
6
|
+
function engineCrash(cause) {
|
|
7
|
+
const error = new ObfuscationError("AfterPack engine hit an internal limit while processing this input in this environment " +
|
|
8
|
+
"(the build was not completed)", []);
|
|
9
|
+
error.cause = cause;
|
|
10
|
+
return error;
|
|
11
|
+
}
|
|
12
|
+
const decoder = new TextDecoder();
|
|
13
|
+
const encoder = new TextEncoder();
|
|
14
|
+
function sourceToString(source) {
|
|
15
|
+
return typeof source === "string" ? source : decoder.decode(source);
|
|
16
|
+
}
|
|
17
|
+
function isFileInput(input) {
|
|
18
|
+
return typeof input === "object" && input !== null && "source" in input;
|
|
19
|
+
}
|
|
20
|
+
function enginePath(file, index, total) {
|
|
21
|
+
if (file.path !== undefined)
|
|
22
|
+
return file.path;
|
|
23
|
+
return total === 1 ? "input.js" : `input-${index}.js`;
|
|
24
|
+
}
|
|
25
|
+
function blockingMessage(diagnostics) {
|
|
26
|
+
const messages = diagnostics
|
|
27
|
+
.filter((d) => d.severity === "error" || d.severity === "critical")
|
|
28
|
+
.map((d) => d.message.replace(/^AfterPack refused this build: /, ""));
|
|
29
|
+
return messages.length > 0 ? messages.join("; ") : null;
|
|
30
|
+
}
|
|
31
|
+
class ObfuscatedFile {
|
|
32
|
+
path;
|
|
33
|
+
code;
|
|
34
|
+
sourceMap;
|
|
35
|
+
diagnostics;
|
|
36
|
+
protectionMap;
|
|
37
|
+
#encoded = null;
|
|
38
|
+
constructor(path, code, sourceMap, diags, protectionMap) {
|
|
39
|
+
this.path = path;
|
|
40
|
+
this.code = code;
|
|
41
|
+
this.sourceMap = sourceMap;
|
|
42
|
+
this.diagnostics = diags;
|
|
43
|
+
this.protectionMap = protectionMap;
|
|
44
|
+
}
|
|
45
|
+
get bytes() {
|
|
46
|
+
if (this.#encoded === null)
|
|
47
|
+
this.#encoded = encoder.encode(this.code);
|
|
48
|
+
return this.#encoded;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const RETRYABLE_BACKOFF_SECONDS = [1, 4, 16];
|
|
52
|
+
const DEFAULT_RETRY_AFTER_SECONDS = 60;
|
|
53
|
+
const MAX_RETRY_AFTER_SECONDS = 120;
|
|
54
|
+
const REQUEST_TIMEOUT_MS = 120_000;
|
|
55
|
+
function sleep(ms) {
|
|
56
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
57
|
+
}
|
|
58
|
+
function engineConfigWithoutKey(config) {
|
|
59
|
+
const { key: _key, ...rest } = config;
|
|
60
|
+
return rest;
|
|
61
|
+
}
|
|
62
|
+
function buildCloudForm(files, paths, sources, engineConfig) {
|
|
63
|
+
const manifestFiles = files.map((file, i) => {
|
|
64
|
+
const entry = { filePath: paths[i], partName: `file-${i}` };
|
|
65
|
+
if (file.sourceMap !== undefined)
|
|
66
|
+
entry.sourceMapPartName = `map-${i}`;
|
|
67
|
+
return entry;
|
|
68
|
+
});
|
|
69
|
+
const form = new FormData();
|
|
70
|
+
form.append("batch", JSON.stringify({ version: "1", files: manifestFiles, config: engineConfig }));
|
|
71
|
+
files.forEach((file, i) => {
|
|
72
|
+
form.append(`file-${i}`, new Blob([sources[i]], { type: "application/javascript" }), paths[i]);
|
|
73
|
+
if (file.sourceMap !== undefined) {
|
|
74
|
+
form.append(`map-${i}`, new Blob([file.sourceMap], { type: "application/json" }));
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
return form;
|
|
78
|
+
}
|
|
79
|
+
function cloudDiagnostic(code, message) {
|
|
80
|
+
return { severity: "error", code, message, span: null, file: null };
|
|
81
|
+
}
|
|
82
|
+
function cloudNetworkError(cause) {
|
|
83
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
84
|
+
return new ObfuscationError(`AfterPack Pro cloud unreachable: ${message}`, [
|
|
85
|
+
cloudDiagnostic("DIAG_CLOUD_NETWORK_ERROR", message),
|
|
86
|
+
]);
|
|
87
|
+
}
|
|
88
|
+
const MAX_CLOUD_MESSAGE_CHARS = 500;
|
|
89
|
+
const MAX_CLOUD_NOTICES = 5;
|
|
90
|
+
const MAX_CLOUD_URL_CHARS = 2048;
|
|
91
|
+
const URL_UNSAFE = /[\s\p{Cc}]/u;
|
|
92
|
+
function displayText(text) {
|
|
93
|
+
const chars = Array.from(text);
|
|
94
|
+
let out = "";
|
|
95
|
+
let count = 0;
|
|
96
|
+
for (let i = 0; i < chars.length && count < MAX_CLOUD_MESSAGE_CHARS; i++) {
|
|
97
|
+
const c = chars[i];
|
|
98
|
+
const code = c.codePointAt(0) ?? 0;
|
|
99
|
+
if (code === 0x1b) {
|
|
100
|
+
const next = chars[i + 1];
|
|
101
|
+
i++;
|
|
102
|
+
if (next === "[") {
|
|
103
|
+
while (i + 1 < chars.length) {
|
|
104
|
+
i++;
|
|
105
|
+
const final = chars[i].codePointAt(0) ?? 0;
|
|
106
|
+
if (final >= 0x40 && final <= 0x7e)
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
else if (next === "]") {
|
|
111
|
+
while (i + 1 < chars.length) {
|
|
112
|
+
i++;
|
|
113
|
+
const inner = chars[i].codePointAt(0) ?? 0;
|
|
114
|
+
if (inner === 0x07)
|
|
115
|
+
break;
|
|
116
|
+
if (inner === 0x1b) {
|
|
117
|
+
if (chars[i + 1] === "\\")
|
|
118
|
+
i++;
|
|
119
|
+
break;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (c === "\t" || c === "\n" || c === "\r") {
|
|
126
|
+
out += " ";
|
|
127
|
+
count++;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (code < 0x20 || (code >= 0x7f && code <= 0x9f))
|
|
131
|
+
continue;
|
|
132
|
+
out += c;
|
|
133
|
+
count++;
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
function cloudErrorCode(status) {
|
|
138
|
+
if (status === 426)
|
|
139
|
+
return "AFTERPACK_CLOUD_UPGRADE_REQUIRED";
|
|
140
|
+
if (status === 410)
|
|
141
|
+
return "AFTERPACK_CLOUD_SUNSET";
|
|
142
|
+
return "AFTERPACK_CLOUD_API";
|
|
143
|
+
}
|
|
144
|
+
async function cloudApiError(response) {
|
|
145
|
+
const text = await response.text().catch(() => "");
|
|
146
|
+
let code = `HTTP_${response.status}`;
|
|
147
|
+
let message = text.trim().length > 0
|
|
148
|
+
? displayText(text.trim())
|
|
149
|
+
: `AfterPack Pro cloud request failed with status ${response.status}`;
|
|
150
|
+
let details = null;
|
|
151
|
+
let notices = null;
|
|
152
|
+
try {
|
|
153
|
+
const parsed = JSON.parse(text);
|
|
154
|
+
notices = cloudNotices(parsed.notices ?? parsed.error?.notices);
|
|
155
|
+
if (typeof parsed.error?.code === "string")
|
|
156
|
+
code = displayText(parsed.error.code);
|
|
157
|
+
if (typeof parsed.error?.message === "string")
|
|
158
|
+
message = displayText(parsed.error.message);
|
|
159
|
+
const raw = parsed.error?.details;
|
|
160
|
+
if (raw !== null && typeof raw === "object" && !Array.isArray(raw)) {
|
|
161
|
+
details = raw;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
catch { }
|
|
165
|
+
return new ObfuscationError(`AfterPack Pro cloud build refused (${code}): ${message}`, [cloudDiagnostic(code, message)], { code: cloudErrorCode(response.status), details, notices });
|
|
166
|
+
}
|
|
167
|
+
function cloudNotices(raw) {
|
|
168
|
+
if (!Array.isArray(raw))
|
|
169
|
+
return null;
|
|
170
|
+
const notices = [];
|
|
171
|
+
for (const entry of raw) {
|
|
172
|
+
if (notices.length >= MAX_CLOUD_NOTICES)
|
|
173
|
+
break;
|
|
174
|
+
if (entry === null || typeof entry !== "object")
|
|
175
|
+
continue;
|
|
176
|
+
const { severity, code, message, url } = entry;
|
|
177
|
+
if (typeof message !== "string")
|
|
178
|
+
continue;
|
|
179
|
+
notices.push({
|
|
180
|
+
severity: typeof severity === "string" ? displayText(severity) : "warning",
|
|
181
|
+
code: typeof code === "string" ? displayText(code) : "",
|
|
182
|
+
message: displayText(message),
|
|
183
|
+
...(typeof url === "string" && url.length <= MAX_CLOUD_URL_CHARS && !URL_UNSAFE.test(url)
|
|
184
|
+
? { url }
|
|
185
|
+
: {}),
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
return notices.length > 0 ? notices : null;
|
|
189
|
+
}
|
|
190
|
+
function clampRetryAfter(header) {
|
|
191
|
+
const parsed = header !== null ? Number.parseInt(header, 10) : Number.NaN;
|
|
192
|
+
const seconds = Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_RETRY_AFTER_SECONDS;
|
|
193
|
+
return Math.min(seconds, MAX_RETRY_AFTER_SECONDS);
|
|
194
|
+
}
|
|
195
|
+
async function requestCloudBatch(key, form) {
|
|
196
|
+
const url = `${cloudApiBase()}/v1/obfuscate/batch`;
|
|
197
|
+
let rateLimitedOnce = false;
|
|
198
|
+
let backoffAttempt = 0;
|
|
199
|
+
for (;;) {
|
|
200
|
+
let response;
|
|
201
|
+
try {
|
|
202
|
+
response = await fetch(url, {
|
|
203
|
+
method: "POST",
|
|
204
|
+
headers: { Authorization: `Bearer ${key}` },
|
|
205
|
+
body: form,
|
|
206
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
catch (cause) {
|
|
210
|
+
throw cloudNetworkError(cause);
|
|
211
|
+
}
|
|
212
|
+
if (response.ok)
|
|
213
|
+
return response;
|
|
214
|
+
if (response.status === 429) {
|
|
215
|
+
const retryAfterSeconds = clampRetryAfter(response.headers.get("retry-after"));
|
|
216
|
+
if (!rateLimitedOnce) {
|
|
217
|
+
rateLimitedOnce = true;
|
|
218
|
+
await sleep(retryAfterSeconds * 1000);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
throw new ObfuscationError("AfterPack Pro cloud rate limited this build after honoring Retry-After once", [cloudDiagnostic("DIAG_RATE_LIMITED", "rate limited after honoring Retry-After once")]);
|
|
222
|
+
}
|
|
223
|
+
if (response.status === 503 || response.status === 504) {
|
|
224
|
+
if (backoffAttempt < RETRYABLE_BACKOFF_SECONDS.length) {
|
|
225
|
+
const delaySeconds = RETRYABLE_BACKOFF_SECONDS[backoffAttempt];
|
|
226
|
+
backoffAttempt += 1;
|
|
227
|
+
await sleep(delaySeconds * 1000);
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
const message = `server returned ${response.status} after ${backoffAttempt} retries`;
|
|
231
|
+
throw new ObfuscationError(`AfterPack Pro cloud unreachable: ${message}`, [
|
|
232
|
+
cloudDiagnostic("DIAG_CLOUD_DOWN", message),
|
|
233
|
+
]);
|
|
234
|
+
}
|
|
235
|
+
throw await cloudApiError(response);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
function extractBoundary(contentType) {
|
|
239
|
+
if (contentType === null)
|
|
240
|
+
return null;
|
|
241
|
+
for (const segment of contentType.split(";")) {
|
|
242
|
+
const trimmed = segment.trim();
|
|
243
|
+
if (trimmed.startsWith("boundary=")) {
|
|
244
|
+
return trimmed.slice("boundary=".length).replace(/^"|"$/g, "");
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
249
|
+
function parseMultipartMixed(text, boundary) {
|
|
250
|
+
const delimiter = `--${boundary}`;
|
|
251
|
+
if (!text.includes(`${delimiter}--`)) {
|
|
252
|
+
throw new ObfuscationError(`AfterPack Pro cloud response was truncated (${text.length} bytes received with no ` +
|
|
253
|
+
"closing multipart delimiter) -- this is a server-side failure, nothing was shipped", []);
|
|
254
|
+
}
|
|
255
|
+
const results = [];
|
|
256
|
+
let summary = null;
|
|
257
|
+
for (const rawPart of text.split(delimiter)) {
|
|
258
|
+
const part = rawPart.trim();
|
|
259
|
+
if (part === "" || part === "--")
|
|
260
|
+
continue;
|
|
261
|
+
const crlfEnd = part.indexOf("\r\n\r\n");
|
|
262
|
+
const [idx, sepLen] = crlfEnd !== -1 ? [crlfEnd, 4] : [part.indexOf("\n\n"), 2];
|
|
263
|
+
if (idx === -1)
|
|
264
|
+
continue;
|
|
265
|
+
const headers = part.slice(0, idx);
|
|
266
|
+
const body = part.slice(idx + sepLen).trim();
|
|
267
|
+
try {
|
|
268
|
+
if (headers.includes('name="batch-summary"')) {
|
|
269
|
+
summary = JSON.parse(body);
|
|
270
|
+
}
|
|
271
|
+
else if (headers.includes('name="obfuscation-result"')) {
|
|
272
|
+
results.push(JSON.parse(body));
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
catch (cause) {
|
|
276
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
277
|
+
throw new ObfuscationError(`AfterPack Pro cloud sent an unparseable response part: ${message}`, []);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
if (summary === null) {
|
|
281
|
+
throw new ObfuscationError("AfterPack Pro cloud response ended without a batch-summary part", []);
|
|
282
|
+
}
|
|
283
|
+
return { results, summary };
|
|
284
|
+
}
|
|
285
|
+
function validateCompleteness(paths, results) {
|
|
286
|
+
const expected = new Set(paths);
|
|
287
|
+
const returned = new Set(results.map((r) => r.filePath));
|
|
288
|
+
const missing = [...expected].filter((p) => !returned.has(p)).sort();
|
|
289
|
+
const unexpected = [...returned].filter((p) => !expected.has(p)).sort();
|
|
290
|
+
if (missing.length === 0 && unexpected.length === 0)
|
|
291
|
+
return;
|
|
292
|
+
throw new ObfuscationError("AfterPack Pro cloud response file set does not match the request " +
|
|
293
|
+
`(missing: ${JSON.stringify(missing)}, unexpected: ${JSON.stringify(unexpected)})`, []);
|
|
294
|
+
}
|
|
295
|
+
function inRequestOrder(paths, results) {
|
|
296
|
+
const pending = new Map();
|
|
297
|
+
results.forEach((result, i) => {
|
|
298
|
+
const bucket = pending.get(result.filePath);
|
|
299
|
+
if (bucket === undefined)
|
|
300
|
+
pending.set(result.filePath, [i]);
|
|
301
|
+
else
|
|
302
|
+
bucket.push(i);
|
|
303
|
+
});
|
|
304
|
+
return paths.map((path) => {
|
|
305
|
+
const at = pending.get(path)?.shift();
|
|
306
|
+
if (at === undefined)
|
|
307
|
+
throw new ObfuscationError(`the cloud returned no result for ${path}`, []);
|
|
308
|
+
return results[at];
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
async function obfuscateAllCloud(files, paths, sources, key, config) {
|
|
312
|
+
const form = buildCloudForm(files, paths, sources, engineConfigWithoutKey(config));
|
|
313
|
+
const response = await requestCloudBatch(key, form);
|
|
314
|
+
const boundary = extractBoundary(response.headers.get("content-type"));
|
|
315
|
+
if (boundary === null) {
|
|
316
|
+
throw new ObfuscationError("AfterPack Pro cloud returned a 200 response with no multipart boundary", []);
|
|
317
|
+
}
|
|
318
|
+
const text = await response.text();
|
|
319
|
+
const { results } = parseMultipartMixed(text, boundary);
|
|
320
|
+
validateCompleteness(paths, results);
|
|
321
|
+
const ordered = inRequestOrder(paths, results);
|
|
322
|
+
const failed = ordered.filter((result) => result.status !== "success" || result.output === null || result.output === undefined);
|
|
323
|
+
if (failed.length > 0) {
|
|
324
|
+
const detail = failed
|
|
325
|
+
.map((result) => `${result.filePath}: cloud obfuscation failed (status: ${result.status})`)
|
|
326
|
+
.join("; ");
|
|
327
|
+
throw new ObfuscationError(`AfterPack refused this build — ${detail}`, []);
|
|
328
|
+
}
|
|
329
|
+
return ordered.map((result, i) => new ObfuscatedFile(files[i].path ?? null, result.output, result.outputMap ?? null, [], null));
|
|
330
|
+
}
|
|
331
|
+
export async function obfuscateAll(files, config) {
|
|
332
|
+
const paths = files.map((file, i) => enginePath(file, i, files.length));
|
|
333
|
+
const sources = files.map((file) => sourceToString(file.source));
|
|
334
|
+
if (config?.key !== undefined) {
|
|
335
|
+
return obfuscateAllCloud(files, paths, sources, config.key, config);
|
|
336
|
+
}
|
|
337
|
+
let results;
|
|
338
|
+
try {
|
|
339
|
+
results = files.map((file, i) => processFile(sources[i], file.sourceMap ?? "", JSON.stringify({ ...(config ?? {}), filePath: paths[i] })));
|
|
340
|
+
}
|
|
341
|
+
catch (cause) {
|
|
342
|
+
throw engineCrash(cause);
|
|
343
|
+
}
|
|
344
|
+
const everyDiagnostic = results.flatMap((result) => result.diagnostics);
|
|
345
|
+
const failed = results
|
|
346
|
+
.map((result, i) => ({ path: paths[i], error: blockingMessage(result.diagnostics) }))
|
|
347
|
+
.filter((file) => file.error !== null);
|
|
348
|
+
if (failed.length > 0) {
|
|
349
|
+
const detail = failed.map((file) => `${file.path}: ${file.error}`).join("; ");
|
|
350
|
+
throw new ObfuscationError(`AfterPack refused this build — ${detail}`, everyDiagnostic);
|
|
351
|
+
}
|
|
352
|
+
const cleartext = results
|
|
353
|
+
.map((result, i) => ({
|
|
354
|
+
path: paths[i],
|
|
355
|
+
discarded: result.diagnostics.some((d) => d.code === DIAG_OUTPUT_UNPARSEABLE) ||
|
|
356
|
+
(result.code === "" && sources[i].trim() !== ""),
|
|
357
|
+
}))
|
|
358
|
+
.filter((file) => file.discarded);
|
|
359
|
+
if (cleartext.length > 0) {
|
|
360
|
+
const named = cleartext.map((file) => file.path).join(", ");
|
|
361
|
+
throw new ObfuscationError(`AfterPack refused this build — obfuscation was discarded and ${named} would ship as cleartext`, everyDiagnostic);
|
|
362
|
+
}
|
|
363
|
+
return results.map((result, i) => new ObfuscatedFile(files[i].path ?? null, result.code, result.sourceMap, result.diagnostics, result.protectionMap ?? null));
|
|
364
|
+
}
|
|
365
|
+
export async function obfuscate(input, config) {
|
|
366
|
+
const file = isFileInput(input) ? input : { source: input };
|
|
367
|
+
const [only] = await obfuscateAll([file], config);
|
|
368
|
+
return only;
|
|
369
|
+
}
|
|
370
|
+
export async function version() {
|
|
371
|
+
try {
|
|
372
|
+
return engineVersion();
|
|
373
|
+
}
|
|
374
|
+
catch (cause) {
|
|
375
|
+
throw engineCrash(cause);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/** A named protection level. Sets `complexity` and the output-size budget together. */
|
|
2
|
+
export type Preset = "minify" | "light" | "medium" | "hard" | "extreme";
|
|
3
|
+
/** A kind of transformation that a region can allow or deny. */
|
|
4
|
+
export type TransformKind = ConfigurableTransform | "stringEncoding";
|
|
5
|
+
type ConfigurableTransform = "controlFlowFlatten" | "opaquePredicate" | "mixedBooleanArithmetic" | "integerBytecode" | "crossDependency" | "scopeDeepen" | "comparisonHardening" | "selfIntegrity" | "objectConstruction";
|
|
6
|
+
/** A runtime reflection pattern your code relies on. `angular` and `nestjs` cover what those frameworks need. */
|
|
7
|
+
export type ReflectionAllow = "functionToString" | "nameIntrospection" | "argumentsCallee" | "prototypeChain" | "decoratorMetadata" | "constructorIntrospection" | "angular" | "nestjs";
|
|
8
|
+
/** Names kept as written, but only inside files that match `glob`. */
|
|
9
|
+
export interface GlobReserved {
|
|
10
|
+
/** Files the names are kept in, e.g. `legacy/**`. */
|
|
11
|
+
glob: string;
|
|
12
|
+
/** Identifier names never renamed in those files. */
|
|
13
|
+
names: string[];
|
|
14
|
+
}
|
|
15
|
+
/** A protection override for one byte range of the original source. Applied on AfterPack Pro builds. */
|
|
16
|
+
export interface RegionConfig {
|
|
17
|
+
/** Start byte offset in the original source, inclusive. */
|
|
18
|
+
start: number;
|
|
19
|
+
/** End byte offset in the original source, exclusive. */
|
|
20
|
+
end: number;
|
|
21
|
+
/** Overrides `complexity` inside the range. `0` applies no transformation there. */
|
|
22
|
+
complexity?: number;
|
|
23
|
+
/** Overrides `inflation` inside the range. */
|
|
24
|
+
inflation?: {
|
|
25
|
+
/** The largest allowed output for the range, as a multiple of its input size. */
|
|
26
|
+
max?: number;
|
|
27
|
+
};
|
|
28
|
+
/** Overrides `strings` inside the range. */
|
|
29
|
+
strings?: {
|
|
30
|
+
/** Encode string literals inside the range. `false` leaves them readable. */
|
|
31
|
+
encode?: boolean;
|
|
32
|
+
};
|
|
33
|
+
/** Overrides `transforms` inside the range. */
|
|
34
|
+
transforms?: {
|
|
35
|
+
/** Only these transformations may apply inside the range. */
|
|
36
|
+
only?: TransformKind[];
|
|
37
|
+
/** These transformations never apply inside the range. */
|
|
38
|
+
deny?: TransformKind[];
|
|
39
|
+
};
|
|
40
|
+
/** A name for the range, shown in the Protection Map. */
|
|
41
|
+
label?: string;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Build configuration. Unknown keys are refused, so a typo fails the build instead of being
|
|
45
|
+
* ignored. Every option: https://www.afterpack.dev/docs/config
|
|
46
|
+
*/
|
|
47
|
+
export interface AfterpackConfig {
|
|
48
|
+
/** The random seed. Unset, every build produces different output; set it to reproduce a build. */
|
|
49
|
+
seed?: number | string;
|
|
50
|
+
/** Your AfterPack Pro key. With a key, the build runs in AfterPack's cloud with much stronger protection. */
|
|
51
|
+
key?: string;
|
|
52
|
+
/** A named protection level. Defaults to `light`. */
|
|
53
|
+
preset?: Preset;
|
|
54
|
+
/** How much protection to apply. `0` applies none; higher values apply more and grow the output. */
|
|
55
|
+
complexity?: number;
|
|
56
|
+
/** Runtime reflection your code relies on. A detected pattern that is not listed fails the build. */
|
|
57
|
+
reflection?: {
|
|
58
|
+
allow?: ReflectionAllow[];
|
|
59
|
+
};
|
|
60
|
+
/** Files to leave untouched, as globs. */
|
|
61
|
+
paths?: {
|
|
62
|
+
exclude?: string[];
|
|
63
|
+
};
|
|
64
|
+
/** Identifier renaming. */
|
|
65
|
+
identifiers?: {
|
|
66
|
+
/** Rename identifiers. `false` keeps every name. */
|
|
67
|
+
rename?: boolean;
|
|
68
|
+
/** Names that are never renamed. */
|
|
69
|
+
reserved?: (string | GlobReserved)[];
|
|
70
|
+
/** Also rename the top-level names of a classic script. */
|
|
71
|
+
globals?: {
|
|
72
|
+
rename?: boolean;
|
|
73
|
+
};
|
|
74
|
+
/** Rename class methods. `false` keeps them for code that reads `fn.name`. */
|
|
75
|
+
methods?: {
|
|
76
|
+
rename?: boolean;
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
/** Output size. `max` is the largest allowed output as a multiple of the input size. */
|
|
80
|
+
inflation?: {
|
|
81
|
+
max?: number | "unlimited";
|
|
82
|
+
};
|
|
83
|
+
/** String literals. */
|
|
84
|
+
strings?: {
|
|
85
|
+
/** Encode string literals so that none stays readable. */
|
|
86
|
+
encode?: boolean;
|
|
87
|
+
/** The shortest string that is encoded. */
|
|
88
|
+
minLength?: number;
|
|
89
|
+
/** Fail the build when more than `max` readable string literals remain. */
|
|
90
|
+
leaks?: {
|
|
91
|
+
max?: number;
|
|
92
|
+
};
|
|
93
|
+
/** String values kept exactly as written, for placeholders a later build step replaces. */
|
|
94
|
+
preserveLiterals?: string[];
|
|
95
|
+
};
|
|
96
|
+
/** Source map output. Never deploy a map: it reverses the obfuscation. */
|
|
97
|
+
sourceMap?: {
|
|
98
|
+
enabled?: boolean;
|
|
99
|
+
sourcesContent?: boolean;
|
|
100
|
+
};
|
|
101
|
+
/** The Protection Map, a report of what was applied where. It contains your source; never publish it. */
|
|
102
|
+
protectionMap?: {
|
|
103
|
+
enabled?: boolean;
|
|
104
|
+
detailed?: boolean;
|
|
105
|
+
};
|
|
106
|
+
/** Protection overrides for byte ranges of the source. */
|
|
107
|
+
regions?: RegionConfig[];
|
|
108
|
+
/** Switch a transformation off with `{ enabled: false }`. */
|
|
109
|
+
transforms?: Partial<Record<ConfigurableTransform, {
|
|
110
|
+
enabled?: boolean;
|
|
111
|
+
}>>;
|
|
112
|
+
}
|
|
113
|
+
/** One file to obfuscate. */
|
|
114
|
+
export interface FileInput {
|
|
115
|
+
/** The file's path, used in results and diagnostics. */
|
|
116
|
+
path?: string;
|
|
117
|
+
/** The JavaScript source. */
|
|
118
|
+
source: string | Uint8Array;
|
|
119
|
+
/** The file's existing source map, so the output map points back to your original source. */
|
|
120
|
+
sourceMap?: string;
|
|
121
|
+
}
|
|
122
|
+
/** `info` never blocks a build; `error` and `critical` do. */
|
|
123
|
+
export type Severity = "info" | "error" | "critical";
|
|
124
|
+
/** A byte range in the original source. */
|
|
125
|
+
export interface Span {
|
|
126
|
+
/** Start byte offset, inclusive. */
|
|
127
|
+
startByte: number;
|
|
128
|
+
/** End byte offset, exclusive. */
|
|
129
|
+
endByte: number;
|
|
130
|
+
}
|
|
131
|
+
/** Something AfterPack reports about a build. Codes: https://www.afterpack.dev/docs/diagnostics */
|
|
132
|
+
export interface Diagnostic {
|
|
133
|
+
/** How serious it is. */
|
|
134
|
+
severity: Severity;
|
|
135
|
+
/** A stable identifier, e.g. `DIAG_PARSE_ERROR`. */
|
|
136
|
+
code: string;
|
|
137
|
+
/** A readable explanation. */
|
|
138
|
+
message: string;
|
|
139
|
+
/** The file it refers to, or `null`. */
|
|
140
|
+
file: string | null;
|
|
141
|
+
/** The source range it refers to, or `null`. */
|
|
142
|
+
span: Span | null;
|
|
143
|
+
}
|
|
144
|
+
/** One obfuscated file. */
|
|
145
|
+
export interface Result {
|
|
146
|
+
/** The input's `path`, or `null` when none was given. */
|
|
147
|
+
path: string | null;
|
|
148
|
+
/** The output as UTF-8 bytes, ready to write. */
|
|
149
|
+
bytes: Uint8Array;
|
|
150
|
+
/** The output as a string. */
|
|
151
|
+
readonly code: string;
|
|
152
|
+
/** The output source map, or `null`. */
|
|
153
|
+
sourceMap: string | null;
|
|
154
|
+
/** Diagnostics for this file. */
|
|
155
|
+
diagnostics: Diagnostic[];
|
|
156
|
+
/** What AfterPack applied to this build, or `null` unless `protectionMap.enabled` is set. It contains your source; never publish it. */
|
|
157
|
+
protectionMap: ProtectionMap | null;
|
|
158
|
+
}
|
|
159
|
+
/** What AfterPack applied to a build, file by file. It contains your original source, so keep it private. */
|
|
160
|
+
export interface ProtectionMap {
|
|
161
|
+
/** The version of this report's format. */
|
|
162
|
+
schemaVersion: number;
|
|
163
|
+
/** The unit every span in the report is measured in. */
|
|
164
|
+
spanUnits?: "utf16";
|
|
165
|
+
/** When the report was produced, or `null` when the build did not record a time. */
|
|
166
|
+
generatedAt: string | null;
|
|
167
|
+
/** The engine settings the build ran with. */
|
|
168
|
+
engine: {
|
|
169
|
+
/** The engine version that produced the build. */
|
|
170
|
+
version: string;
|
|
171
|
+
/** Which engine path ran the build. */
|
|
172
|
+
backend: string;
|
|
173
|
+
/** The seed the build used. */
|
|
174
|
+
seed: number;
|
|
175
|
+
/** The named protection level, or `null` when none was set. */
|
|
176
|
+
preset: Preset | null;
|
|
177
|
+
/** How much protection was applied. */
|
|
178
|
+
complexity: number;
|
|
179
|
+
[key: string]: unknown;
|
|
180
|
+
};
|
|
181
|
+
/** One entry per file in the build. */
|
|
182
|
+
files: ProtectionMapFile[];
|
|
183
|
+
}
|
|
184
|
+
/** The protection report for one file in a build. */
|
|
185
|
+
export interface ProtectionMapFile {
|
|
186
|
+
/** The file and its original source. */
|
|
187
|
+
file: {
|
|
188
|
+
/** The file's path, or `null` when none was given. */
|
|
189
|
+
path: string | null;
|
|
190
|
+
/** The file's original source. */
|
|
191
|
+
originalSource: string;
|
|
192
|
+
/** The input size in bytes. */
|
|
193
|
+
inputSize: number;
|
|
194
|
+
/** The output size in bytes. */
|
|
195
|
+
outputSize: number;
|
|
196
|
+
[key: string]: unknown;
|
|
197
|
+
};
|
|
198
|
+
/** What was applied across ranges of the file. */
|
|
199
|
+
regions: Record<string, unknown>[];
|
|
200
|
+
/** Notable spots the report calls out. */
|
|
201
|
+
spotlights: Record<string, unknown>[];
|
|
202
|
+
/** Totals for the whole file. */
|
|
203
|
+
aggregate: Record<string, unknown>;
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* `code` on an error from a cloud build that the AfterPack service refused.
|
|
207
|
+
* `AFTERPACK_CLOUD_UPGRADE_REQUIRED`: this version is no longer accepted; `details.minVersion` names
|
|
208
|
+
* the one to install. `AFTERPACK_CLOUD_SUNSET`: the API this version speaks is retired.
|
|
209
|
+
* `AFTERPACK_CLOUD_API`: any other refusal.
|
|
210
|
+
*/
|
|
211
|
+
export type CloudErrorCode = "AFTERPACK_CLOUD_UPGRADE_REQUIRED" | "AFTERPACK_CLOUD_SUNSET" | "AFTERPACK_CLOUD_API";
|
|
212
|
+
/**
|
|
213
|
+
* A message from the AfterPack service for the person running the build. Treat every field as
|
|
214
|
+
* untrusted display text.
|
|
215
|
+
*/
|
|
216
|
+
export interface Notice {
|
|
217
|
+
/** How to present it, e.g. `info` or `warning`. */
|
|
218
|
+
severity: string;
|
|
219
|
+
/** A stable identifier for the notice. */
|
|
220
|
+
code: string;
|
|
221
|
+
/** The text to show. */
|
|
222
|
+
message: string;
|
|
223
|
+
/** A link with more detail. */
|
|
224
|
+
url?: string;
|
|
225
|
+
}
|
|
226
|
+
/** Thrown when a build cannot ship: AfterPack refused it, or a file would ship unprotected. */
|
|
227
|
+
export declare class ObfuscationError extends Error {
|
|
228
|
+
/** Diagnostics that explain the failure. */
|
|
229
|
+
readonly diagnostics: Diagnostic[];
|
|
230
|
+
/** Set when the AfterPack service refused a cloud build. */
|
|
231
|
+
readonly code?: CloudErrorCode;
|
|
232
|
+
/** Structured detail from the service, such as `minVersion`. */
|
|
233
|
+
readonly details?: Record<string, unknown> | null;
|
|
234
|
+
/** Messages from the service attached to the refusal. */
|
|
235
|
+
readonly notices?: Notice[] | null;
|
|
236
|
+
constructor(message: string, diagnostics: Diagnostic[], cloud?: {
|
|
237
|
+
code: CloudErrorCode;
|
|
238
|
+
details: Record<string, unknown> | null;
|
|
239
|
+
notices: Notice[] | null;
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
export {};
|
package/dist/contract.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export class ObfuscationError extends Error {
|
|
2
|
+
diagnostics;
|
|
3
|
+
code;
|
|
4
|
+
details;
|
|
5
|
+
notices;
|
|
6
|
+
constructor(message, diagnostics, cloud) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "ObfuscationError";
|
|
9
|
+
this.diagnostics = diagnostics;
|
|
10
|
+
if (cloud !== undefined) {
|
|
11
|
+
this.code = cloud.code;
|
|
12
|
+
this.details = cloud.details;
|
|
13
|
+
this.notices = cloud.notices;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
package/dist/engine.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Diagnostic, ProtectionMap } from "./contract.js";
|
|
2
|
+
export type ModuleSource = () => WebAssembly.Module;
|
|
3
|
+
export interface EngineOutput {
|
|
4
|
+
code: string;
|
|
5
|
+
sourceMap: string | null;
|
|
6
|
+
diagnostics: Diagnostic[];
|
|
7
|
+
protectionMap?: ProtectionMap | null;
|
|
8
|
+
}
|
|
9
|
+
export declare function useModule(source: ModuleSource): void;
|
|
10
|
+
export declare function engineVersion(): string;
|
|
11
|
+
export declare function processFile(source: string, inputSourceMap: string, configJson: string): EngineOutput;
|
package/dist/engine.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import * as glue from "../engine/afterpack_engine_bg.js";
|
|
2
|
+
let loadModule = null;
|
|
3
|
+
let bound = false;
|
|
4
|
+
let boundMemory = null;
|
|
5
|
+
export function useModule(source) {
|
|
6
|
+
loadModule = source;
|
|
7
|
+
}
|
|
8
|
+
function bind() {
|
|
9
|
+
if (bound)
|
|
10
|
+
return;
|
|
11
|
+
if (loadModule === null) {
|
|
12
|
+
throw new Error("@afterpack/wasm loaded with no runtime entry point. Import the package by name so " +
|
|
13
|
+
"its `workerd` / `node` export condition resolves, rather than a file inside it.");
|
|
14
|
+
}
|
|
15
|
+
const { exports } = new WebAssembly.Instance(loadModule());
|
|
16
|
+
glue.__wbg_set_wasm(exports);
|
|
17
|
+
boundMemory = exports.memory;
|
|
18
|
+
bound = true;
|
|
19
|
+
}
|
|
20
|
+
function dropInstance() {
|
|
21
|
+
bound = false;
|
|
22
|
+
boundMemory?.grow(0);
|
|
23
|
+
boundMemory = null;
|
|
24
|
+
}
|
|
25
|
+
function callEngine(call) {
|
|
26
|
+
bind();
|
|
27
|
+
try {
|
|
28
|
+
return call();
|
|
29
|
+
}
|
|
30
|
+
catch (cause) {
|
|
31
|
+
dropInstance();
|
|
32
|
+
throw cause;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function engineVersion() {
|
|
36
|
+
return callEngine(() => glue.version());
|
|
37
|
+
}
|
|
38
|
+
export function processFile(source, inputSourceMap, configJson) {
|
|
39
|
+
return callEngine(() => JSON.parse(glue.process_with_map(source, inputSourceMap, configJson)));
|
|
40
|
+
}
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./api.js";
|
package/dist/node.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./api.js";
|
package/dist/workers.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export function __wbg_set_wasm(exports: WebAssembly.Exports): void;
|
|
2
|
+
|
|
3
|
+
export function process(input: string, config_json: string): string;
|
|
4
|
+
|
|
5
|
+
export function process_with_map(
|
|
6
|
+
input: string,
|
|
7
|
+
input_source_map: string,
|
|
8
|
+
config_json: string,
|
|
9
|
+
): string;
|
|
10
|
+
|
|
11
|
+
export function version(): string;
|
|
12
|
+
|
|
13
|
+
export function validate_config(config_json: string): string;
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @param {string} input
|
|
3
|
+
* @param {string} config_json
|
|
4
|
+
* @returns {string}
|
|
5
|
+
*/
|
|
6
|
+
export function process(input, config_json) {
|
|
7
|
+
let deferred3_0;
|
|
8
|
+
let deferred3_1;
|
|
9
|
+
try {
|
|
10
|
+
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
|
|
11
|
+
const ptr0 = passStringToWasm0(input, wasm.__wbindgen_export, wasm.__wbindgen_export2);
|
|
12
|
+
const len0 = WASM_VECTOR_LEN;
|
|
13
|
+
const ptr1 = passStringToWasm0(config_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);
|
|
14
|
+
const len1 = WASM_VECTOR_LEN;
|
|
15
|
+
wasm.process(retptr, ptr0, len0, ptr1, len1);
|
|
16
|
+
var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
|
|
17
|
+
var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
|
|
18
|
+
deferred3_0 = r0;
|
|
19
|
+
deferred3_1 = r1;
|
|
20
|
+
return getStringFromWasm0(r0, r1);
|
|
21
|
+
} finally {
|
|
22
|
+
wasm.__wbindgen_add_to_stack_pointer(16);
|
|
23
|
+
wasm.__wbindgen_export3(deferred3_0, deferred3_1, 1);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* @param {string} input
|
|
29
|
+
* @param {string} input_source_map
|
|
30
|
+
* @param {string} config_json
|
|
31
|
+
* @returns {string}
|
|
32
|
+
*/
|
|
33
|
+
export function process_with_map(input, input_source_map, config_json) {
|
|
34
|
+
let deferred4_0;
|
|
35
|
+
let deferred4_1;
|
|
36
|
+
try {
|
|
37
|
+
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
|
|
38
|
+
const ptr0 = passStringToWasm0(input, wasm.__wbindgen_export, wasm.__wbindgen_export2);
|
|
39
|
+
const len0 = WASM_VECTOR_LEN;
|
|
40
|
+
const ptr1 = passStringToWasm0(input_source_map, wasm.__wbindgen_export, wasm.__wbindgen_export2);
|
|
41
|
+
const len1 = WASM_VECTOR_LEN;
|
|
42
|
+
const ptr2 = passStringToWasm0(config_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);
|
|
43
|
+
const len2 = WASM_VECTOR_LEN;
|
|
44
|
+
wasm.process_with_map(retptr, ptr0, len0, ptr1, len1, ptr2, len2);
|
|
45
|
+
var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
|
|
46
|
+
var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
|
|
47
|
+
deferred4_0 = r0;
|
|
48
|
+
deferred4_1 = r1;
|
|
49
|
+
return getStringFromWasm0(r0, r1);
|
|
50
|
+
} finally {
|
|
51
|
+
wasm.__wbindgen_add_to_stack_pointer(16);
|
|
52
|
+
wasm.__wbindgen_export3(deferred4_0, deferred4_1, 1);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* @param {string} config_json
|
|
58
|
+
* @returns {string}
|
|
59
|
+
*/
|
|
60
|
+
export function validate_config(config_json) {
|
|
61
|
+
let deferred2_0;
|
|
62
|
+
let deferred2_1;
|
|
63
|
+
try {
|
|
64
|
+
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
|
|
65
|
+
const ptr0 = passStringToWasm0(config_json, wasm.__wbindgen_export, wasm.__wbindgen_export2);
|
|
66
|
+
const len0 = WASM_VECTOR_LEN;
|
|
67
|
+
wasm.validate_config(retptr, ptr0, len0);
|
|
68
|
+
var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
|
|
69
|
+
var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
|
|
70
|
+
deferred2_0 = r0;
|
|
71
|
+
deferred2_1 = r1;
|
|
72
|
+
return getStringFromWasm0(r0, r1);
|
|
73
|
+
} finally {
|
|
74
|
+
wasm.__wbindgen_add_to_stack_pointer(16);
|
|
75
|
+
wasm.__wbindgen_export3(deferred2_0, deferred2_1, 1);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* @returns {string}
|
|
81
|
+
*/
|
|
82
|
+
export function version() {
|
|
83
|
+
let deferred1_0;
|
|
84
|
+
let deferred1_1;
|
|
85
|
+
try {
|
|
86
|
+
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
|
|
87
|
+
wasm.version(retptr);
|
|
88
|
+
var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true);
|
|
89
|
+
var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true);
|
|
90
|
+
deferred1_0 = r0;
|
|
91
|
+
deferred1_1 = r1;
|
|
92
|
+
return getStringFromWasm0(r0, r1);
|
|
93
|
+
} finally {
|
|
94
|
+
wasm.__wbindgen_add_to_stack_pointer(16);
|
|
95
|
+
wasm.__wbindgen_export3(deferred1_0, deferred1_1, 1);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
let cachedDataViewMemory0 = null;
|
|
99
|
+
function getDataViewMemory0() {
|
|
100
|
+
if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
|
|
101
|
+
cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
|
|
102
|
+
}
|
|
103
|
+
return cachedDataViewMemory0;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function getStringFromWasm0(ptr, len) {
|
|
107
|
+
return decodeText(ptr >>> 0, len);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
let cachedUint8ArrayMemory0 = null;
|
|
111
|
+
function getUint8ArrayMemory0() {
|
|
112
|
+
if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
|
|
113
|
+
cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
|
|
114
|
+
}
|
|
115
|
+
return cachedUint8ArrayMemory0;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function passStringToWasm0(arg, malloc, realloc) {
|
|
119
|
+
if (realloc === undefined) {
|
|
120
|
+
const buf = cachedTextEncoder.encode(arg);
|
|
121
|
+
const ptr = malloc(buf.length, 1) >>> 0;
|
|
122
|
+
getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf);
|
|
123
|
+
WASM_VECTOR_LEN = buf.length;
|
|
124
|
+
return ptr;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
let len = arg.length;
|
|
128
|
+
let ptr = malloc(len, 1) >>> 0;
|
|
129
|
+
|
|
130
|
+
const mem = getUint8ArrayMemory0();
|
|
131
|
+
|
|
132
|
+
let offset = 0;
|
|
133
|
+
|
|
134
|
+
for (; offset < len; offset++) {
|
|
135
|
+
const code = arg.charCodeAt(offset);
|
|
136
|
+
if (code > 0x7F) break;
|
|
137
|
+
mem[ptr + offset] = code;
|
|
138
|
+
}
|
|
139
|
+
if (offset !== len) {
|
|
140
|
+
if (offset !== 0) {
|
|
141
|
+
arg = arg.slice(offset);
|
|
142
|
+
}
|
|
143
|
+
ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
|
|
144
|
+
const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
|
|
145
|
+
const ret = cachedTextEncoder.encodeInto(arg, view);
|
|
146
|
+
|
|
147
|
+
offset += ret.written;
|
|
148
|
+
ptr = realloc(ptr, len, offset, 1) >>> 0;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
WASM_VECTOR_LEN = offset;
|
|
152
|
+
return ptr;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
|
|
156
|
+
cachedTextDecoder.decode();
|
|
157
|
+
const MAX_SAFARI_DECODE_BYTES = 2146435072;
|
|
158
|
+
let numBytesDecoded = 0;
|
|
159
|
+
function decodeText(ptr, len) {
|
|
160
|
+
numBytesDecoded += len;
|
|
161
|
+
if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
|
|
162
|
+
cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
|
|
163
|
+
cachedTextDecoder.decode();
|
|
164
|
+
numBytesDecoded = len;
|
|
165
|
+
}
|
|
166
|
+
return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const cachedTextEncoder = new TextEncoder();
|
|
170
|
+
|
|
171
|
+
if (!('encodeInto' in cachedTextEncoder)) {
|
|
172
|
+
cachedTextEncoder.encodeInto = function (arg, view) {
|
|
173
|
+
const buf = cachedTextEncoder.encode(arg);
|
|
174
|
+
view.set(buf);
|
|
175
|
+
return {
|
|
176
|
+
read: arg.length,
|
|
177
|
+
written: buf.length
|
|
178
|
+
};
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
let WASM_VECTOR_LEN = 0;
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
let wasm;
|
|
186
|
+
export function __wbg_set_wasm(val) {
|
|
187
|
+
wasm = val;
|
|
188
|
+
}
|
|
Binary file
|
package/package.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@afterpack/wasm",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "The AfterPack JavaScript obfuscator as WebAssembly, for Cloudflare Workers and Node",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/node.js",
|
|
7
|
+
"types": "./dist/node.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"workerd": {
|
|
11
|
+
"types": "./dist/workers.d.ts",
|
|
12
|
+
"default": "./dist/workers.js"
|
|
13
|
+
},
|
|
14
|
+
"worker": {
|
|
15
|
+
"types": "./dist/workers.d.ts",
|
|
16
|
+
"default": "./dist/workers.js"
|
|
17
|
+
},
|
|
18
|
+
"node": {
|
|
19
|
+
"types": "./dist/node.d.ts",
|
|
20
|
+
"default": "./dist/node.js"
|
|
21
|
+
},
|
|
22
|
+
"default": {
|
|
23
|
+
"types": "./dist/workers.d.ts",
|
|
24
|
+
"default": "./dist/workers.js"
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"./package.json": "./package.json"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist",
|
|
31
|
+
"engine/afterpack_engine_bg.d.ts",
|
|
32
|
+
"engine/afterpack_engine_bg.js",
|
|
33
|
+
"engine/afterpack_engine_bg.wasm",
|
|
34
|
+
"readme.md"
|
|
35
|
+
],
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=18"
|
|
38
|
+
},
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public",
|
|
41
|
+
"registry": "https://registry.npmjs.org/"
|
|
42
|
+
},
|
|
43
|
+
"homepage": "https://www.afterpack.dev/docs/workers",
|
|
44
|
+
"bugs": {
|
|
45
|
+
"url": "https://github.com/afterpack-dev/afterpack/issues"
|
|
46
|
+
},
|
|
47
|
+
"keywords": [
|
|
48
|
+
"obfuscator",
|
|
49
|
+
"javascript-obfuscator",
|
|
50
|
+
"obfuscation",
|
|
51
|
+
"javascript",
|
|
52
|
+
"code-protection",
|
|
53
|
+
"source-code-protection",
|
|
54
|
+
"javascript-security",
|
|
55
|
+
"anti-reverse-engineering",
|
|
56
|
+
"webassembly",
|
|
57
|
+
"wasm",
|
|
58
|
+
"cloudflare-workers",
|
|
59
|
+
"edge",
|
|
60
|
+
"afterpack"
|
|
61
|
+
],
|
|
62
|
+
"author": "AfterPack <hello@afterpack.dev>",
|
|
63
|
+
"license": "SEE LICENSE IN LICENSE"
|
|
64
|
+
}
|
package/readme.md
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# @afterpack/wasm
|
|
2
|
+
|
|
3
|
+
The [AfterPack JavaScript obfuscator](https://www.afterpack.dev) as WebAssembly. Use it where a native Node addon can't load, for example to obfuscate JavaScript in a Cloudflare Worker. It also runs in Node.
|
|
4
|
+
|
|
5
|
+
For a normal Node build, use [`@afterpack/core`](https://www.npmjs.com/package/@afterpack/core). It has the same `obfuscate` and `obfuscateAll` API, runs natively and keeps the work off the main thread. Want to try AfterPack first? The [playground](https://www.afterpack.dev/playground) obfuscates JavaScript in your browser.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @afterpack/wasm
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## In a Cloudflare Worker
|
|
14
|
+
|
|
15
|
+
No init step, no `nodejs_compat` flag and no extra wrangler rules.
|
|
16
|
+
|
|
17
|
+
```javascript
|
|
18
|
+
import { obfuscate } from "@afterpack/wasm";
|
|
19
|
+
|
|
20
|
+
export default {
|
|
21
|
+
async fetch(request) {
|
|
22
|
+
const source = await request.text();
|
|
23
|
+
const result = await obfuscate({ path: "app.js", source }, { preset: "hard" });
|
|
24
|
+
return new Response(result.bytes, {
|
|
25
|
+
headers: { "content-type": "application/javascript" },
|
|
26
|
+
});
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The full guide: [obfuscate JavaScript in a Cloudflare Worker](https://www.afterpack.dev/docs/workers).
|
|
32
|
+
|
|
33
|
+
## In Node
|
|
34
|
+
|
|
35
|
+
Same import. The package picks its Node entry automatically.
|
|
36
|
+
|
|
37
|
+
```javascript
|
|
38
|
+
import { obfuscate, obfuscateAll, version } from "@afterpack/wasm";
|
|
39
|
+
|
|
40
|
+
const result = await obfuscate('console.log("hello")', { preset: "hard" });
|
|
41
|
+
result.code; // the obfuscated source
|
|
42
|
+
result.bytes; // the same output as bytes, ready to write
|
|
43
|
+
|
|
44
|
+
// Several files at once. Results come back in input order.
|
|
45
|
+
const results = await obfuscateAll([
|
|
46
|
+
{ path: "dist/app.js", source: appSource },
|
|
47
|
+
{ path: "dist/vendor.js", source: vendorSource, sourceMap: vendorMap },
|
|
48
|
+
]);
|
|
49
|
+
|
|
50
|
+
await version(); // "0.1.0"
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`obfuscate` accepts a string, a `Uint8Array`, or a file object `{ path, source, sourceMap }`, where `sourceMap` is the file's existing map to chain. Each result has `code`, `bytes`, `sourceMap` and `diagnostics`. The second argument is the config. See the [configuration reference](https://www.afterpack.dev/docs/config) and the [presets](https://www.afterpack.dev/docs/presets).
|
|
54
|
+
|
|
55
|
+
## Errors
|
|
56
|
+
|
|
57
|
+
If a build can't ship safely, the call throws an `ObfuscationError` with the engine's diagnostics. That covers an invalid config, a blocking diagnostic, or output that would go out unprotected.
|
|
58
|
+
|
|
59
|
+
```javascript
|
|
60
|
+
import { obfuscate, ObfuscationError } from "@afterpack/wasm";
|
|
61
|
+
|
|
62
|
+
try {
|
|
63
|
+
await obfuscate(source);
|
|
64
|
+
} catch (err) {
|
|
65
|
+
if (err instanceof ObfuscationError) console.error(err.diagnostics);
|
|
66
|
+
throw err;
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
## Pro
|
|
71
|
+
|
|
72
|
+
Without a key, this package runs AfterPack inside your Worker or Node process and applies basic protection. Add a Pro key (`{ key: env.AFTERPACK_KEY }`) and the same call sends the build to AfterPack's cloud, which applies much stronger protection. That protection runs only in the cloud and is never part of this package. See [deployment modes](https://www.afterpack.dev/docs/deployment-modes), [AfterPack Pro](https://www.afterpack.dev/docs/pro) and [pricing](https://www.afterpack.dev/#pricing).
|
|
73
|
+
|
|
74
|
+
## Size
|
|
75
|
+
|
|
76
|
+
| Measure | Bytes | |
|
|
77
|
+
|---|---:|---|
|
|
78
|
+
| Raw `.wasm` | 4,979,041 | 4.75 MiB |
|
|
79
|
+
| Gzipped | 1,506,446 | 1.44 MiB |
|
|
80
|
+
|
|
81
|
+
This fits Cloudflare's Worker size limit on both the free and paid plans. CPU time is the tighter limit: the free plan allows 10 ms per request, and obfuscating a 185 KB bundle at `complexity: 8` takes about 263 ms on an Apple M-series laptop. Plan on Workers Paid for real bundles.
|
|
82
|
+
|
|
83
|
+
## Limits
|
|
84
|
+
|
|
85
|
+
- No browser entry. It runs in Workers and Node.
|
|
86
|
+
- Each file is one synchronous engine call that holds the isolate until it finishes. `obfuscateAll` processes files one at a time.
|
|
87
|
+
|
|
88
|
+
## License
|
|
89
|
+
|
|
90
|
+
Free for any use, including commercial and CI, with no limits, and the output is yours. You can't redistribute the binary on its own, build a competing obfuscation product or service on it, or reverse engineer it. See the [AfterPack Engine License](https://www.afterpack.dev/license).
|
|
91
|
+
|
|
92
|
+
Questions and feedback: [get in touch](https://www.afterpack.dev/contact). Bug reports: [GitHub](https://github.com/afterpack-dev/afterpack/issues).
|