@afterpack/electron 0.1.0-rc.20260925T1347

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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 AfterPack
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ AfterPack CLI and framework integrations
2
+ Copyright 2026 AfterPack — https://www.afterpack.dev
3
+
4
+ This product includes software developed at AfterPack (https://www.afterpack.dev).
package/README.md ADDED
@@ -0,0 +1,140 @@
1
+ # @afterpack/electron
2
+
3
+ Electron app source protection for electron-vite and Electron Forge. `@afterpack/electron`
4
+ obfuscates the main, preload and renderer bundles of one app with one shared seed, using the
5
+ [AfterPack](https://www.afterpack.dev) JavaScript obfuscator.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install --save-dev @afterpack/electron
11
+ ```
12
+
13
+ ## electron-vite
14
+
15
+ Wrap your config once:
16
+
17
+ ```ts
18
+ // electron.vite.config.ts
19
+ import { withAfterpack } from "@afterpack/electron";
20
+ import { defineConfig, externalizeDepsPlugin } from "electron-vite";
21
+
22
+ export default withAfterpack(
23
+ defineConfig({
24
+ main: { plugins: [externalizeDepsPlugin()] },
25
+ preload: { plugins: [externalizeDepsPlugin()] },
26
+ renderer: {},
27
+ }),
28
+ );
29
+ ```
30
+
31
+ `withAfterpack` adds AfterPack to each of `main`, `preload` and `renderer` that your config has, and
32
+ prints which ones it wired. Each bundle is obfuscated before Vite writes it. If obfuscation fails,
33
+ the build fails.
34
+
35
+ ## Electron Forge with Vite
36
+
37
+ Forge loads each Vite config separately, so add the plugin to each one and name the part it builds:
38
+
39
+ ```ts
40
+ // vite.main.config.ts (and the same in vite.preload and vite.renderer, with their leg)
41
+ import { afterpackElectron } from "@afterpack/electron";
42
+
43
+ export default { plugins: [afterpackElectron({ leg: "main" })] };
44
+ ```
45
+
46
+ `leg` is required and is one of `"main"`, `"preload"` or `"renderer"`.
47
+
48
+ ## One seed for the whole app
49
+
50
+ Every part of one build shares one seed, so main, preload and renderer are obfuscated as one
51
+ program. A new seed is drawn for each build. When your build script runs each part as a separate
52
+ command, there is no shared process, so pin the seed in the environment:
53
+
54
+ ```sh
55
+ AFTERPACK_SEED=git npm run build
56
+ ```
57
+
58
+ ## Other toolchains
59
+
60
+ | Toolchain | Setup |
61
+ | --- | --- |
62
+ | electron-vite | `withAfterpack(defineConfig({ ... }))` |
63
+ | Electron Forge + Vite | `afterpackElectron({ leg })` in each config |
64
+ | Electron Forge + webpack | [`@afterpack/webpack`](https://www.npmjs.com/package/@afterpack/webpack) in each config |
65
+ | vite-plugin-electron | `afterpackElectron({ leg: "renderer" })`, placed last |
66
+ | electron-builder | packages, does not bundle; set up the bundler it packages |
67
+ | separate build commands | one plugin per part, with `AFTERPACK_SEED` set |
68
+
69
+ ## Keep local files out of app.asar
70
+
71
+ AfterPack writes its Protection Map to `.afterpack/`. It contains your original source, so exclude
72
+ it from the packaged app. The plugin prints this reminder when it finds a packager config:
73
+
74
+ ```jsonc
75
+ // electron-builder
76
+ "files": ["**/*", "!.afterpack/**", "!**/*.backup.*", "!**/*.map"]
77
+ // Electron Forge
78
+ packagerConfig: { ignore: [/^\/\.afterpack/, /\.backup\./, /\.map$/] }
79
+ ```
80
+
81
+ ## Options
82
+
83
+ ```ts
84
+ withAfterpack(config, { preset: "hard", seed: "git" });
85
+ ```
86
+
87
+ | Option | What it does | Default |
88
+ | --- | --- | --- |
89
+ | [`preset`][preset] | `"minify"`, `"light"`, `"medium"`, `"hard"` or `"extreme"` | `"light"` |
90
+ | [`seed`][seed] | a number or string; `"git"` uses the current commit | a new random seed per build, shared by every part |
91
+ | [`identifiers.reserved`][identifiers.reserved] | names never to rename | none |
92
+ | [`protectionMap.enabled`][protectionMap.enabled] | write the Protection Map, one per part in `.afterpack/<leg>/` | on when Vite emits source maps |
93
+ | [`build.autorun`][build.autorun] | `false` turns AfterPack off | `true` |
94
+ | `leg` | plugin option: `"main"`, `"preload"` or `"renderer"`; required for `afterpackElectron` | set by `withAfterpack` |
95
+ | `projectRoot` | plugin option: the app root that ties the parts into one build | `process.cwd()` |
96
+
97
+ Every other [`@afterpack/vite`](https://www.npmjs.com/package/@afterpack/vite) option works too, and
98
+ every other option is in the [configuration reference](https://www.afterpack.dev/docs/config).
99
+ Options can also live in `afterpack.json` or in `AFTERPACK_*` environment variables.
100
+
101
+ [preset]: https://www.afterpack.dev/docs/config#preset
102
+ [seed]: https://www.afterpack.dev/docs/config#seed
103
+ [identifiers.reserved]: https://www.afterpack.dev/docs/config#identifiers-reserved
104
+ [protectionMap.enabled]: https://www.afterpack.dev/docs/config#protectionMap-enabled
105
+ [build.autorun]: https://www.afterpack.dev/docs/config#build-autorun
106
+ [build.backup]: https://www.afterpack.dev/docs/config#build-backup
107
+ [sourceMap.enabled]: https://www.afterpack.dev/docs/config#sourceMap-enabled
108
+
109
+ ## What the plugin refuses
110
+
111
+ - electron-vite's `bytecodePlugin` on the same part, or `.jsc` files in the output: the build fails.
112
+ Bytecode replaces the bundle AfterPack would protect, so the two cannot be combined.
113
+ - [`build.backup`][build.backup] set to `true`: the build fails, because the backup would hold your
114
+ original source inside `app.asar`.
115
+ - [Source maps][sourceMap.enabled] turned on: a warning, since a map inside `app.asar` gives your
116
+ source away.
117
+
118
+ ## Pro
119
+
120
+ Without a key, AfterPack runs on your machine and applies basic protection. Set
121
+ [`AFTERPACK_KEY`](https://www.afterpack.dev/docs/config#key) in your environment and the same plugin
122
+ sends the build to AfterPack's cloud, which applies much stronger protection. Keep the key out of
123
+ your Vite config. See [AfterPack Pro](https://www.afterpack.dev/docs/pro).
124
+
125
+ ## Links
126
+
127
+ - [Electron setup guide](https://www.afterpack.dev/docs/frameworks/electron)
128
+ - [Protect an Electron app's license check](https://www.afterpack.dev/docs/use-cases/electron-license-logic)
129
+ - [Presets and protection levels](https://www.afterpack.dev/docs/presets)
130
+ - [How AfterPack compares to other obfuscators](https://www.afterpack.dev/docs/comparison)
131
+
132
+ ## License
133
+
134
+ Apache-2.0. The engine it runs, `@afterpack/core`, has its own
135
+ [license](https://www.afterpack.dev/license).
136
+
137
+ ## Feedback
138
+
139
+ Questions, suggestions and bug reports: [afterpack.dev/contact](https://www.afterpack.dev/contact).
140
+ You can also file a bug on [GitHub Issues](https://github.com/afterpack-dev/afterpack/issues).
package/dist/index.cjs ADDED
@@ -0,0 +1,167 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+ const node_fs = __toESM(require("node:fs"));
25
+ const node_path = __toESM(require("node:path"));
26
+ const __afterpack_integration_utils = __toESM(require("@afterpack/integration-utils"));
27
+ const __afterpack_vite = __toESM(require("@afterpack/vite"));
28
+
29
+ //#region src/notices.ts
30
+ const PACKAGER_CONFIGS = [
31
+ "electron-builder.yml",
32
+ "electron-builder.yaml",
33
+ "electron-builder.json",
34
+ "electron-builder.json5",
35
+ "electron-builder.toml",
36
+ "electron-builder.config.js",
37
+ "electron-builder.config.cjs",
38
+ "electron-builder.config.mjs",
39
+ "electron-builder.config.ts",
40
+ "forge.config.js",
41
+ "forge.config.cjs",
42
+ "forge.config.mjs",
43
+ "forge.config.ts"
44
+ ];
45
+ const NOTICE_STATE = Symbol.for("afterpack.electron.notices");
46
+ function sharedNoticeState() {
47
+ const holder = globalThis;
48
+ holder[NOTICE_STATE] ??= {
49
+ seenLegs: new Set(),
50
+ leakWarned: false,
51
+ advisoryArmed: false,
52
+ envSeedPinned: void 0
53
+ };
54
+ return holder[NOTICE_STATE];
55
+ }
56
+ const state = sharedNoticeState();
57
+ function recordEnvSeedPinned() {
58
+ state.envSeedPinned ??= process.env[__afterpack_integration_utils.SEED_ENV_VAR] != null;
59
+ }
60
+ function hasPackagerConfig(root) {
61
+ if (PACKAGER_CONFIGS.some((name) => (0, node_fs.existsSync)((0, node_path.join)(root, name)))) return true;
62
+ try {
63
+ const pkg = JSON.parse((0, node_fs.readFileSync)((0, node_path.join)(root, "package.json"), "utf8"));
64
+ return pkg.build != null || pkg.config?.forge != null;
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+ function warnPackagedTreeLeak(root, warn) {
70
+ if (state.leakWarned || !hasPackagerConfig(root)) return;
71
+ state.leakWarned = true;
72
+ warn("[afterpack-electron] this project has an Electron packager config. AfterPack's artifacts embed ORIGINAL SOURCE and are NOT excluded by default — add\n electron-builder: \"files\": [\"**/*\", \"!.afterpack/**\", \"!**/*.backup.*\", \"!**/*.map\"]\n electron-forge: packagerConfig.ignore: [/^\\/\\.afterpack/, /\\.backup\\./, /\\.map$/]\nor they ship inside app.asar.");
73
+ }
74
+ function recordLegBuilt(leg, seedPinned) {
75
+ state.seenLegs.add(leg);
76
+ if (state.advisoryArmed || seedPinned || state.envSeedPinned) return;
77
+ state.advisoryArmed = true;
78
+ process.on("exit", () => {
79
+ if (state.seenLegs.size > 1) return;
80
+ console.warn(`[afterpack-electron] only the "${[...state.seenLegs][0]}" leg was obfuscated in this process, so the other legs drew their own seeds. Set ${__afterpack_integration_utils.SEED_ENV_VAR}=git (or a pinned value) once in the shared build script so every leg shares one.`);
81
+ });
82
+ }
83
+
84
+ //#endregion
85
+ //#region src/index.ts
86
+ const BYTECODE_PLUGIN = "vite:bytecode";
87
+ const BYTECODE_EXT = /\.c?jsc$/;
88
+ function collectBytecodeChunks(dir, found = []) {
89
+ if (!(0, node_fs.existsSync)(dir)) return found;
90
+ for (const name of (0, node_fs.readdirSync)(dir)) {
91
+ const full = (0, node_path.join)(dir, name);
92
+ if ((0, node_fs.statSync)(full).isDirectory()) collectBytecodeChunks(full, found);
93
+ else if (BYTECODE_EXT.test(name)) found.push(full);
94
+ }
95
+ return found;
96
+ }
97
+ function bytecodeRefusal(leg, what) {
98
+ return new Error(`[afterpack-electron:${leg}] ${what}. electron-vite's bytecodePlugin replaces every emitted chunk with a 3-line loader and ships the real application as V8 bytecode (.jsc), so AfterPack would obfuscate the loader and report success while the application itself went untouched. They cannot compose (bytecode replaces the chunk Rollup generated): drop bytecodePlugin, or drop AfterPack for this leg.`);
99
+ }
100
+ function guardPlugin(leg, seedPinned) {
101
+ let outDir = "";
102
+ return {
103
+ name: `afterpack-electron:${leg}`,
104
+ configResolved(config) {
105
+ outDir = (0, node_path.resolve)(config.root, config.build.outDir);
106
+ recordEnvSeedPinned();
107
+ if (config.plugins.some((p) => p.name === BYTECODE_PLUGIN)) throw bytecodeRefusal(leg, `${BYTECODE_PLUGIN} is enabled for this leg`);
108
+ warnPackagedTreeLeak(config.root, (m) => config.logger ? config.logger.warn(m) : console.warn(m));
109
+ },
110
+ closeBundle() {
111
+ const bytecode = collectBytecodeChunks(outDir);
112
+ if (bytecode.length > 0) throw bytecodeRefusal(leg, `${bytecode.length} V8 bytecode chunk(s) are in ${outDir}`);
113
+ recordLegBuilt(leg, seedPinned);
114
+ }
115
+ };
116
+ }
117
+ function afterpackElectron(options) {
118
+ const { leg,...rest } = options;
119
+ const resolvedSettings = (0, __afterpack_integration_utils.resolvePluginConfig)({
120
+ label: `afterpack-electron:${leg}`,
121
+ options: rest,
122
+ localKeys: ["projectRoot"]
123
+ }).options;
124
+ const artifacts = resolvedSettings.artifactOptions;
125
+ if (artifacts.build?.backup === true) throw new Error(`[afterpack-electron:${leg}] build.backup:true writes a .backup.<hash>.js holding the COMPLETE original source next to each output, inside the tree the packager copies into app.asar — every user would receive your source. Remove it.`);
126
+ if (artifacts.sourceMap?.enabled === true || artifacts.sourceMap?.emitUrl === true) console.warn(`[afterpack-electron:${leg}] source maps are enabled. A .map with sourcesContent inside app.asar is full deobfuscation — keep this to local debug builds, and exclude *.map from the packaged files.`);
127
+ const sharedSeedProjectRoot = rest.projectRoot ?? process.cwd();
128
+ const obfuscationPlugin = (0, __afterpack_vite.afterpackVite)({
129
+ ...rest,
130
+ leg,
131
+ projectRoot: sharedSeedProjectRoot
132
+ });
133
+ const bytecodeAndSeedGuardPlugin = guardPlugin(leg, resolvedSettings.seed !== void 0);
134
+ return [obfuscationPlugin, bytecodeAndSeedGuardPlugin];
135
+ }
136
+ const LEGS = [
137
+ "main",
138
+ "preload",
139
+ "renderer"
140
+ ];
141
+ function injectLegs(config, options) {
142
+ const wired = [];
143
+ for (const leg of LEGS) {
144
+ const legConfig = config[leg];
145
+ if (!legConfig) continue;
146
+ legConfig.plugins = [...legConfig.plugins ?? [], afterpackElectron({
147
+ ...options,
148
+ leg
149
+ })];
150
+ wired.push(leg);
151
+ }
152
+ if (wired.length === 0) throw new Error("[afterpack-electron] withAfterpack() found no main/preload/renderer section on this config — it must wrap an electron-vite config, not a plain Vite one.");
153
+ console.log(`[afterpack-electron] wired into legs: ${wired.join(", ")}`);
154
+ return config;
155
+ }
156
+ function withAfterpack(config, options = {}) {
157
+ if (typeof config === "function") return (env) => {
158
+ const resolved = config(env);
159
+ return resolved instanceof Promise ? resolved.then((c) => injectLegs(c, options)) : injectLegs(resolved, options);
160
+ };
161
+ if (config instanceof Promise) return config.then((c) => injectLegs(c, options));
162
+ return injectLegs(config, options);
163
+ }
164
+
165
+ //#endregion
166
+ exports.afterpackElectron = afterpackElectron;
167
+ exports.withAfterpack = withAfterpack;
@@ -0,0 +1,14 @@
1
+ import { AfterpackPluginOptions } from "@afterpack/integration-utils";
2
+ import { Plugin } from "vite";
3
+
4
+ //#region src/index.d.ts
5
+ type ElectronLeg = "main" | "preload" | "renderer";
6
+ type AfterpackElectronOptions = AfterpackPluginOptions & {
7
+ projectRoot?: string;
8
+ };
9
+ declare function afterpackElectron(options: AfterpackElectronOptions & {
10
+ leg: ElectronLeg;
11
+ }): Plugin[];
12
+ declare function withAfterpack<T>(config: T, options?: AfterpackElectronOptions): T;
13
+ //#endregion
14
+ export { AfterpackElectronOptions, ElectronLeg, afterpackElectron, withAfterpack };
@@ -0,0 +1,14 @@
1
+ import { AfterpackPluginOptions } from "@afterpack/integration-utils";
2
+ import { Plugin } from "vite";
3
+
4
+ //#region src/index.d.ts
5
+ type ElectronLeg = "main" | "preload" | "renderer";
6
+ type AfterpackElectronOptions = AfterpackPluginOptions & {
7
+ projectRoot?: string;
8
+ };
9
+ declare function afterpackElectron(options: AfterpackElectronOptions & {
10
+ leg: ElectronLeg;
11
+ }): Plugin[];
12
+ declare function withAfterpack<T>(config: T, options?: AfterpackElectronOptions): T;
13
+ //#endregion
14
+ export { AfterpackElectronOptions, ElectronLeg, afterpackElectron, withAfterpack };
package/dist/index.js ADDED
@@ -0,0 +1,143 @@
1
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+ import { SEED_ENV_VAR, resolvePluginConfig } from "@afterpack/integration-utils";
4
+ import { afterpackVite } from "@afterpack/vite";
5
+
6
+ //#region src/notices.ts
7
+ const PACKAGER_CONFIGS = [
8
+ "electron-builder.yml",
9
+ "electron-builder.yaml",
10
+ "electron-builder.json",
11
+ "electron-builder.json5",
12
+ "electron-builder.toml",
13
+ "electron-builder.config.js",
14
+ "electron-builder.config.cjs",
15
+ "electron-builder.config.mjs",
16
+ "electron-builder.config.ts",
17
+ "forge.config.js",
18
+ "forge.config.cjs",
19
+ "forge.config.mjs",
20
+ "forge.config.ts"
21
+ ];
22
+ const NOTICE_STATE = Symbol.for("afterpack.electron.notices");
23
+ function sharedNoticeState() {
24
+ const holder = globalThis;
25
+ holder[NOTICE_STATE] ??= {
26
+ seenLegs: new Set(),
27
+ leakWarned: false,
28
+ advisoryArmed: false,
29
+ envSeedPinned: void 0
30
+ };
31
+ return holder[NOTICE_STATE];
32
+ }
33
+ const state = sharedNoticeState();
34
+ function recordEnvSeedPinned() {
35
+ state.envSeedPinned ??= process.env[SEED_ENV_VAR] != null;
36
+ }
37
+ function hasPackagerConfig(root) {
38
+ if (PACKAGER_CONFIGS.some((name) => existsSync(join(root, name)))) return true;
39
+ try {
40
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
41
+ return pkg.build != null || pkg.config?.forge != null;
42
+ } catch {
43
+ return false;
44
+ }
45
+ }
46
+ function warnPackagedTreeLeak(root, warn) {
47
+ if (state.leakWarned || !hasPackagerConfig(root)) return;
48
+ state.leakWarned = true;
49
+ warn("[afterpack-electron] this project has an Electron packager config. AfterPack's artifacts embed ORIGINAL SOURCE and are NOT excluded by default — add\n electron-builder: \"files\": [\"**/*\", \"!.afterpack/**\", \"!**/*.backup.*\", \"!**/*.map\"]\n electron-forge: packagerConfig.ignore: [/^\\/\\.afterpack/, /\\.backup\\./, /\\.map$/]\nor they ship inside app.asar.");
50
+ }
51
+ function recordLegBuilt(leg, seedPinned) {
52
+ state.seenLegs.add(leg);
53
+ if (state.advisoryArmed || seedPinned || state.envSeedPinned) return;
54
+ state.advisoryArmed = true;
55
+ process.on("exit", () => {
56
+ if (state.seenLegs.size > 1) return;
57
+ console.warn(`[afterpack-electron] only the "${[...state.seenLegs][0]}" leg was obfuscated in this process, so the other legs drew their own seeds. Set ${SEED_ENV_VAR}=git (or a pinned value) once in the shared build script so every leg shares one.`);
58
+ });
59
+ }
60
+
61
+ //#endregion
62
+ //#region src/index.ts
63
+ const BYTECODE_PLUGIN = "vite:bytecode";
64
+ const BYTECODE_EXT = /\.c?jsc$/;
65
+ function collectBytecodeChunks(dir, found = []) {
66
+ if (!existsSync(dir)) return found;
67
+ for (const name of readdirSync(dir)) {
68
+ const full = join(dir, name);
69
+ if (statSync(full).isDirectory()) collectBytecodeChunks(full, found);
70
+ else if (BYTECODE_EXT.test(name)) found.push(full);
71
+ }
72
+ return found;
73
+ }
74
+ function bytecodeRefusal(leg, what) {
75
+ return new Error(`[afterpack-electron:${leg}] ${what}. electron-vite's bytecodePlugin replaces every emitted chunk with a 3-line loader and ships the real application as V8 bytecode (.jsc), so AfterPack would obfuscate the loader and report success while the application itself went untouched. They cannot compose (bytecode replaces the chunk Rollup generated): drop bytecodePlugin, or drop AfterPack for this leg.`);
76
+ }
77
+ function guardPlugin(leg, seedPinned) {
78
+ let outDir = "";
79
+ return {
80
+ name: `afterpack-electron:${leg}`,
81
+ configResolved(config) {
82
+ outDir = resolve(config.root, config.build.outDir);
83
+ recordEnvSeedPinned();
84
+ if (config.plugins.some((p) => p.name === BYTECODE_PLUGIN)) throw bytecodeRefusal(leg, `${BYTECODE_PLUGIN} is enabled for this leg`);
85
+ warnPackagedTreeLeak(config.root, (m) => config.logger ? config.logger.warn(m) : console.warn(m));
86
+ },
87
+ closeBundle() {
88
+ const bytecode = collectBytecodeChunks(outDir);
89
+ if (bytecode.length > 0) throw bytecodeRefusal(leg, `${bytecode.length} V8 bytecode chunk(s) are in ${outDir}`);
90
+ recordLegBuilt(leg, seedPinned);
91
+ }
92
+ };
93
+ }
94
+ function afterpackElectron(options) {
95
+ const { leg,...rest } = options;
96
+ const resolvedSettings = resolvePluginConfig({
97
+ label: `afterpack-electron:${leg}`,
98
+ options: rest,
99
+ localKeys: ["projectRoot"]
100
+ }).options;
101
+ const artifacts = resolvedSettings.artifactOptions;
102
+ if (artifacts.build?.backup === true) throw new Error(`[afterpack-electron:${leg}] build.backup:true writes a .backup.<hash>.js holding the COMPLETE original source next to each output, inside the tree the packager copies into app.asar — every user would receive your source. Remove it.`);
103
+ if (artifacts.sourceMap?.enabled === true || artifacts.sourceMap?.emitUrl === true) console.warn(`[afterpack-electron:${leg}] source maps are enabled. A .map with sourcesContent inside app.asar is full deobfuscation — keep this to local debug builds, and exclude *.map from the packaged files.`);
104
+ const sharedSeedProjectRoot = rest.projectRoot ?? process.cwd();
105
+ const obfuscationPlugin = afterpackVite({
106
+ ...rest,
107
+ leg,
108
+ projectRoot: sharedSeedProjectRoot
109
+ });
110
+ const bytecodeAndSeedGuardPlugin = guardPlugin(leg, resolvedSettings.seed !== void 0);
111
+ return [obfuscationPlugin, bytecodeAndSeedGuardPlugin];
112
+ }
113
+ const LEGS = [
114
+ "main",
115
+ "preload",
116
+ "renderer"
117
+ ];
118
+ function injectLegs(config, options) {
119
+ const wired = [];
120
+ for (const leg of LEGS) {
121
+ const legConfig = config[leg];
122
+ if (!legConfig) continue;
123
+ legConfig.plugins = [...legConfig.plugins ?? [], afterpackElectron({
124
+ ...options,
125
+ leg
126
+ })];
127
+ wired.push(leg);
128
+ }
129
+ if (wired.length === 0) throw new Error("[afterpack-electron] withAfterpack() found no main/preload/renderer section on this config — it must wrap an electron-vite config, not a plain Vite one.");
130
+ console.log(`[afterpack-electron] wired into legs: ${wired.join(", ")}`);
131
+ return config;
132
+ }
133
+ function withAfterpack(config, options = {}) {
134
+ if (typeof config === "function") return (env) => {
135
+ const resolved = config(env);
136
+ return resolved instanceof Promise ? resolved.then((c) => injectLegs(c, options)) : injectLegs(resolved, options);
137
+ };
138
+ if (config instanceof Promise) return config.then((c) => injectLegs(c, options));
139
+ return injectLegs(config, options);
140
+ }
141
+
142
+ //#endregion
143
+ export { afterpackElectron, withAfterpack };
package/package.json ADDED
@@ -0,0 +1,80 @@
1
+ {
2
+ "name": "@afterpack/electron",
3
+ "version": "0.1.0-rc.20260925T1347",
4
+ "description": "Electron integration for AfterPack: obfuscate the main, preload and renderer bundles of an app with one seed",
5
+ "type": "module",
6
+ "main": "./dist/index.cjs",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ },
15
+ "require": {
16
+ "types": "./dist/index.d.cts",
17
+ "default": "./dist/index.cjs"
18
+ },
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "LICENSE",
24
+ "NOTICE",
25
+ "dist"
26
+ ],
27
+ "peerDependencies": {
28
+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
29
+ },
30
+ "dependencies": {
31
+ "@afterpack/integration-utils": "0.1.0-rc.20260925T1347",
32
+ "@afterpack/vite": "0.1.0-rc.20260925T1347"
33
+ },
34
+ "devDependencies": {
35
+ "@biomejs/biome": "2.4.4",
36
+ "@types/node": "^22.0.0",
37
+ "tsdown": "^0.11.0",
38
+ "typescript": "^5.0.0",
39
+ "vite": "^8.0.12",
40
+ "vitest": "^2.0.0"
41
+ },
42
+ "engines": {
43
+ "node": ">=18"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "repository": {
49
+ "type": "git",
50
+ "url": "https://github.com/afterpack-dev/afterpack.git",
51
+ "directory": "packages/electron"
52
+ },
53
+ "keywords": [
54
+ "obfuscator",
55
+ "javascript-obfuscator",
56
+ "obfuscation",
57
+ "code-protection",
58
+ "source-code-protection",
59
+ "javascript-security",
60
+ "anti-reverse-engineering",
61
+ "electron",
62
+ "electron-vite",
63
+ "electron-forge",
64
+ "afterpack"
65
+ ],
66
+ "author": "AfterPack (https://www.afterpack.dev)",
67
+ "license": "Apache-2.0",
68
+ "homepage": "https://www.afterpack.dev/docs/frameworks/electron",
69
+ "bugs": {
70
+ "url": "https://github.com/afterpack-dev/afterpack/issues"
71
+ },
72
+ "scripts": {
73
+ "build": "tsdown src/index.ts --format esm --format cjs --dts --shims",
74
+ "dev": "tsdown src/index.ts --format esm --format cjs --shims --watch",
75
+ "lint": "biome check .",
76
+ "lint:fix": "biome check --write .",
77
+ "typecheck": "tsc --noEmit",
78
+ "test": "vitest run"
79
+ }
80
+ }