cj-tauri 2.3.2 → 2.3.6

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.
@@ -0,0 +1,444 @@
1
+ /**
2
+ * `cj-tauri sign` 子命令:鸿蒙真机签名(体检 / 写回 / 登录 AGC / 全自动现签)。
3
+ *
4
+ * 用法:
5
+ * cj-tauri sign 签名体检:能不能装、缺什么、下一步是什么(离线,免账号)
6
+ * cj-tauri sign --apply 离线写回:把本机匹配 UDID+包名的现成材料写进
7
+ * targets/ohos/build-profile.json5(免账号)
8
+ * cj-tauri sign --login 浏览器登录 AGC 一次,令牌加密落盘(~/.cj-tauri/sign/)
9
+ * cj-tauri sign --auto [--newKeys] 全自动:注册设备 → 材料 → 证书 → profile → 写回
10
+ * cj-tauri sign --json 体检结果按 JSON 输出(机器可读)
11
+ *
12
+ * 在线部分仅 --login / --auto;--check / --apply 纯离线。
13
+ */
14
+
15
+ package cli
16
+
17
+ import std.collection.*
18
+ import std.fs.*
19
+ import std.process.*
20
+ import stdx.encoding.json.*
21
+
22
+ /** 有损 UTF-8:非法序列按 U+FFFD 替换(子进程输出解码用) */
23
+ func lenientUtf8(bytes: Array<Byte>): String {
24
+ let out = ArrayList<UInt8>()
25
+ var i: Int64 = 0
26
+ let n = Int64(bytes.size)
27
+ while (i < n) {
28
+ let b = Int64(bytes[i])
29
+ var need: Int64 = 0
30
+ var cp: Int64 = 0
31
+ if (b < 0x80) {
32
+ out.add(bytes[i])
33
+ i += 1
34
+ continue
35
+ } else if ((b & 0xE0) == 0xC0) {
36
+ need = 1
37
+ cp = b & 0x1F
38
+ } else if ((b & 0xF0) == 0xE0) {
39
+ need = 2
40
+ cp = b & 0x0F
41
+ } else if ((b & 0xF8) == 0xF0) {
42
+ need = 3
43
+ cp = b & 0x07
44
+ } else {
45
+ out.add(all: [0xEF, 0xBF, 0xBD])
46
+ i += 1
47
+ continue
48
+ }
49
+ if (i + need >= n) {
50
+ out.add(all: [0xEF, 0xBF, 0xBD])
51
+ i += 1
52
+ continue
53
+ }
54
+ var ok = true
55
+ var k: Int64 = 1
56
+ while (k <= need) {
57
+ let c = Int64(bytes[i + k])
58
+ if ((c & 0xC0) != 0x80) {
59
+ ok = false
60
+ break
61
+ }
62
+ cp = (cp << 6) | (c & 0x3F)
63
+ k += 1
64
+ }
65
+ if (!ok) {
66
+ out.add(all: [0xEF, 0xBF, 0xBD])
67
+ i += 1
68
+ continue
69
+ }
70
+ for (m in 0..(need + 1)) {
71
+ out.add(bytes[i + m])
72
+ }
73
+ i = i + need + 1
74
+ }
75
+ return String.fromUtf8(out.toArray())
76
+ }
77
+
78
+ /** 从工程目录收集签名体检/写回需要的事实 */
79
+ public class SignProjectInfo {
80
+ public var projectRoot: String = ""
81
+ public var bundleName: String = ""
82
+ public var product: String = "default"
83
+ public var buildProfile: String = ""
84
+ public var hdcPath: String = ""
85
+ public var error: String = ""
86
+ }
87
+
88
+ /**
89
+ * 定位鸿蒙工程的三要素:targets/ohos 目录、AppScope/app.json5 的 bundleName、
90
+ * build-profile.json5、hdc 可执行文件。找不到时带原因返回。
91
+ */
92
+ public func signCollectProject(projectRoot: String): SignProjectInfo {
93
+ let info = SignProjectInfo()
94
+ var root = projectRoot
95
+ if (root == "") {
96
+ root = "targets/ohos"
97
+ }
98
+ if (!exists(Path(root))) {
99
+ info.error = "鸿蒙工程目录不存在:${root}(先跑 `cj-tauri sync ohos` 派生骨架)"
100
+ return info
101
+ }
102
+ info.projectRoot = root
103
+ // bundleName
104
+ let appJson5 = "${root}/AppScope/app.json5"
105
+ if (!exists(Path(appJson5))) {
106
+ info.error = "找不到 ${appJson5}"
107
+ return info
108
+ }
109
+ let appText = String.fromUtf8(File.readFrom(appJson5))
110
+ info.bundleName = json5ValueAfter(appText, "bundleName")
111
+ if (info.bundleName == "") {
112
+ info.error = "${appJson5} 里读不到 bundleName"
113
+ return info
114
+ }
115
+ // build-profile.json5
116
+ let bp = "${root}/build-profile.json5"
117
+ if (!exists(Path(bp))) {
118
+ info.error = "找不到 ${bp}"
119
+ return info
120
+ }
121
+ info.buildProfile = bp
122
+ // product 名(读 products[].name,缺省 default)
123
+ let bpText = String.fromUtf8(File.readFrom(bp))
124
+ let prod = json5ValueAfter(bpText, "name")
125
+ if (prod != "" && prod != "default") {
126
+ info.product = prod
127
+ }
128
+ // hdc:环境变量 → PATH → DevEco 默认位置
129
+ info.hdcPath = signFirstExistingEnv(["HDC_PATH", "OHOS_HDC"])
130
+ if (info.hdcPath == "") {
131
+ let deveco = signFirstExistingEnv(["DEVECO_SDK_HOME", "OHOS_HOME", "DEVECO_HOME"])
132
+ var candidates = ArrayList<String>()
133
+ if (deveco != "") {
134
+ if (deveco.endsWith("openharmony") || deveco.contains("openharmony")) {
135
+ candidates.add("${deveco}/toolchains/hdc.exe")
136
+ candidates.add("${deveco}/toolchains/hdc")
137
+ }
138
+ candidates.add("${deveco}/default/openharmony/toolchains/hdc.exe")
139
+ candidates.add("${deveco}/default/openharmony/toolchains/hdc")
140
+ }
141
+ for (c in candidates) {
142
+ if (exists(Path(c))) {
143
+ info.hdcPath = c
144
+ break
145
+ }
146
+ }
147
+ }
148
+ if (info.hdcPath == "") {
149
+ // 交给 PATH(报错时提示怎么修)
150
+ info.hdcPath = "hdc"
151
+ }
152
+ return info
153
+ }
154
+
155
+ /** 签名体检:能不能装、缺什么、下一步(离线,免账号) */
156
+ public func cmdSignCheck(proj: SignProjectInfo, asJson: Bool): Int64 {
157
+ let udid = deviceUdidViaHdc(proj.hdcPath)
158
+ let configDir = ohosConfigDir()
159
+ let cands = discoverProfiles(configDir)
160
+ // 工程自己的配置
161
+ var hasConfig = false
162
+ var filesExist = false
163
+ var allowsDevice = false
164
+ var profileType = ""
165
+ var projProfileText = ""
166
+ if (proj.buildProfile != "" && exists(Path(proj.buildProfile))) {
167
+ let text = String.fromUtf8(File.readFrom(proj.buildProfile))
168
+ let s = parseProjSigning(text)
169
+ hasConfig = s.hasSigningConfigs
170
+ if (hasConfig) {
171
+ let m = signingMaterialOf(text)
172
+ filesExist = exists(Path(m.storeFile)) && exists(Path(m.profile)) &&
173
+ exists(Path(m.certpath))
174
+ if (exists(Path(m.profile))) {
175
+ try {
176
+ projProfileText = extractProfileJson(
177
+ signLatin1Of(File.readFrom(m.profile)))
178
+ } catch (e: Exception) {
179
+ let _ = e
180
+ }
181
+ let p = parseOhosProfile(projProfileText, m.profile)
182
+ profileType = p.profileType
183
+ allowsDevice = p.allows(udid)
184
+ }
185
+ }
186
+ }
187
+ let check = judgeSign(hasConfig, filesExist, allowsDevice, profileType, udid,
188
+ pickProfile(cands, udid, proj.bundleName).isSome())
189
+ // 包名门槛:仅在"需要走候选材料"的路径上叠判
190
+ if (!check.ok && (hasConfig == false || filesExist == false)) {
191
+ check.bundleMatch = false
192
+ for (p in cands) {
193
+ if (p.allows(udid) && bundleMatches(proj.bundleName, p.bundleName)) {
194
+ check.bundleMatch = true
195
+ break
196
+ }
197
+ }
198
+ if (!check.bundleMatch) {
199
+ let census = profileBundleCensus(cands, udid)
200
+ check.reason = "${check.reason};且本机没有「含本机 UDID 且包名为 ${proj.bundleName}」的材料"
201
+ check.nextStep = "跑 `cj-tauri sign --login` + `sign --auto` 为这个包名现签一份;" +
202
+ "本机现有材料:${census}"
203
+ }
204
+ }
205
+ if (asJson) {
206
+ var o = check.toJson()
207
+ o.put("bundleName", JsonString(proj.bundleName))
208
+ o.put("projectRoot", JsonString(proj.projectRoot))
209
+ println(o.toJsonString())
210
+ if (check.ok) {
211
+ return 0
212
+ }
213
+ return 1
214
+ }
215
+ println("[sign] 工程根: ${proj.projectRoot}")
216
+ println("[sign] 包名: ${proj.bundleName}")
217
+ println("[sign] 设备 UDID: ${if (udid == "") { "(取不到)" } else { udid }}")
218
+ println("[sign] 结论: ${if (check.ok) { "可直装" } else { "装不上" }}")
219
+ if (!check.ok) {
220
+ println("[sign] 原因: ${check.reason}")
221
+ }
222
+ println("[sign] 下一步: ${check.nextStep}")
223
+ if (check.ok) {
224
+ return 0
225
+ }
226
+ return 1
227
+ }
228
+
229
+ /** 离线写回:把本机匹配 UDID+包名的现成材料写进 build-profile.json5 */
230
+ public func cmdSignApply(proj: SignProjectInfo): Int64 {
231
+ let udid = deviceUdidViaHdc(proj.hdcPath)
232
+ let configDir = ohosConfigDir()
233
+ let cands = discoverProfiles(configDir)
234
+ match (pickProfile(cands, udid, proj.bundleName)) {
235
+ case Some(p) =>
236
+ let (p12, cer) = ("${p.p7bPath[0..(p.p7bPath.size - 4)]}.p12",
237
+ "${p.p7bPath[0..(p.p7bPath.size - 4)]}.cer")
238
+ if (!exists(Path(p12)) || !exists(Path(cer))) {
239
+ eprintln("[sign] 候选材料缺文件:${p12} / ${cer}")
240
+ return 1
241
+ }
242
+ // 口令密文优先取 donor 工程(同名 .p12 的工程)里现成的;没有就自己造
243
+ var storePwd = ""
244
+ var keyPwd = ""
245
+ // 1) 找 ~/.ohos/config 同目录 json5?没有这个约定 → 从 material/ 自己造不出来
246
+ // (明文口令只存在于生成它的那一次),所以这里只能沿用「已有工程写回过的密文」:
247
+ // 扫描本仓 examples/*/targets/ohos/build-profile.json5 找同一 .p12 的 donor。
248
+ let (dp12, dkey) = signScavengeDonorCiphertexts(p12)
249
+ if (dp12 != "" && dkey != "") {
250
+ storePwd = dp12
251
+ keyPwd = dkey
252
+ println("[sign] 沿用 donor 工程的口令密文(同一 .p12)")
253
+ } else {
254
+ let (workKey, wkErr) = loadWorkKey(materialDirOfConfig(configDir))
255
+ if (wkErr != "") {
256
+ eprintln("[sign] 读 material/ 失败:${wkErr}")
257
+ eprintln("[sign] 没有可沿用的口令密文,请跑 `cj-tauri sign --login` + `sign --auto` 生成一套新材料")
258
+ return 1
259
+ }
260
+ // 密文造不出来(明文口令不可知)→ 如实说明
261
+ let _ = workKey
262
+ eprintln("[sign] 候选材料的明文口令不可知(它只在生成那一次存在过),离线写回做不了")
263
+ eprintln("[sign] 请跑 `cj-tauri sign --login` + `cj-tauri sign --auto` 生成一套自己掌口令的新材料")
264
+ return 1
265
+ }
266
+ let m = SigningMaterial()
267
+ m.storeFile = p12
268
+ m.certpath = cer
269
+ m.profile = p.p7bPath
270
+ m.storePassword = storePwd
271
+ m.keyPassword = keyPwd
272
+ let origin = String.fromUtf8(File.readFrom(proj.buildProfile))
273
+ let (newText, err) = if (parseProjSigning(origin).hasSigningConfigs) {
274
+ replaceOwnSigningConfigs(origin, m)
275
+ } else {
276
+ applySigningConfig(origin, m)
277
+ }
278
+ if (err != "") {
279
+ eprintln("[sign] 写回失败:${err}")
280
+ return 1
281
+ }
282
+ let bak = "${proj.buildProfile}.cj-tauri-apply.bak"
283
+ File.writeTo(bak, origin.toArray())
284
+ File.writeTo(proj.buildProfile, newText.toArray())
285
+ println("[sign] 已写回 ${proj.buildProfile}(备份:${bak})")
286
+ println("[sign] profile: ${p.p7bPath}")
287
+ println("[sign] 下一步: hvigor assembleHap → hdc install -r → aa start")
288
+ return 0
289
+ case None =>
290
+ eprintln("[sign] 本机没有「含本机 UDID 且包名为 ${proj.bundleName}」的材料")
291
+ eprintln("[sign] 本机现有:${profileBundleCensus(cands, udid)}")
292
+ eprintln("[sign] 请跑 `cj-tauri sign --login` + `cj-tauri sign --auto` 为这个包名现签一份")
293
+ return 1
294
+ }
295
+ }
296
+
297
+ /**
298
+ * 扫描本仓 examples 下各工程 build-profile.json5,找与目标 .p12 **同名**的 donor,
299
+ * 搬它的口令密文(同一套材料 → 密文通用,搬家安全)。
300
+ */
301
+ func signScavengeDonorCiphertexts(targetP12: String): (String, String) {
302
+ let roots = [".", "..", "../..", "../../..", "../../../.."]
303
+ for (r in roots) {
304
+ let base = "${r}/examples"
305
+ if (!exists(Path(base))) {
306
+ continue
307
+ }
308
+ var entries: Array<FileInfo>
309
+ try {
310
+ entries = Directory.readFrom(Path(base))
311
+ } catch (e: Exception) {
312
+ let _ = e
313
+ continue
314
+ }
315
+ for (e in entries) {
316
+ if (!e.isDirectory()) {
317
+ continue
318
+ }
319
+ for (sub in ["targets/ohos", "."]) {
320
+ let bp = "${base}/${e.name}/${sub}/build-profile.json5"
321
+ if (!exists(Path(bp))) {
322
+ continue
323
+ }
324
+ try {
325
+ let text = String.fromUtf8(File.readFrom(bp))
326
+ let m = signingMaterialOf(text)
327
+ if (m.storePassword != "" && m.keyPassword != "" &&
328
+ sameMaterialFile(m.storeFile, targetP12)) {
329
+ return (m.storePassword, m.keyPassword)
330
+ }
331
+ } catch (ex: Exception) {
332
+ let _ = ex
333
+ }
334
+ }
335
+ }
336
+ }
337
+ return ("", "")
338
+ }
339
+
340
+ /** `sign` 子命令入口 */
341
+ public func cmdSign(args: Array<String>): Int64 {
342
+ var doLogin = false
343
+ var doAuto = false
344
+ var doApply = false
345
+ var asJson = false
346
+ var forceNewKeys = false
347
+ var projectRoot = ""
348
+ var i = 1
349
+ while (i < args.size) {
350
+ let a = args[i]
351
+ if (a == "--login") {
352
+ doLogin = true
353
+ } else if (a == "--auto") {
354
+ doAuto = true
355
+ } else if (a == "--apply") {
356
+ doApply = true
357
+ } else if (a == "--json") {
358
+ asJson = true
359
+ } else if (a == "--newKeys") {
360
+ forceNewKeys = true
361
+ } else if (a == "--path") {
362
+ if (i + 1 >= args.size) {
363
+ eprintln("用法: --path <ohos 工程目录>(缺省 targets/ohos)")
364
+ return 1
365
+ }
366
+ projectRoot = args[i + 1]
367
+ i = i + 2
368
+ continue
369
+ } else {
370
+ eprintln("未知选项: ${a}")
371
+ return 1
372
+ }
373
+ i += 1
374
+ }
375
+ let proj = signCollectProject(projectRoot)
376
+ if (proj.error != "") {
377
+ eprintln("[sign] ${proj.error}")
378
+ return 1
379
+ }
380
+ if (doLogin) {
381
+ let r = agcLogin(300, true)
382
+ if (!r.ok) {
383
+ eprintln("[sign] 登录失败:${r.error}")
384
+ return 1
385
+ }
386
+ println("[sign] 登录成功:${r.userName}(团队 ${r.teamCount} 个,默认 ${r.teamName})")
387
+ println("[sign] 令牌已加密落盘 ~/.cj-tauri/sign/token.enc(约 4 小时后过期)")
388
+ return 0
389
+ }
390
+ if (doAuto) {
391
+ var token: AgcLoginOutcome
392
+ match (loadAgcToken()) {
393
+ case Some(t) => token = t
394
+ case None =>
395
+ eprintln("[sign] 没有可用令牌(或已过期):先跑 `cj-tauri sign --login` 完成一次浏览器授权")
396
+ return 1
397
+ }
398
+ let inp = AutoSignInput()
399
+ inp.configDir = ohosConfigDir()
400
+ inp.projectRoot = proj.projectRoot
401
+ inp.bundleName = proj.bundleName
402
+ inp.buildProfile = proj.buildProfile
403
+ inp.product = proj.product
404
+ inp.forceNewKeys = forceNewKeys
405
+ // UDID 与设备类型
406
+ let udid = deviceUdidViaHdc(proj.hdcPath)
407
+ if (udid == "") {
408
+ eprintln("[sign] 拿不到设备 UDID(设备没连?)")
409
+ return 1
410
+ }
411
+ inp.udid = udid
412
+ try {
413
+ let (code, out, _) = executeWithOutput(proj.hdcPath,
414
+ ["shell", "getprop", "hw_sc.build.os.deviceType"])
415
+ if (code == 0) {
416
+ inp.deviceType = signDeviceTypeOf(lenientUtf8(out))
417
+ }
418
+ } catch (e: Exception) {
419
+ let _ = e
420
+ inp.deviceType = "4"
421
+ }
422
+ let outcome = autoSign(inp, token)
423
+ if (asJson) {
424
+ println(outcome.toJson().toJsonString())
425
+ } else {
426
+ for (s in outcome.steps) {
427
+ println("[sign] ${s}")
428
+ }
429
+ if (outcome.error != "") {
430
+ eprintln("[sign] 失败:${outcome.error}")
431
+ } else {
432
+ println("[sign] 完成。下一步: hvigor assembleHap → hdc install -r → aa start")
433
+ }
434
+ }
435
+ if (outcome.ok) {
436
+ return 0
437
+ }
438
+ return 1
439
+ }
440
+ if (doApply) {
441
+ return cmdSignApply(proj)
442
+ }
443
+ return cmdSignCheck(proj, asJson)
444
+ }