README-cn.md
1# Arkguard
2Arkguard 是Javascript和Typescript的源码混淆工具。
3
4# 在DevEco Studio中的用法
5Arkguard已经被集成了到SDK中。可以在DevEco Studio中很方便地使用。Arkguard只能用于Stage模型
6(不支持FA模型)。目前Arkguard只提供名称混淆的能力(因为其它混淆能力会劣化性能)。
7使用Arkguard可以混淆以下名称:
8* 参数名和局部变量名
9* 顶层作用域的名称
10* 属性名称
11
12Arkguard默认使能对参数名和局部变量名的混淆。顶层作用域名称和属性名称的混淆是默认关闭的,
13因为默认打开可能会导致运行时错误。你可以通过[混淆选项](#混淆选项)来开启它们。
14
15创建一个新工程的时候,配置文件`build-profile.json5`中会自动生成以下内容:
16```
17"arkOptions": {
18 "obfuscation": {
19 "ruleOptions": {
20 "enable": true,
21 "files": ["obfuscation-rules.txt"],
22 }
23 }
24}
25```
26创建一个新的library的时候,还会额外生成`consumerFiles`属性:
27```
28"arkOptions": {
29 "obfuscation": {
30 "ruleOptions": {
31 "enable": true,
32 "files": ["obfuscation-rules.txt"],
33 }
34 "consumerFiles": ["consumer-rules.txt"]
35 }
36}
37```
38
39要想开启混淆,需要满足下面的条件:
40* 属性`ruleOptions.enable`的值为`true`,并且所有依赖的library的`ruleOptions.enable`属性是`true`
41* 在release模式构建
42
43属性`ruleOptions.files`中指定的混淆配置文件会在构建HAP或HAR的时候被应用。
44
45属性`consumerFiles`中指定的混淆配置文件会在构建依赖这个library的工程或library时被应用。
46这些混淆配置文件的内容还会被合并到HAR包中的`obfuscation.txt`文件。
47
48当构建HAP或者HAR的时候,最终的混淆规则是自身的`ruleOptions.files`属性,依赖的library的`consumerFiles`属性,
49以及依赖的HAR包中的`obfuscation.txt`文件的合并。如果构建的是HAR,`obfuscation.txt`是自身的`consumerFiles`属性,
50依赖的library的`consumerFiles`属性,以及依赖的HAR包中的`obfuscation.txt`文件的合并。
51构建HAP不会生成`obfuscation.txt`。详细合并的策略可以查看[混淆规则合并策略](#混淆规则合并策略)。
52
53## 配置混淆规则
54在创建工程或library的时候,DevEco Studio会自动生成`obfuscation-rules.txt`和`consumer-rules.txt`文件,
55但是它们默认不会包含任何混淆规则。你可以在这些文件中写混淆规则,或者也可以将规则写在其它文件,
56然后将文件路径放到`ruleOptions.files`和`consumerFiles`中,如下面的例子所示。
57```
58"buildOption": {
59 "arkOptions": {
60 "obfuscation": {
61 "ruleOptions": {
62 "enable": true,
63 "files": ["obfuscation-rules.txt", "myrules.txt"],
64 }
65 "consumerFiles": ["consumer-rules.txt", "my-consumer-rules.txt"]
66 }
67 }
68}
69```
70
71在混淆规则文件中,你可以写[混淆选项](#混淆选项)和[保留选项](#保留选项)。
72
73### 混淆选项
74
75#### -disable-obfuscation
76
77关闭所有混淆。如果你使用这个选项,那么构建出来的HAP或HAR将不会被混淆。默认情况下,
78Arkguard只混淆参数名和局部变量名(通过将它们重新命名为随机的短名字)。
79
80#### -enable-property-obfuscation
81
82开启属性混淆。 如果你使用这个选项,那么所有的属性名都会被混淆,除了下面场景:
83* 被`import/export`直接导入或导出的类或对象的属性名不会被混淆。比如下面例子中的属性名`data`不会被混淆。
84 ```
85 export class MyClass {
86 data: string;
87 }
88 ```
89 对于间接导出的场景,比如`export MyClass`和`let a = MyClass; export {a};`,如果你不想混淆它们的属性名,那么你需要使用[保留选项](#保留选项)来保留这些属性名。另外,对于直接导出的类或对象的属性的属性名,比如下面例子中的`name`和`age`, 如果你不想混淆它们,那么你也需要使用[保留选项](#保留选项)来保留这些属性名。
90 ```
91 export class MyClass {
92 person = {name: "123", age: 100};
93 }
94 ```
95 如果想混淆直接导入/导出的名称,请参考[`-enable-export-obfuscation`](#-enable-export-obfuscation)选项。
96* ArkUI组件中的属性名不会被混淆。比如下面例子中的`message`和`data`不会被混淆。
97 ```
98 @Component struct MyExample {
99 @State message: string = "hello";
100 data: number[] = [];
101 ...
102 }
103 ```
104* 被[保留选项](#保留选项)指定的属性名不会被混淆。
105* 系统API列表中的属性名不会被混淆。系统API列表是构建时从SDK中自动提取出来的一个名称列表,其缓存文件为systemApiCache.json,路径为工程目录下build/cache/{...}/release/obfuscation中
106* 在Native API场景中,在so的d.ts文件中声明的API不会被混淆。
107* 字符串字面量属性名不会被混淆。比如下面例子中的`"name"`和`"age"`不会被混淆。
108 ```
109 let person = {"name": "abc"};
110 person["age"] = 22;
111 ```
112 如果你想混淆字符串字面量属性名,你需要在该选项的基础上再使用`-enable-string-property-obfuscation`选项。比如
113 ```
114 -enable-property-obfuscation
115 -enable-string-property-obfuscation
116 ```
117 **注意**:
118 **1.** 如果代码里面有字符串属性名包含特殊字符(除了`a-z, A-Z, 0-9, _`之外的字符),比如`let obj = {"\n": 123, "": 4, " ": 5}`,建议不要开启`-enable-string-property-obfuscation`选项,因为当不想混淆这些名字时,可能无法通过[保留选项](#保留选项)来指定保留这些名字。
119 **2.** 系统API的属性白名单中不包含声明文件中使用的字符串常量值,比如示例中的字符串'ohos.want.action.home'不被包含在属性白名单中
120 ```
121 // 系统API文件@ohos.app.ability.wantConstant片段:
122 export enum Params {
123 ACTION_HOME = 'ohos.want.action.home'
124 }
125 // 开发者源码示例:
126 let params = obj['ohos.want.action.home'];
127 ```
128 因此在开启了`-enable-string-property-obfuscation`选项时,如果想保留代码中使用的系统API字符串常量的属性不被混淆,比如obj['ohos.want.action.home'], 那么需要使用keep选项保留。
129
130#### -enable-toplevel-obfuscation
131
132开启顶层作用域名称混淆。如果你使用这个选项,那么所有的顶层作用域的名称都会被混淆,除了下面场景:
133* 被`import/export`的名称不会被混淆。
134* 当前文件找不到声明的名称不会被混淆。
135* 被[保留选项](#保留选项)指定的顶层作用域名称不会被混淆。
136* 系统API列表中的顶层作用域名称不会被混淆。
137
138#### -enable-filename-obfuscation
139
140开启文件/文件夹名称混淆。如果使用这个选项,那么所有的文件/文件夹名称都会被混淆,除了下面场景:
141* oh-package.json5文件中'main'、'types'字段配置的文件/文件夹名称不会被混淆。
142* 模块内module.json5文件中'srcEntry'字段配置的文件/文件夹名称不会被混淆。
143* 被[`-keep-file-name`](#保留选项)指定的文件/文件夹名称不会被混淆。
144* 非ECMAScript模块引用方式(ECMAScript模块示例:`import {foo} from './filename'`)
145* 非路径引用方式,比如例子中的json5不会被混淆 `import module from 'json5'`
146
147**注意**:
148**1.** 由于系统会在应用运行时加载某些指定的文件,针对这类文件,开发者需要手动在[`-keep-file-name`]选项中配置相应的白名单,防止指定文件被混淆,导致运行失败。
149上述需要手动配置白名单的情况,包括但不限于以下场景:
150(1) 当模块中包含Ability组件时。用户需要将`scr/main/module.json5`中,'abilities'字段下所有'srcEntry'对应的路径配置到白名单中。
151(2) 当模块中包含Worker多线程服务时,用户需要将`build-profiles.json5`中,'buildOption'-'sourceOption'-'workers'字段下所有的路径配置到白名单中。
152
153#### -enable-export-obfuscation
154
155开启直接导入或导出的类或对象的名称和属性名混淆。如果使用这个选项,那么模块中的直接导入或导出的名称都会被混淆,除了下面场景:
156* 远程HAR(真实路径在oh_modules中的包)中导出的类或对象的名称和属性名不会被混淆。
157* 被[保留选项](#保留选项)指定的名称与属性名不会被混淆。
158* 系统API列表中的名称不会被混淆。
159
160**注意**:
1611. 混淆导入或导出的类中属性名称需要同时开启`-enable-property-obfuscation`与`-enable-export-obfuscation`选项。
1622. 编译HSP时,如果开启`-enable-export-obfuscation`选项,需要在模块中的混淆配置文件`obfuscation-rules.txt`中保留对外暴露的接口。
1633. HAP/HSP/HAR依赖HSP场景下,编译时如果开启`-enable-export-obfuscation`选项,需要在模块中的混淆配置文件`obfuscation-rules.txt`中保留HSP导入的接口。
164
165 ```
166 // 代码示例(HSP中入口文件Index.ets):
167 export { add, customApiName } from './src/main/ets/utils/Calc'
168
169 // 保留接口名称配置示例:
170 // HSP以及依赖此HSP的模块中obfuscation-rules.txt文件配置:
171 keep-global-name
172 add
173 customApiName
174 ```
175
176#### -compact
177
178去除不必要的空格符和所有的换行符。如果使用这个选项,那么所有代码会被压缩到一行。
179**注意**:release模式构建的应用栈信息仅包含代码行号,不包含列号,因此compact功能开启后无法依据报错栈中的行号定位到源码具体位置。
180
181#### -remove-log
182
183删除以下场景中对 console.* 语句的调用,要求console.*语句返回值未被调用。
1841. 文件顶层的调用
1852. 代码块Block中的调用
1863. 模块Module中的调用
1874. switch语句中的调用
188
189#### `-print-namecache` filepath
190
191将名称缓存保存到指定的文件路径。名称缓存包含名称混淆前后的映射。
192注意:每次全量构建工程时都会生成新的namecache.json文件,因此您每次发布新版本时都要注意保存一个该文件的副本。
193
194#### `-apply-namecache` filepath
195
196复用指定的名称缓存文件。名字将会被混淆成缓存映射对应的名字,如果没有对应,将会被混淆成新的随机段名字。
197该选项应该在增量编译场景中被使用。
198
199默认情况下,DevEco Studio会在临时的缓存目录中保存缓存文件,并且在增量编译场景中自动应用该缓存文件。
200缓存目录:build/cache/{...}/release/obfuscation
201
202#### -remove-comments
203
204删除文件中的所有注释,包括单行、多行,及JsDoc注释。以下场景除外:
205声明文件中,在`-keep-comments`中配置的类、方法、struct、枚举等名称上方的JsDoc注释。
206**注意**:编译生成的源码文件中的注释默认会被全部删除,不支持配置保留。
207### 保留选项
208
209#### `-keep-property-name` [,identifiers,...]
210指定你想保留的属性名。比如下面的例子:
211```
212-keep-property-name
213age
214firstName
215lastName
216```
217**注意**:该选项在开启`-enable-property-obfuscation`时生效
218
219`-keep-comments`
220保留声明文件中元素上方的JsDoc注释。比如想保留声明文件中Human类上方的JsDoc注释,可进行以下配置:
221```
222-keep-comments
223Human
224```
225**注意**:
2261. 该选项在开启`-remove-comments`时生效
2272. 当声明文件中某个元素名称被混淆时,该元素上方的JsDoc注释无法通过`-keep-comments`保留。比如当在`-keep-comments`中配置了
228exportClass时,如果下面的类名被混淆,其JsDoc注释无法被保留:
229```
230/**
231** @class exportClass
232*/
233export class exportClass {}
234```
235
236**哪些属性名应该被保留?**
237
238为了保障混淆的正确性,我们建议你保留所有不通过点语法访问的属性。
239
240例子:
241```
242var obj = {x0: 0, x1: 0, x2: 0};
243for (var i = 0; i <= 2; i++) {
244 console.log(obj['x' + i]); // x0, x1, x2 应该被保留
245}
246
247Object.defineProperty(obj, 'y', {}); // y 应该被保留
248console.log(obj.y);
249
250obj.s = 0;
251let key = 's';
252console.log(obj[key]); // s 应该被保留
253
254obj.u = 0;
255console.log(obj.u); // u 可以被正确地混淆
256
257obj.t = 0;
258console.log(obj['t']); // 在开启字符串字面量属性名混淆时t和't'会被正确地混淆,但是我们建议保留
259
260obj['v'] = 0;
261console.log(obj['v']); // 在开启字符串字面量属性名混淆时'v'会被正确地混淆,但是我们建议保留
262```
263在Native API场景中,没有在so的d.ts文件中声明的API,如果要在ets/ts/js文件中使用需要手动保留。
264
265
266#### `-keep-global-name` [,identifiers,...]
267
268指定要保留的顶层作用域的名称。比如,
269```
270-keep-global-name
271Person
272printPersonName
273```
274
275**哪些顶层作用域的名称应该被保留?**
276
277在Javascript中全局变量是`globalThis`的属性。如果在代码中使用`globalThis`去访问全局变量,那么该变量名应该被保留。
278
279例子:
280```
281var a = 0;
282console.log(globalThis.a); // a 应该被保留
283
284function foo(){}
285globalThis.foo(); // foo 应该被保留
286
287var c = 0;
288console.log(c); // c 可以被正确地混淆
289
290function bar(){}
291bar(); // bar 可以被正确地混淆
292
293class MyClass {}
294let d = new MyClass(); // MyClass 可以被正确地混淆
295```
296
297#### `-keep-file-name` [,identifiers,...]
298
299指定要保留的文件/文件夹的名称(不需要写文件后缀)。比如,
300```
301-keep-file-name
302index
303entry
304```
305**哪些文件名应该被保留?**
306```
307const module1 = require('./file1') // ARKTs不支持CommonJS语法,这种路径引用应该被保留
308const moduleName = './file2'
309const module2 = import(moduleName) // 动态引用方式无法识别moduleName是否是路径,应该被保留
310```
311
312#### `-keep-dts` filepath
313
314保留指定路径的`.d.ts`文件中的名称。这里的文件路径可以是一个目录,这种情况下目录中所有`.d.ts`文件中的名称都会被保留。
315如果在构建HAR时使用了这个选项,那么文件中的名称会被合并到最后的`obfuscation.txt`文件中。
316
317#### `-keep` path
318保留指定路径中的所有名称(例如变量名、类名、属性名等)不被混淆。这个路径可以是文件与文件夹,若是文件夹,则文件夹下的文件及子文件夹中文件都不混淆。
319路径仅支持相对路径,`./`与`../`为相对于混淆配置文件所在目录。
320```
321-keep
322./src/main/ets/fileName.ts // fileName.ts中的名称不混淆
323../folder // folder目录下文件及子文件夹中的名称都不混淆
324../oh_modules/json5 // 引用的三方库json5里所有文件中的名称都不混淆
325```
326注:该功能不影响文件名混淆`-enable-filename-obfuscation`的功能
327
328### 保留选项支持通配符
329#### 名称类通配符
330以下保留选项支持配置名称类通配符:
331
332`-keep-property-name`
333
334`-keep-global-name`
335
336`-keep-file-name`
337
338`-keep-comments`
339
340名称类通配符使用方式如下:
341
342| 通配符 | 含义 | 示例 |
343| ------ | ---------------------- | ------------------------------------------ |
344| ? | 匹配任意单个字符 | "AB?"能匹配"ABC"等,但不能匹配"AB" |
345| \* | 匹配任意数量的任意字符 | "\*AB\*"能匹配"AB"、"aABb"、"cAB"、"ABc"等 |
346
347**使用示例**:
348
349保留所有以a开头的属性名称:
350```
351-keep-property-name
352a*
353```
354
355保留所有单个字符的属性名称:
356```
357-keep-property-name
358?
359```
360
361保留所有属性名称:
362```
363-keep-property-name
364*
365```
366
367
368#### 路径类通配符
369以下保留选项支持配置路径类通配符:
370
371`-keep`
372
373路径类通配符使用方式如下:
374
375| 通配符 | 含义 | 示例 |
376| ------ | ------------------------------------------------------------------------ | ------------------------------------------------- |
377| ? | 匹配任意单个字符,除了路径分隔符'/' | "../a?"能匹配"../ab"等,但不能匹配"../a/" |
378| \* | 匹配任意数量的任意字符,除了路径分隔符'/' | "../a*/c"能匹配"../ab/c",但不能匹配"../ab/d/s/c" |
379| \*\* | 匹配任意数量的任意字符 | "../a**/c"能匹配"../ab/c",也能匹配"../ab/d/s/c" |
380| ! | 表示非,只能写在某个路径最前端,用来排除用户配置的白名单中已有的某种情况 | "!../a/b/c.ets"表示除"../a/b/c.ets"以外 |
381
382**使用示例**:
383
384表示路径../a/b/中所有文件夹(不包含子文件夹)中的c.ets文件不会被混淆:
385```
386-keep
387../a/b/*/c.ets
388```
389
390表示路径../a/b/中所有文件夹(包含子文件夹)中的c.ets文件不会被混淆:
391```
392-keep
393../a/b/**/c.ets
394```
395
396表示路径../a/b/中,除了c.ets文件以外的其它文件都不会被混淆:
397```
398-keep
399../a/b/
400!../a/b/c.ets
401```
402
403无意义:
404```
405-keep
406!../a/b/c.ets
407```
408
409表示所有文件都不会被混淆:
410```
411-keep
412*
413```
414
415**注意**:
416
417(1)以上选项,不支持配置通配符'*'、'?'、'!'作其它含义使用。
418例如:
419```
420class A {
421 '*'= 1
422}
423
424-keep-property-name
425*
426```
427
428此时'\*'表示匹配任意数量的任意字符,配置效果为所有属性名称都不混淆,而不是只有'\*'属性不被混淆。
429
430(2)-keep选项中只允许使用'/'路径格式,不支持'\\'或'\\\\'。
431
432### 注释
433
434可以使用`#`在混淆规则文件中进行注释。每行以`#`开头的文本会被当做是注释,比如下面的例子:
435```
436# white list for MainAbility.ets
437-keep-global-name
438MyComponent
439GlobalFunction
440
441-keep-property-name # white list for dynamic property names
442firstName
443lastName
444age
445```
446构建HAR时,注释不会被合并到最后的`obfuscation.txt`文件中。
447
448### 混淆规则合并策略
449一个工程中经常会有许多混淆规则文件,这些文件来自于:
450* 主工程的`ruleOptions.files` (这里主工程我们指的是正在构建的工程)
451* 本地依赖的library中的`consumerFiles`选项中指定的文件
452* 远程依赖的HAR包中的`obfuscate.txt`文件
453
454当构建主工程的时候,这些文件中的混淆规则会按照下面的合并策略(伪代码)进行合并:
455```
456let `listRules` 表示上面提到的所有混淆规则文件的列表
457let finalRule = {
458 disableObfuscation: false,
459 enablePropertyObfuscation: false,
460 enableToplevelObfuscation: false,
461 compact: false,
462 removeLog: false,
463 keepPropertyName: [],
464 keepGlobalName: [],
465 keepDts: [],
466 printNamecache: string,
467 applyNamecache: string
468}
469for each file in `listRules`:
470 for each option in file:
471 switch(option) {
472 case -disable-obfuscation:
473 finalRule.disableObfuscation = true;
474 continue;
475 case -enable-property-obfuscation:
476 finalRule.enablePropertyObfuscation = true;
477 continue;
478 case -enable-toplevel-obfuscation:
479 finalRule.enableToplevelObfuscation = true;
480 continue;
481 case -compact:
482 finalRule.compact = true;
483 continue;
484 case -remove-log:
485 finalRule.removeLog = true;
486 continue;
487 case -print-namecache:
488 finalRule.printNamecache = #{指定的路径名};
489 continue;
490 case -apply-namecache:
491 finalRule.applyNamecache = #{指定的路径名};
492 continue;
493 case -keep-property-name:
494 finalRule.keepPropertyName.push(#{指定的名称});
495 continue;
496 case -keep-global-name:
497 finalRule.keepGlobalName.push(#{指定的名称});
498 continue;
499 case -keep-dts:
500 finalRule.keepDts.push(#{指定的路径});
501 continue;
502 }
503 end-for
504end-for
505```
506最后使用的混淆规则来自于对象`finalRule`。
507
508如果构建的是HAR,那么最终的`obfuscate.txt`文件内容来自于主工程和本地依赖的library的`consumerFiles`选项,
509以及依赖的HAR的`obfuscate.txt`文件的合并。合并策略和上面一样,除了以下的不同:
510* `-keep-dts`选项会被转换成`-keep-global-name`和`-keep-property-name`。
511* `-print-namecache`和`apply-namecache`选项会被忽略,不会出现在最后的`obfuscate.txt`文件中。
512
README.md
1# Arkguard
2Arkguard is a javascript and typescript obfuscation tool.
3For Chinese version please read [README-cn.md](README-cn.md)
4(中文版说明请查看[README-cn.md](README-cn.md)).
5
6# Usage in DevEco Studio
7Arkguard has been integrated into SDK. It is convenient to use Arkguard in DevEco Studio.
8In DevEco Studio, Arkguard can be enabled only in Stage Model (FA Model is not supported).
9For now only name obfuscations can be used in DevEco Studio (because other obfuscation
10abilities of Arkguard may hurt execution performance).
11You can obfuscate the following names:
12* parameter names and local variable names
13* names in global scope
14* property names
15
16We enable the obfuscation of parameter names and local variable names by default. However,
17global names obfuscation and property names obfuscation are disabled by default, as they may
18cause runtime error if they are enabled by default.
19You can enable them by [obfuscation options](#obfuscation-options).
20
21When you create a new project, the following config will be generated in `build-profile.json5`.
22```
23"arkOptions": {
24 "obfuscation": {
25 "ruleOptions": {
26 "enable": true,
27 "files": ["obfuscation-rules.txt"],
28 }
29 }
30}
31```
32When you create a new library, additional property `consumerFiles` will be added.
33```
34"arkOptions": {
35 "obfuscation": {
36 "ruleOptions": {
37 "enable": true,
38 "files": ["obfuscation-rules.txt"],
39 }
40 "consumerFiles": ["consumer-rules.txt"]
41 }
42}
43```
44
45To enable obfuscation, the following conditions should be satisfied:
46* the property `ruleOptions.enable` is `true` and the property `ruleOptions.enable` of every dependent library is `true`.
47* build in release mode
48
49The files in the property `ruleOptions.files` will be applied when you build HAP or HAR.
50
51The files in the property `consumerFiles` will be applied when you build the project or library which
52depends on this library. They will also be merged into a file `obfuscation.txt` in the resulting HAR.
53
54When you are building HAP or HAR, the final obfucation rules are combination of self's `ruleOptions.files`
55property, dependent libraries' `consumerFiles` properties and dependent HAR's `obfuscation.txt`.
56If you are building HAR, the content of `obfuscation.txt` is the combination of self's `consumerFiles` property,
57dependent libraries' `consumerFiles` properties and dependent HAR's `obfuscation.txt`. If you are building
58HAP, `obfuscation.txt` will not be generated. For more details, please jump to
59"[How Arkguard merges rules](#how-arkguard-merges-rules)".
60
61## Write rules
62
63The files `obfuscation-rules.txt` and `consumer-rules.txt` are created by DevEco Studio automatically, but they do not
64contain any rule by default. You can write rules in these files or include rules from other files, as the following
65example shows.
66```
67"buildOption": {
68 "arkOptions": {
69 "obfuscation": {
70 "ruleOptions": {
71 "enable": true,
72 "files": ["obfuscation-rules.txt", "myrules.txt"],
73 }
74 "consumerFiles": ["consumer-rules.txt", "my-consumer-rules.txt"]
75 }
76 }
77}
78```
79
80In rule files, you can write [obfuscation options](#obfuscation-options) and [keep options](#keep-options).
81
82### Obfuscation options
83
84#### -disable-obfuscation
85
86Specifies to disable all obfuscations. If you use this option, the resulting HAP or HAR will not be obfuscated. By default,
87Arkguard only obfuscates the parameter names and local variable names by assigning random short names to them.
88
89#### -enable-property-obfuscation
90
91Specifies to obfuscate the property names. If you use this option, all property names will be obfuscated except the
92following:
93* the property names of classes or objects directly imported or exported by `import/export` will be kept. For example, the property name `data` in
94 ```
95 export class MyClass {
96 data: string;
97 }
98 ```
99 will not be obfuscated.
100For 'indirectly export' cases such as `export MyClass` and `let a = MyClass; export {a};`, if you do not want to obfuscate
101their property names, you need to use [keep options](#keep-options) to keep them. Besides, for the property names of properties of directly exported classes or objects, like `name` and `age` in the following example, if you do not want to obfuscate them, then you also need [keep options](#keep-options) to keep them.
102 ```
103 export class MyClass {
104 person = {name: "123", age: 100};
105 }
106 ```
107 If you want to obfuscate import/export names, please refer to the [`-enable-export-obfuscation`](#-enable-export-obfuscation) option.
108* the property names defined in UI components. For example, the property names `message` and `data` in
109 ```
110 @Component struct MyExample {
111 @State message: string = "hello";
112 data: number[] = [];
113 ...
114 }
115 ```
116 will not be obfuscated.
117* the property names that are specified by [keep options](#keep-options).
118* the property names in system API list. System API list is a name set which is extracted from SDK automatically by default. The cache file is systemApiCache.json, and the path is build/cache/{...}/release/obfuscation in the module directory.
119* in the Native API scenario, the APIs in the d.ts file of so library will not be obfuscated.
120* the property names that are string literals. For example, the property names "name" and "age" in the following code will not be obfuscated.
121 ```
122 let person = {"name": "abc"};
123 person["age"] = 22;
124 ```
125 If you want to obfuscate these string literal property names, you should addtionally use the option `-enable-toplevel-obfuscation`. For example,
126 ```
127 -enable-property-obfuscation
128 -enable-string-property-obfuscation
129 ```
130 **Note**:
131 **1.** If there are string literal property names which contain special characters (that is, all characters except
132 `a-z, A-Z, 0-9, _`, for example `let obj = {"\n": 123, "": 4, " ": 5}` then we would not suggest to enable the
133 option `-enable-string-property-obfuscation`, because [keep options](#keep-options) may not allow to keep these
134 names when you do not want to obfuscate them.
135 **2.** The property white list of the system API does not include the string constant in the declaration file. For example, the string `'ohos.want.action.home'` in the example is not included in the white list.
136 ```
137 // System Api @ohos.app.ability.wantConstant snippet:
138 export enum Params {
139 DLP_PARAM_SANDBOX = 'ohos.dlp.param.sandbox'
140 }
141 // Developer source example:
142 let params = obj['ohos.want.action.home'];
143 ```
144 Therefore, when `-enable-string-property-obfuscation` is enabled, if you don't want to obfuscate the property like `'ohos.dlp.param.sandbox'`, which is a string constant in system api. you should keep it manually.
145
146Specifies to obfuscate the names in the global scope. If you use this option, all global names will be obfuscated
147except the following:
148* the `import/export` global names.
149* the global names that are not declared in the current file.
150* the global names that are specified by [keep options](#keep-options).
151* the global names in system API list.
152
153#### -enable-filename-obfuscation
154
155Specifies to obfuscate the file/folder names. If you use this option, all file/folder names will be obfuscated except the following:
156* the file/folder names configured in the 'main' and 'types' fields in the oh-package.json5.
157* the file/folder names configured in the 'srcEntry' field in the module.json5.
158* the file/folder names that are specified by [`-keep-file-name`](#keep-options).
159* non-ECMAScript module reference (ECMAScript module example: `import {foo} from './filename'`)
160* non-path reference, such as json5 will not be obfuscated `import module from 'json5'`
161**Note**:
162**1.** Due to the system loading certain specified files during application runtime, developers need to configure the corresponding white list manually in the [` keep file name `] option to prevent specified files from being confused and causing runtime failures.
163The above situations that require configure white list manually include but are not limited to the following scenarios:
164(1) When the module contains Ability component, you need to configure all paths corresponding to 'srcEntry' in the 'abilities' field in `scr/main/module.json5` to the white list.
165(2) When the module contains multithreading services: Worker, you need to configure all the paths in the field 'buildOption'-'sourceOption'-'workers' in `build-profiles.json5` to the white list.
166
167#### -enable-export-obfuscation
168
169Enable name and property name obfuscation for directly imported or exported classes or objects. If you use this option, the names of direct imports or exports in the module will be obfuscated, except in the following scenarios:
170* The names and property names of classes or objects exported in remote HAR (packages with real paths in oh_modules) will not be obfuscated.
171* Names and property names specified by [keep options](#keep-options) will not be obfuscated.
172* Names in the system API list will not be obfuscated.
173
174**Note**:
1751. To obfuscate the property names in imported or exported classes, you need to enable both the `-enable-property-obfuscation` and `-enable-export-obfuscation` options.
1762. When compiling HSP, if the `-enable-export-obfuscation` option is used, the externally exposed interfaces need to be kept in the obfuscation configuration file `obfuscation-rules.txt` in the module.
1773. In the scenario where HAP/HSP/HAR depends on HSP, if the `-enable-export-obfuscation` option is used during compilation, the interface imported from HSP needs to be kept in the obfuscation configuration file `obfuscation-rules.txt` in the module.
178
179 ```
180 // Code example (entry file Index.ets in HSP):
181 export { add, customApiName } from './src/main/ets/utils/Calc'
182
183 // Example of keeping interface name:
184 // obfuscation-rules.txt file configuration in HSP and modules that depend on this HSP:
185 keep-global-name
186 add
187 customApiName
188 ```
189
190#### -compact
191
192Specifies to remove unnecessary blank spaces and all line feeds. If you use this option, all code will be compressed into
193one line.
194**Note**: The stack information in release mode only includes the line number of code, not the column number. Therefore, when the compact is enabled, the specific location of the source code cannot be located based on the line number of stack information.
195
196#### -remove-log
197
198Delete the expressions involving direct calls to console.* statements in the following scenarios:
1991. Calls at the toplevel level of a file.
2002. Calls within a block.
2013. Calls within a module.
2024. Calls within a switch statement.
203and the return value of console.* should not be called
204
205#### `-print-namecache` filepath
206
207Specifies to print the name cache that contains the mapping from the old names to new names.
208Note: The namecache.json file will be generated every time the module is fully built, so you should save a copy each time you publish a new version.
209
210#### `-apply-namecache` filepath
211
212Specifies to reuse the given cache file. The old names in the cache will receive the corresponding new names specified in
213the cache. Other names will receive new random short names. This option should be used in incremental obfuscation.
214
215By default, DevEco Studio will keep and update the namecache file in the temporary cache directory and apply the cache for
216incremental compilation.
217Cache directory: build/cache/{...}/release/obfuscation
218
219#### -remove-comments
220
221Remove all comments including single line, multi line and JsDoc comments, in a project except:
222* Those names of JsDoc comments above class, function, struct, enum ... in declaration files are in `-keep-comments`.
223**Note**: `-keep-comments` doesn't work for comments in generated source files, which will be deleted.
224### Keep options
225
226#### `-keep-property-name` [,identifiers,...]
227
228Specifies property names that you want to keep. For example,
229```
230-keep-property-name
231age
232firstName
233lastName
234```
235**Note**: This option is avaliable when `-enable-property-obfuscation` is enabled.
236
237`-keep-comments`
238To retain JsDoc comments above elements in declaration files, such as preserving the JsDoc comment above the Human class,
239you can make the following configuration:
240```
241-keep-comments
242Human
243```
244**Note**:
2451. This option is avaliable when `-remove-comments` is enabled.
2462. If the name of an element is obfuscated, the JsDoc comments
247above that element cannot be kept using `-keep-comments`. For example, when you have exportClass in `-keep-comments`,
248you should make sure that the following class will not be obfuscated, or the JsDoc comments above the class will still be removed:
249```
250/**
251** @class exportClass
252*/
253export class exportClass {}
254```
255
256**What property names should be kept?**
257
258For safety, we would suggest keeping all property names that are not accessed through dot syntax.
259
260Example:
261```
262var obj = {x0: 0, x1: 0, x2: 0};
263for (var i = 0; i <= 2; i++) {
264 console.log(obj['x' + i]); // x0, x1, x2 should be kept
265}
266
267Object.defineProperty(obj, 'y', {}); // y should be kept
268console.log(obj.y);
269
270obj.s = 0;
271let key = 's';
272console.log(obj[key]); // s should be kept
273
274obj.u = 0;
275console.log(obj.u); // u can be safely obfuscated
276
277obj.t = 0;
278console.log(obj['t']); // t and 't' can be safely obfuscated when `-enable-string-property-obfuscation`, but we suggest keeping t
279
280obj['v'] = 0;
281console.log(obj['v']); // 'v' can be safely obfuscated when `-enable-string-property-obfuscation`, but we suggest keeping v
282```
283In the native API scenario, if in the ets/ts/js file you want to use APIs that are not declared in d.ts file, you need to keep these APIs.
284
285#### `-keep-global-name` [,identifiers,...]
286
287Specifies names that you want to keep in the global scope. For example,
288```
289-keep-global-name
290Person
291printPersonName
292```
293
294**What global names should be kept?**
295
296It is known that in javascript the variables in the global scope are properties of `globalThis`. So if in your code
297you access a global variable as a property, then the global name should be kept.
298
299Example:
300```
301var a = 0;
302console.log(globalThis.a); // a should be kept
303
304function foo(){}
305globalThis.foo(); // foo should be kept
306
307var c = 0;
308console.log(c); // c can be safely obfuscated
309
310function bar(){}
311bar(); // bar can be safely obfuscated
312
313class MyClass {}
314let d = new MyClass(); // MyClass can be safely obfuscated
315```
316
317#### `-keep-file-name` [,identifiers,...]
318
319Specify the name of files/folders to keep (no need to write the file suffix). for example,
320```
321-keep-file-name
322index
323entry
324```
325**What file names should be kept?**
326```
327const module1 = require('./file1') // ARKTs doesn't support CommonJS, this path reference should be kept.
328const moduleName = './file2'
329const module2 = import(moduleName) // dynamic reference cannot identify whether moduleName is a path and should be retained.
330```
331
332#### `-keep-dts` filepath
333
334Specifies to keep names in the given `.d.ts` file. Here filepath can be also a directory. If so, then the names in all
335`d.ts` files under the given directory will be kept.
336If your are building HAR with this option, then the kept names will be merged into the resulting `obfuscation.txt`.
337
338#### `-keep` path
339Names(such as variable names, class names, property names, etc.) in the specified path are not obfuscated. This path can be a file or a folder. If it is a folder, the files in the folder and the files in subfolders will not be obfuscated.
340The path only supports relative paths, `./` and `../` are relative to the directory where the obfuscation configuration file is located.
341```
342-keep
343./src/main/ets/fileName.ts // The names in fileName.ts are not obfusated.
344../folder // The names of files and subfolders in the folder directory are not obfusated.
345../oh_modules/json5 // The names of all files in the referenced library json5 are not obfusated.
346```
347Note: This option does not affect the function of file name obfuscation `-enable-filename-obfuscation`
348
349### Keep options support wildcards
350#### Wildcards for name categories
351The following options support configuring wildcards for name categories:<br>
352`-keep-property-name`<br>
353`-keep-global-name`<br>
354`-keep-file-name`<br>
355`-keep-comments`<br>
356
357The usage of name categories wildcards is as follows:
358
359| Wildcard | Meaning | Example |
360| -------- | ------------------------------------ | -------------------------------------------------- |
361| ? | Matches any single character | "AB?" can match "ABC", etc., but cannot match "AB" |
362| \* | Matches any number of any characters | "*AB*" can match "AB", "aABb", "cAB", "ABc", etc. |
363
364**Examples**:
365
366Retains all property names starting with 'a':
367```
368-keep-property-name
369a*
370```
371
372Retains all single-character property names:
373```
374-keep-property-name
375?
376```
377
378Retains all property names:
379
380```
381-keep-property-name
382*
383```
384
385
386#### Wildcards for path categories
387The following options support configuring wildcards for path categories:
388
389`-keep`
390
391The usage of path categories wildcards is as follows:
392
393| Wildcard | Meaning | Example |
394| -------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
395| ? | Matches any single character except path separator '/' | "../a?" can match "../ab", etc., but cannot match "../a/" |
396| \* | Matches any number of any characters except path separator '/' | "../a*/c" can match "../ab/c", but cannot match "../ab/d/s/c" |
397| \*\* | Matches any number of any characters | "../a**/c" can match "../ab/c", and also "../ab/d/s/c" |
398| ! | Represents negation and can only be written at the beginning of a path to exclude certain cases that already exist in the user-configured whitelist | "!../a/b/c.ets" means except "../a/b/c.ets" |
399
400**Examples**:
401
402Indicates that the c.ets files in all folders in ../a/b/ (excluding subfolders) will not be obfuscated:
403```
404-keep
405../a/b/*/c.ets
406```
407
408Indicates that the c.ets files in all folders in ../a/b/ (including subfolders) will not be obfuscated:
409```
410-keep
411../a/b/**/c.ets
412```
413
414Indicates that except for the c.ets file, all other files in ../a/b/ will not be obfuscated:
415
416```
417-keep
418../a/b/
419!../a/b/c.ets
420```
421
422Meaningless:
423
424```
425-keep
426!../a/b/c.ets
427```
428
429Indicates that all files will not be obfuscated:
430
431```
432-keep
433*
434```
435
436**Note**:
437
438(1)The above options do not support configuring wildcards '*', '?', '!' for other meanings.
439
440For example:
441```
442class A {
443 '*'= 1
444}
445-keep-property-name
446*
447```
448
449It becomes ineffective when you only want to retain the '\*' property.
450
451Here, \* indicates matching any number of any characters, resulting in all property names not being obfuscated, rather than only '\*' not being obfuscated.
452
453(2) The -keep option only allows the use of '/' as the path separator and does not support '\\' or '\\\\'.
454
455### Comments
456
457You can write comments in obfuscation rule file by using `#`. The line begins with `#` is treated as comment.
458For example,
459```
460# white list for MainAbility.ets
461-keep-global-name
462MyComponent
463GlobalFunction
464
465-keep-property-name # white list for dynamic property names
466firstName
467lastName
468age
469```
470If your are building HAR, comments will not be merged into the resulting `obfuscation.txt`.
471
472### How Arkguard merges rules
473Typically there may be serveral rule files in your project. These rule files come from:
474* `ruleOptions.files` in main project (Here by main project we mean the project you are building)
475* `consumerFiles` in local dependent libraries
476* `obfuscate.txt` in remote dependent HARs
477When building your main project, all these rules will be merged by the following strategy (in pseudo code):
478```
479let `listRules` be the list of all rule files that are mentioned above.
480let finalRule = {
481 disableObfuscation: false,
482 enablePropertyObfuscation: false,
483 enableToplevelObfuscation: false,
484 compact: false,
485 removeLog: false,
486 keepPropertyName: [],
487 keepGlobalName: [],
488 keepDts: [],
489 printNamecache: string,
490 applyNamecache: string
491}
492for each file in `listRules`:
493 for each option in file:
494 switch(option) {
495 case -disable-obfuscation:
496 finalRule.disableObfuscation = true;
497 continue;
498 case -enable-property-obfuscation:
499 finalRule.enablePropertyObfuscation = true;
500 continue;
501 case -enable-toplevel-obfuscation:
502 finalRule.enableToplevelObfuscation = true;
503 continue;
504 case -compact:
505 finalRule.compact = true;
506 continue;
507 case -remove-log:
508 finalRule.removeLog = true;
509 continue;
510 case -print-namecache:
511 finalRule.printNamecache = #{specified path};
512 continue;
513 case -apply-namecache:
514 finalRule.applyNamecache = #{specified path};
515 continue;
516 case -keep-property-name:
517 finalRule.keepPropertyName.push(#{specified names});
518 continue;
519 case -keep-global-name:
520 finalRule.keepGlobalName.push(#{specified names});
521 continue;
522 case -keep-dts:
523 finalRule.keepDts.push(#{specified file path});
524 continue;
525 }
526 end-for
527end-for
528```
529The final obfuscation rules are in the object `finalRule`.
530
531If you are building HAR, the resulting `obfuscate.txt` are obtained by merging the rules from `consumerFiles` in main
532project and local dependent libraries, and `obfuscate.txt` in remote dependent HARs. The merging strategy is the same
533except:
534* The `-keep-dts` option will be converted to `-keep-global-name` and `-keep-property-name` options in the resulting
535`obfuscate.txt`.
536* The options `-print-namecache` and `apply-namecache` will be omitted and will not appear in the resulting
537`obfuscate.txt`.
538