cj-tauri 2.1.1 → 2.1.3

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/README.md CHANGED
@@ -6,11 +6,12 @@ Tauri's trio to Cangjie: a Cangjie backend (statically compiled) plus a system W
6
6
  (`invoke` / `resolve` / `event`), and a capability-based security model (capability allowlists).
7
7
 
8
8
  - Repository and full documentation: <https://github.com/yangyongzhen/cj-tauri>
9
- - Current version: **2.1.1** (fixed in this release: sync now keeps the launcher on the framework path
10
- the business package declares (no more cjpm module conflicts after editing the path), the desktop
11
- launcher locates assets/ two levels up so it runs straight from targets/, and new **serial command
12
- groups** — `TauriApp.registerSerial` — execute same-group commands strictly in arrival order, which
13
- ai-chat's web-tab commands now use; plus the hello-world example and starter guide)
9
+ - Current version: **2.1.3** (new in this release: `scripts/winbuild.sh` now pairs the Windows stdx
10
+ package with the installed `cjc` — a mismatched pair compiles and links fine but aborts at startup,
11
+ and under a GUI subsystem it leaves **no log at all** — plus the `cookie-export` round of Windows
12
+ fixes: `USERPROFILE` fallback for the home directory, an empty cookie filter that reads the whole
13
+ store instead of matching `about:blank`, a borrowed `ICoreWebView2CookieList` that was being
14
+ released, and a cookie reply buffer too small to stay valid JSON)
14
15
  - Current status: **Windows (WebView2), Linux (WebKitGTK) and HarmonyOS PC (ArkWeb) all run on real
15
16
  hardware**; on the HarmonyOS side the menu capability bit and `fs` / `mqtt` / `redis` / `sqlite` /
16
17
  `store` / `http` have been verified on a device
@@ -165,6 +166,40 @@ Known limitation: the first `dev` / `build` builds the C bridge into the **frame
165
166
  (that's where the app's `cjpm.toml` link options point), so the package install directory must be writable;
166
167
  if you installed under a read-only path, run from inside the repository instead.
167
168
 
169
+ ## Changes in 2.1.3
170
+
171
+ - **Windows single-file builds use the cjc-matched stdx**: `scripts/winbuild.sh` defaulted to the
172
+ `1.0.5.1` Windows stdx while `cjc` was `1.2.0`. That pair builds, links and ships, but the app
173
+ aborts at startup — and with `--subsystem=windows` stderr is not connected, so double-clicking a
174
+ broken exe produced **no log whatsoever**. The default now points at the matched package
175
+ (log line `[winbuild] cjc 1.2.0 + windows stdx 1.2.0.1`) and a guard refuses to build when the
176
+ major/minor versions differ.
177
+ - `examples/cookie-export` Windows fixes: `homeDir()` falls back to `USERPROFILE` (and only wins when
178
+ the directory really exists), an empty cookie filter reads the whole store instead of matching the
179
+ `about:blank` URL, the borrowed `ICoreWebView2CookieList` is no longer released (it crashed the
180
+ WebView2 process with `0xc0000005`), and the cookie reply buffer is large enough to stay valid JSON.
181
+
182
+ For the full list see `[2.1.3] - 2026-11-06` in the repository's `CHANGELOG.md`.
183
+
184
+ ## Changes in 2.1.2
185
+
186
+ - **Native CookieManager bridge**: `WebViewHost.cookiesJson(filter)` (C side `cj_bridge_get_cookies`)
187
+ returns the whole cookie store as `{"ok":true,"cookies":[…]}` — `webkit_cookie_manager_get_all_cookies`
188
+ on Linux, `ICoreWebView2_2::getCookieManager` + `GetCookies` on Windows. Embedded page views share the
189
+ host's WebKit context / WebView2 environment, so **httpOnly** session cookies (`z_c0`, `sessionid`,
190
+ `UserToken`) are readable — the ones `document.cookie` can never see. Blocking on the outside,
191
+ asynchronous on the inside: the platform layer posts the read to the UI thread and the caller waits
192
+ with a timeout, reporting `ok=false` with a reason instead of hanging.
193
+ - New `examples/cookie-export` app: embedded login for 5 platforms (CSDN / Zhihu / Juejin / OSChina /
194
+ Baijiahao), field validation against cspub's hard requirements, and export in both formats
195
+ (`~/.cspub/config.json` merged — other platforms' keys are preserved — plus `~/.cspub/cookie_<platform>`
196
+ at mode 600). Ships with 8 unit tests covering bridge-reply parsing, domain filtering, header assembly,
197
+ required-field checks and the merge-write.
198
+ - **Fixed** the `GLib-GObject-CRITICAL: g_object_unref: assertion 'G_IS_OBJECT (object)' failed` printed
199
+ on every bridge round-trip on Linux: `on_js_done` used the deprecated `webkit_web_view_run_javascript`,
200
+ whose finished result must not be unreffed as a `GObject` on WebKitGTK 2.52. Switched to
201
+ `evaluate_javascript` (`JSCValue`, transfer full) — warning gone, bridge builds warning-free.
202
+
168
203
  ## Changes in 2.1.1
169
204
 
170
205
  - **Serial command groups** (issue #6-4): `IpcHub.registerSerial(cmd, handler, group)` /
@@ -185,7 +220,7 @@ if you installed under a read-only path, run from inside the repository instead.
185
220
  - New `examples/hello-world` (smallest runnable app, generated by this CLI) and
186
221
  `docs/hello-world-入门教程.md` — a starter guide written from an actual npx-create-to-window run.
187
222
 
188
- For the full list see `[2.1.1] - 2026-10-26` in the repository's `CHANGELOG.md`.
223
+ For the full list see `[2.1.2] - 2026-11-05` in the repository's `CHANGELOG.md`.
189
224
 
190
225
  ## Changes in 2.1.0
191
226
 
package/cjpm.toml CHANGED
@@ -2,7 +2,7 @@
2
2
  cjc-version = "1.0.5"
3
3
  name = "cjTauri"
4
4
  description = "仓颉版 Tauri:轻量跨端混合开发框架(WebView 宿主 + IPC 桥 + 能力安全模型)"
5
- version = "2.1.1"
5
+ version = "2.1.3"
6
6
  target-dir = ""
7
7
  output-type = "static"
8
8
  compile-option = ""
package/cli/cjpm.toml CHANGED
@@ -2,7 +2,7 @@
2
2
  cjc-version = "1.0.5"
3
3
  name = "cli"
4
4
  description = "cj-tauri CLI:脚手架 create / dev / build / run / info"
5
- version = "2.1.1"
5
+ version = "2.1.3"
6
6
  target-dir = ""
7
7
  output-type = "executable"
8
8
  compile-option = ""
@@ -10,7 +10,7 @@ import std.collection.*
10
10
 
11
11
  /** CLI 版本:须与 cli/cjpm.toml 的 version、CHANGELOG 顶部版本一致(scripts/check-version.sh 校验) */
12
12
  func cliVersion(): String {
13
- return "2.1.1"
13
+ return "2.1.3"
14
14
  }
15
15
 
16
16
  /** 一次命令所需的路径上下文 */
package/cli/src/sync.cj CHANGED
@@ -397,7 +397,7 @@ func readBizFrameworkPath(): Option<String> {
397
397
  if (b == 10) { // '\n':行结束,处理这一行
398
398
  let hit = pathFromCjTauriLine(line)
399
399
  if (let Some(p) <- hit) {
400
- return Some(absolutizeBizPath(p))
400
+ return bizFrameworkPathOf(p)
401
401
  }
402
402
  line.clear()
403
403
  } else if (b != 13) { // 跳过 '\r'
@@ -407,11 +407,82 @@ func readBizFrameworkPath(): Option<String> {
407
407
  // 文件无结尾换行时的最后一行
408
408
  let last = pathFromCjTauriLine(line)
409
409
  if (let Some(p) <- last) {
410
- return Some(absolutizeBizPath(p))
410
+ return bizFrameworkPathOf(p)
411
411
  }
412
412
  return None
413
413
  }
414
414
 
415
+ /**
416
+ * 业务包声明的框架路径 → 可用框架根(issue #7)。
417
+ * lingqu 0.13.1+ 起 `cjpm.toml` 依赖写 `path = "${CJ_TAURI_ROOT}"`——cjpm 对
418
+ * dependencies.path 与 link-option 都会展开环境变量,但 sync 这里先前拿到的是
419
+ * **字面量**(`${CJ_TAURI_ROOT}` 拼进 cwd 变成不存在的目录),导致 sync 必挂而
420
+ * 构建正常。修法:
421
+ * ① `${VAR}` 形式 → 用 std.env.getVariable 展开(未定义的变量保留原样);
422
+ * ② 绝对化后路径不存在 → 回退 resolveFrameworkRoot()(CJ_TAURI_ROOT / 仓内定位),
423
+ * 与「读不到声明回 None」的旧行为一致——字面量不是声明,别拿它继续走。
424
+ */
425
+ func bizFrameworkPathOf(p: String): Option<String> {
426
+ let expanded = expandVarPlaceholders(p)
427
+ let abs = absolutizeBizPath(expanded)
428
+ if (exists(Path(abs))) {
429
+ return Some(abs)
430
+ }
431
+ return resolveFrameworkRoot()
432
+ }
433
+
434
+ /**
435
+ * 把字符串里的 `${VAR}` 逐个展开为环境变量值;未定义的变量保留原样(可诊断)。
436
+ *
437
+ * **只认 `${VAR}`,不认 `$VAR`——这是有意与 cjpm 对齐**:实测 cjpm 对
438
+ * `path = "$CJ_TAURI_ROOT"` 直接报 `the path '$CJ_TAURI_ROOT' … does not exist`,
439
+ * 若 sync 单独支持无花括号形式,反而会造成「sync 过了、`cjpm build` 挂」的分裂。
440
+ *
441
+ * 全程按**字节**收集、最后一次 `fromUtf8`:把每个字节单独 `String.fromUtf8([b])` 会在
442
+ * 多字节 UTF-8 上炸(实测 `path = "/tmp/框架本体"` → `IllegalArgumentException: Invalid
443
+ * utf8 byte sequence`,中文路径的 workspace 直接跑不了 sync)——汉字是 3 字节,逐字节
444
+ * 转字符串每段都不是合法序列。展开值同理按其字节拼回。
445
+ */
446
+ func expandVarPlaceholders(p: String): String {
447
+ let bytes = p.toArray()
448
+ let n = bytes.size
449
+ let out = ArrayList<Byte>()
450
+ var i = 0
451
+ while (i < n) {
452
+ // '${'(0x24 0x7B)开头 → 读到 '}'(0x7D)
453
+ if (bytes[i] == 36 && i + 1 < n && bytes[i + 1] == 123) {
454
+ var j = i + 2
455
+ let name = ArrayList<Byte>()
456
+ var closed = false
457
+ while (j < n) {
458
+ if (bytes[j] == 125) { // '}'
459
+ closed = true
460
+ break
461
+ }
462
+ name.add(bytes[j])
463
+ j += 1
464
+ }
465
+ if (closed && name.size > 0) {
466
+ let varName = String.fromUtf8(name.toArray())
467
+ // 未定义时保留的原文形如 ${VAR}——"$" 与 "{" 分开拼,避免字面量
468
+ // "${" 被当成插值起始符(没有配对 "}" 就报 unterminated)
469
+ let orig = "$" + "{" + varName + "}"
470
+ for (b in valueOfVar(varName, orig)) {
471
+ out.add(b)
472
+ }
473
+ i = j + 1
474
+ } else {
475
+ out.add(bytes[i])
476
+ i += 1
477
+ }
478
+ } else {
479
+ out.add(bytes[i])
480
+ i += 1
481
+ }
482
+ }
483
+ return String.fromUtf8(out.toArray())
484
+ }
485
+
415
486
  /** 行里含 "cjTauri" 时,取首个引号对之间的内容(模板生成的行即 ` cjTauri = { path = "..." }`,
416
487
  第一个引号就是路径值的开头);不含或内容为空回 None */
417
488
  func pathFromCjTauriLine(line: ArrayList<Byte>): Option<String> {
@@ -466,19 +537,45 @@ func bytesFind(data: ArrayList<Byte>, pat: Array<Byte>, from: Int64): Int64 {
466
537
  }
467
538
 
468
539
  /** 业务包 toml 里的相对路径以业务包根(= sync 的 cwd)为基准绝对化;
469
- launcher 在 targets/desktop 下,相对基准不同,不能直接抄 */
540
+ launcher 在 targets/desktop 下,相对基准不同,不能直接抄。
541
+
542
+ 绝对路径的三种写法都要认——只判 `/` 开头会把 Windows 盘符当相对路径拼成
543
+ `<cwd>/D:/…`,于是 `create` 产物声明的框架(`toTomlPath` 写出的正是 `D:/…`)
544
+ 永远被判不存在、只能靠 `resolveFrameworkRoot()` 回退;回退捡到另一份框架副本
545
+ 就是 issue #6 那个「两份副本 → cjpm 模块冲突」:
546
+ ① `/` 开头(POSIX);
547
+ ② `X:/` 或 `X:\`(Windows 盘符,大小写都算);
548
+ ③ `//` 或两个反斜杠开头(UNC 共享路径)。 */
470
549
  func absolutizeBizPath(p: String): String {
471
- var first: UInt8 = 0
472
- for (b in p) {
473
- first = b
474
- break
550
+ let b = p.toArray()
551
+ let n = b.size
552
+ if (n > 0 && b[0] == 47) { // '/'
553
+ return p
475
554
  }
476
- if (first == 47) { // '/' 开头已是绝对路径
555
+ // 'X:' + 分隔符 —— 盘符绝对路径
556
+ if (n >= 3 && isAsciiLetter(b[0]) && b[1] == 58 && (b[2] == 47 || b[2] == 92)) {
557
+ return p
558
+ }
559
+ // 两个相同分隔符开头 —— UNC(Linux 上 '//x' 也是绝对路径,判成绝对同样正确)
560
+ if (n >= 2 && (b[0] == 47 || b[0] == 92) && b[0] == b[1]) {
477
561
  return p
478
562
  }
479
563
  return currentDir() + "/" + p
480
564
  }
481
565
 
566
+ /** ASCII 字母——盘符只可能是 A-Z / a-z,别用字符字面量(本仓只用字节常量) */
567
+ func isAsciiLetter(c: UInt8): Bool {
568
+ return (c >= 65 && c <= 90) || (c >= 97 && c <= 122)
569
+ }
570
+
571
+ /** 环境变量取值,未定义回原样(保留 ${VAR} 原文,好诊断)——case 块里只放 return */
572
+ func valueOfVar(name: String, orig: String): String {
573
+ match (getVariable(name)) {
574
+ case Some(v) => return v
575
+ case None => return orig
576
+ }
577
+ }
578
+
482
579
  // ---------- ohos 骨架(批次 3-PR3,RFC §7.3) ----------
483
580
 
484
581
  /** 能力清单文件名单:[capabilities] 目录下 .json 的 basename(sync 生成与 check 漂移共用) */
@@ -1191,6 +1191,32 @@ void cj_core_dialog_tick(cj_host *h, dlg_req *req) {
1191
1191
  cj_plat_sync_unlock(h->dlg_lock);
1192
1192
  }
1193
1193
 
1194
+ /* =========================================================================
1195
+ * Cookie 读取:core 只做入口校验与日志,投递 / 等待 / 解析全在平台层
1196
+ *
1197
+ * 为什么不在 core 建状态机(对比 dialog):dialog 是模态单槽,必须由 core 串行化;
1198
+ * cookie 读取是只读快照,可以并发,平台各自把请求包在栈上结构里即可,core 不持状态。
1199
+ * ========================================================================= */
1200
+
1201
+ char *cj_bridge_get_cookies(cj_host *h, const char *filter) {
1202
+ char *json;
1203
+ if (!h || !h->ready) {
1204
+ cj_logf("[cj-bridge] get_cookies ignored: host not ready\n");
1205
+ return cj_strdup("{\"ok\":false,\"error\":\"host not ready\"}");
1206
+ }
1207
+ json = cj_plat_get_cookies(h, filter ? filter : "");
1208
+ if (!json) {
1209
+ return cj_strdup("{\"ok\":false,\"error\":\"platform returned null\"}");
1210
+ }
1211
+ cj_logf("[cj-bridge] get_cookies: filter=%s -> %d bytes\n",
1212
+ (filter && *filter) ? filter : "(all)", (int)strlen(json));
1213
+ return json;
1214
+ }
1215
+
1216
+ void cj_bridge_cookies_free(char *s) {
1217
+ free(s);
1218
+ }
1219
+
1194
1220
  /* =========================================================================
1195
1221
  * 串口(plugin_serial):路径白名单 + 参数校验 + 导出转发
1196
1222
  *
@@ -297,6 +297,14 @@ void cj_plat_view_set_bounds(cj_host *h, long long view, int x, int y, int w, in
297
297
  void cj_plat_view_navigate(cj_host *h, long long view, const char *url);
298
298
  void cj_plat_view_destroy(cj_host *h, long long view);
299
299
 
300
+ /* ---- Cookie 读取(「一键导出登录态」类工具)----
301
+ 阻塞式:平台把请求投到宿主 UI 线程发起异步读(Linux = webkit_cookie_manager_get_all_cookies,
302
+ Windows = ICoreWebView2CookieManager::GetCookies),拿到结果后回填并唤醒调用方。
303
+ 返回 malloc 的 JSON(**调用方 free**),失败也返回 JSON。filter = 域名后缀,空串 = 全部。
304
+ 平台必须在 UI 线程退出/窗口先关时也唤醒等待方(否则 worker 线程永远吊在条件变量上):
305
+ 等待方自带超时,但别指望它——超时只是最后一道防线。 */
306
+ char *cj_plat_get_cookies(cj_host *h, const char *filter);
307
+
300
308
  /* 宿主能力位(CJ_CAP_* 的按位或):纯静态事实,cj_plat_init 里由平台给出。 */
301
309
  int cj_plat_host_capabilities(cj_host *h);
302
310
 
@@ -446,6 +454,20 @@ CJ_BRIDGE_API void cj_bridge_set_dialog_callback(cj_host *h, cj_on_dialog_fn cb)
446
454
  CJ_BRIDGE_API int cj_bridge_show_dialog(cj_host *h, int kind, const char *title,
447
455
  const char *message, const char *filter);
448
456
 
457
+ /* ===== Cookie 读取(「一键导出各平台登录态」类工具用)=====
458
+ 从宿主 WebView 的 cookie 仓库整份读出,**含 httpOnly**——这正是它相对
459
+ document.cookie 的全部意义:各平台的会话令牌(知乎 z_c0 / 掘金 sessionid …)
460
+ 基本都带 httpOnly,注入 JS 读 document.cookie 拿不到它们。
461
+ filter 是域名后缀(如 "csdn.net";空串 / NULL = 全部)。
462
+ 返回 malloc 的 JSON,**调用方负责 free**;失败也返回 JSON({"ok":false,"error":…})。
463
+ 线程口径:请在命令 worker 线程调用(内部投 UI 线程发起异步读 + 带超时等待);
464
+ 调用方已站在 UI 线程时直接返回错误 JSON——等待的事件得由 UI 线程处理,阻塞即自死锁。 */
465
+ CJ_BRIDGE_API char *cj_bridge_get_cookies(cj_host *h, const char *filter);
466
+
467
+ /* 释放 cj_bridge_get_cookies 返回的缓冲(NULL 安全,幂等)。失败结果也是 malloc 的 JSON,
468
+ 同样要走这里。 */
469
+ CJ_BRIDGE_API void cj_bridge_cookies_free(char *s);
470
+
449
471
  /* 菜单栏:wire 是 MenuModel.toWire() 的线路文本(空串 = 移除菜单栏)。
450
472
  未 start 时只记下、建窗时生效;start 之后调用=运行期换菜单(平台投到 UI 线程重建)。 */
451
473
  CJ_BRIDGE_API void cj_bridge_set_menu(cj_host *h, const char *wire);
@@ -370,13 +370,18 @@ void cj_plat_wake_ui(cj_host *h) {
370
370
  /* ===== 平台原语:投递 / 运行时操作 ===== */
371
371
 
372
372
  /* 回投结果校验:这条 eval 是「仓颉 → 前端」的唯一出口,静默失败会让前端 promise 永久 pending。
373
- Windows 侧有 log_hr("ExecuteScript", …) 兜同一件事(两平台对称)。 */
373
+ Windows 侧有 log_hr("ExecuteScript", …) 兜同一件事(两平台对称)。
374
+
375
+ 用 evaluate_javascript 而不是弃用的 run_javascript:后者的 finish 返回 WebKitJavascriptResult,
376
+ 在本机 WebKitGTK 2.52 上对它 g_object_unref 会触发 G_IS_OBJECT 断言失败(gdb 栈:
377
+ on_js_done → g_log → g_logv),每条命令刷一条 GLib-CRITICAL。新 API 返回 JSCValue(transfer full),
378
+ 所有权语义明确,顺带消掉编译期的 deprecated 警告。world_name / source_uri 传 NULL = 用页面主世界。 */
374
379
  static void on_js_done(GObject *src, GAsyncResult *res, gpointer ud) {
375
380
  GError *err = NULL;
376
- WebKitJavascriptResult *r =
377
- webkit_web_view_run_javascript_finish(WEBKIT_WEB_VIEW(src), res, &err);
381
+ JSCValue *r =
382
+ webkit_web_view_evaluate_javascript_finish(WEBKIT_WEB_VIEW(src), res, &err);
378
383
  if (r) {
379
- g_object_unref(r); /* 每次回投都会新建一个结果对象,不看也要释放 */
384
+ g_object_unref(r); /* 每次回投都会新建一个结果值,不看也要释放 */
380
385
  }
381
386
  if (err) {
382
387
  fprintf(stderr, "[cj-bridge] run js failed: %s\n", err->message);
@@ -387,7 +392,8 @@ static void on_js_done(GObject *src, GAsyncResult *res, gpointer ud) {
387
392
  void cj_plat_post_js(cj_host *h, const char *script_utf8) {
388
393
  plat_host *p = h ? (plat_host *)h->plat : NULL;
389
394
  if (!p || !p->view || !script_utf8) return;
390
- webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(p->view), script_utf8, NULL, on_js_done, NULL);
395
+ webkit_web_view_evaluate_javascript(WEBKIT_WEB_VIEW(p->view), script_utf8, -1, NULL, NULL, NULL,
396
+ on_js_done, NULL);
391
397
  }
392
398
 
393
399
  void cj_plat_open_devtools(cj_host *h) {
@@ -1612,6 +1618,242 @@ void cj_plat_view_destroy(cj_host *h, long long view) {
1612
1618
  view_post(h, CJ_VIEW_OP_DESTROY, view, 0, 0, 0, 0, 0, NULL);
1613
1619
  }
1614
1620
 
1621
+ /* =========================================================================
1622
+ * Cookie 读取(「一键导出各平台登录态」类工具)
1623
+ *
1624
+ * 形态:命令 worker 线程调 cj_plat_get_cookies → 投 GTK 线程 → webkit 异步读 cookie store
1625
+ * → 回调序列化成 JSON → 唤醒等待方(带 5s 超时)。
1626
+ *
1627
+ * 为什么必须走原生(而不是注入 JS 读 document.cookie):httpOnly。知乎 z_c0、掘金 sessionid
1628
+ * 这类会话令牌都带 httpOnly,JS 侧看不见——导出一个「字段齐全但发文 401」的文件比导不出来
1629
+ * 更难查。cookie store 才是全量快照。
1630
+ *
1631
+ * 为什么不用 core 的 cj_sync:那套谓词等待没有超时,窗口在等待期间销毁时 worker 会永远吊在
1632
+ * 条件变量上;这里自带 pthread mutex + cond + timedwait,超时后放弃等待(结构交给回调回收)。
1633
+ * ========================================================================= */
1634
+
1635
+ typedef struct cookie_call {
1636
+ cj_host *h;
1637
+ char *filter; /* 域名后缀;空串 = 全部 */
1638
+ char *json; /* 结果 JSON(GTK 线程 malloc,等待方取走后自己 free)*/
1639
+ int ready;
1640
+ int abandoned; /* 等待方已超时放弃:结构由异步回调自己回收 */
1641
+ pthread_mutex_t mtx;
1642
+ pthread_cond_t cond;
1643
+ } cookie_call;
1644
+
1645
+ /* JSON 字符串转义:只处理 JSON 必需的字符,>=0x20 的字节原样输出
1646
+ (cookie 值多是 ASCII;UTF-8 多字节序列逐字节拷贝不会被破坏)*/
1647
+ static void cookie_json_escaped(GString *out, const char *s) {
1648
+ const unsigned char *p = (const unsigned char *)(s ? s : "");
1649
+ g_string_append_c(out, '"');
1650
+ for (; *p; p++) {
1651
+ switch (*p) {
1652
+ case '"': g_string_append(out, "\\\""); break;
1653
+ case '\\': g_string_append(out, "\\\\"); break;
1654
+ case '\n': g_string_append(out, "\\n"); break;
1655
+ case '\r': g_string_append(out, "\\r"); break;
1656
+ case '\t': g_string_append(out, "\\t"); break;
1657
+ default:
1658
+ if (*p < 0x20) {
1659
+ g_string_append_printf(out, "\\u%04x", (unsigned)*p);
1660
+ } else {
1661
+ g_string_append_c(out, (char)*p);
1662
+ }
1663
+ }
1664
+ }
1665
+ g_string_append_c(out, '"');
1666
+ }
1667
+
1668
+ /* filter 为空 → 全收;否则按域名后缀匹配(".csdn.net" 命中 "csdn.net")*/
1669
+ static int cookie_domain_matches(const char *domain, const char *filter) {
1670
+ size_t dl, fl;
1671
+ if (!filter || !*filter) return 1;
1672
+ if (!domain) return 0;
1673
+ dl = strlen(domain);
1674
+ fl = strlen(filter);
1675
+ if (dl < fl) return 0;
1676
+ if (g_ascii_strncasecmp(domain + dl - fl, filter, fl) != 0) return 0;
1677
+ return dl == fl || domain[dl - fl - 1] == '.';
1678
+ }
1679
+
1680
+ static void cookie_call_free(cookie_call *c) {
1681
+ if (!c) return;
1682
+ free(c->filter);
1683
+ free(c->json);
1684
+ pthread_mutex_destroy(&c->mtx);
1685
+ pthread_cond_destroy(&c->cond);
1686
+ free(c);
1687
+ }
1688
+
1689
+ /* 释放 get_all_cookies_finish 给的 GList:元素是 SoupCookie(普通结构体,不是 GObject),
1690
+ 逐个 soup_cookie_free 再 g_list_free。不用 g_list_free_full 是为了让释放路径显式可读,
1691
+ 也避免 GDestroyNotify 的函数指针强转在严格编译选项下被质疑。*/
1692
+ static void cookie_list_free(GList *list) {
1693
+ GList *it;
1694
+ for (it = list; it; it = it->next) {
1695
+ if (it->data) soup_cookie_free((SoupCookie *)it->data);
1696
+ }
1697
+ g_list_free(list);
1698
+ }
1699
+
1700
+ /* 结果回填:等待方还在就交出去;已超时放弃就由这里回收结构 */
1701
+ static void cookie_call_set_result(cookie_call *c, char *json) {
1702
+ int abandon;
1703
+ pthread_mutex_lock(&c->mtx);
1704
+ abandon = c->abandoned;
1705
+ if (!abandon) {
1706
+ c->json = json;
1707
+ c->ready = 1;
1708
+ pthread_cond_signal(&c->cond);
1709
+ }
1710
+ pthread_mutex_unlock(&c->mtx);
1711
+ if (abandon) {
1712
+ free(json);
1713
+ cookie_call_free(c);
1714
+ }
1715
+ }
1716
+
1717
+ static void cookie_call_set_error(cookie_call *c, const char *msg) {
1718
+ GString *s = g_string_new("{\"ok\":false,\"error\":");
1719
+ cookie_json_escaped(s, msg);
1720
+ g_string_append_c(s, '}');
1721
+ cookie_call_set_result(c, g_string_free(s, FALSE));
1722
+ }
1723
+
1724
+ /* webkit 异步读完成(GTK 线程)*/
1725
+ static void on_all_cookies(GObject *src, GAsyncResult *res, gpointer ud) {
1726
+ cookie_call *c = (cookie_call *)ud;
1727
+ GError *err = NULL;
1728
+ GList *list;
1729
+ GList *it;
1730
+ GString *out;
1731
+ int n = 0;
1732
+ int first = 1;
1733
+
1734
+ list = webkit_cookie_manager_get_all_cookies_finish(WEBKIT_COOKIE_MANAGER(src), res, &err);
1735
+ if (err) {
1736
+ GString *msg = g_string_new("cookie store read failed: ");
1737
+ g_string_append(msg, err->message ? err->message : "unknown");
1738
+ cookie_call_set_error(c, msg->str);
1739
+ g_string_free(msg, TRUE);
1740
+ g_error_free(err);
1741
+ cookie_list_free(list);
1742
+ return;
1743
+ }
1744
+
1745
+ /* 先数一遍匹配项(JSON 里的 count 得写准;cookie 数量级很小,两遍遍历无所谓)*/
1746
+ for (it = list; it; it = it->next) {
1747
+ SoupCookie *ck = (SoupCookie *)it->data;
1748
+ if (ck && cookie_domain_matches(soup_cookie_get_domain(ck), c->filter)) n++;
1749
+ }
1750
+
1751
+ out = g_string_new("");
1752
+ g_string_append_printf(out, "{\"ok\":true,\"count\":%d,\"cookies\":[", n);
1753
+ for (it = list; it; it = it->next) {
1754
+ SoupCookie *ck = (SoupCookie *)it->data;
1755
+ GDateTime *exp;
1756
+ if (!ck || !cookie_domain_matches(soup_cookie_get_domain(ck), c->filter)) continue;
1757
+ if (!first) g_string_append_c(out, ',');
1758
+ first = 0;
1759
+ g_string_append(out, "{\"name\":");
1760
+ cookie_json_escaped(out, soup_cookie_get_name(ck));
1761
+ g_string_append(out, ",\"value\":");
1762
+ cookie_json_escaped(out, soup_cookie_get_value(ck));
1763
+ g_string_append(out, ",\"domain\":");
1764
+ cookie_json_escaped(out, soup_cookie_get_domain(ck));
1765
+ g_string_append(out, ",\"path\":");
1766
+ cookie_json_escaped(out, soup_cookie_get_path(ck));
1767
+ g_string_append_printf(out, ",\"secure\":%s,\"httpOnly\":%s",
1768
+ soup_cookie_get_secure(ck) ? "true" : "false",
1769
+ soup_cookie_get_http_only(ck) ? "true" : "false");
1770
+ exp = soup_cookie_get_expires(ck);
1771
+ if (exp) {
1772
+ g_string_append_printf(out, ",\"expires\":%" G_GINT64_FORMAT,
1773
+ (gint64)g_date_time_to_unix(exp));
1774
+ } else {
1775
+ g_string_append(out, ",\"expires\":0,\"session\":true");
1776
+ }
1777
+ g_string_append_c(out, '}');
1778
+ }
1779
+ g_string_append(out, "]}");
1780
+
1781
+ cookie_list_free(list);
1782
+ cookie_call_set_result(c, g_string_free(out, FALSE));
1783
+ }
1784
+
1785
+ /* GTK 线程:发起异步读 */
1786
+ static gboolean cookie_idle(gpointer ud) {
1787
+ cookie_call *c = (cookie_call *)ud;
1788
+ plat_host *p = (c && c->h) ? (plat_host *)c->h->plat : NULL;
1789
+ WebKitWebView *wv;
1790
+ WebKitWebContext *ctx;
1791
+
1792
+ if (!p || !p->view) {
1793
+ cookie_call_set_error(c, "webview not ready");
1794
+ return G_SOURCE_REMOVE;
1795
+ }
1796
+ wv = WEBKIT_WEB_VIEW(p->view);
1797
+ ctx = webkit_web_view_get_context(wv);
1798
+ if (!ctx) {
1799
+ cookie_call_set_error(c, "web context unavailable");
1800
+ return G_SOURCE_REMOVE;
1801
+ }
1802
+ webkit_cookie_manager_get_all_cookies(
1803
+ webkit_web_context_get_cookie_manager(ctx), NULL, on_all_cookies, c);
1804
+ return G_SOURCE_REMOVE;
1805
+ }
1806
+
1807
+ char *cj_plat_get_cookies(cj_host *h, const char *filter) {
1808
+ plat_host *p = h ? (plat_host *)h->plat : NULL;
1809
+ cookie_call *c;
1810
+ struct timespec ts;
1811
+ char *json = NULL;
1812
+
1813
+ if (!p || !p->view) {
1814
+ return strdup("{\"ok\":false,\"error\":\"webview not ready\"}");
1815
+ }
1816
+ if (cj_plat_is_ui_thread(h)) {
1817
+ /* 等待的事件得由 UI 线程处理:站在这里阻塞 = 自己把自己锁死 */
1818
+ return strdup("{\"ok\":false,\"error\":\"get_cookies must be called from a worker thread\"}");
1819
+ }
1820
+
1821
+ c = (cookie_call *)calloc(1, sizeof(*c));
1822
+ if (!c) return strdup("{\"ok\":false,\"error\":\"out of memory\"}");
1823
+ c->h = h;
1824
+ c->filter = strdup(filter ? filter : "");
1825
+ if (!c->filter) {
1826
+ free(c);
1827
+ return strdup("{\"ok\":false,\"error\":\"out of memory\"}");
1828
+ }
1829
+ pthread_mutex_init(&c->mtx, NULL);
1830
+ pthread_cond_init(&c->cond, NULL);
1831
+
1832
+ if (!g_idle_add(cookie_idle, c)) {
1833
+ cookie_call_free(c);
1834
+ return strdup("{\"ok\":false,\"error\":\"ui thread unavailable\"}");
1835
+ }
1836
+
1837
+ pthread_mutex_lock(&c->mtx);
1838
+ clock_gettime(CLOCK_REALTIME, &ts);
1839
+ ts.tv_sec += 5;
1840
+ while (!c->ready) {
1841
+ if (pthread_cond_timedwait(&c->cond, &c->mtx, &ts) == ETIMEDOUT) break;
1842
+ }
1843
+ if (c->ready) {
1844
+ json = c->json;
1845
+ c->json = NULL;
1846
+ pthread_mutex_unlock(&c->mtx);
1847
+ cookie_call_free(c);
1848
+ } else {
1849
+ /* 超时:放弃等待但**不能**释放结构——异步回调可能还在路上,交给它回收 */
1850
+ c->abandoned = 1;
1851
+ pthread_mutex_unlock(&c->mtx);
1852
+ json = strdup("{\"ok\":false,\"error\":\"timeout waiting for cookie store\"}");
1853
+ }
1854
+ return json;
1855
+ }
1856
+
1615
1857
  /* 最小化到托盘这里只**记一条策略**(并复位提醒位):真正的拦截发生在用户按下最小化的那一刻
1616
1858
  (window-state-event),此刻窗口层没有可做的事——与 Windows 侧同形。 */
1617
1859
  void cj_plat_set_minimize_to_tray(cj_host *h, int enabled) {
@@ -1077,6 +1077,404 @@ int cj_plat_post_ui(cj_host *h, cj_ui_fn fn, void *ud) {
1077
1077
  return 1;
1078
1078
  }
1079
1079
 
1080
+ /* =========================================================================
1081
+ * Cookie 读取(「一键导出各平台登录态」类工具)
1082
+ *
1083
+ * 为什么必须走原生:httpOnly。知乎 z_c0、掘金 sessionid 这类会话令牌都带 httpOnly,
1084
+ * 注入 JS 读 document.cookie 拿不到——导出「字段看着齐全、发文却 401」的文件比导不出来更难查。
1085
+ * WebView2 的 ICoreWebView2CookieManager::GetCookies 给的是全量快照(含 httpOnly 属性)。
1086
+ *
1087
+ * 形态与 Linux 侧同形:worker 线程 → 投 UI 线程 → 异步读 → 回填 JSON → 唤醒(带 5s 超时)。
1088
+ * GetCookies 按 uri 匹配 cookie 域,所以 filter 拼成 https://<filter>/;空 filter 传**空 uri**
1089
+ * (SDK 契约:uri 为空串/空指针时返回同 profile 下全部 cookie),不按 uri 过滤。
1090
+ * ========================================================================= */
1091
+
1092
+ typedef struct cookie_call {
1093
+ cj_host *h;
1094
+ char *filter;
1095
+ char *json;
1096
+ int ready;
1097
+ int abandoned; /* 等待方已超时放弃:结构由异步回调自己回收 */
1098
+ CRITICAL_SECTION cs;
1099
+ CONDITION_VARIABLE cv;
1100
+ } cookie_call;
1101
+
1102
+ /* 极简动态字符串:Windows 侧没有 glib,为几段 JSON 引一个库不值当 */
1103
+ typedef struct cookie_sbuf {
1104
+ char *p;
1105
+ size_t len;
1106
+ size_t cap;
1107
+ } cookie_sbuf;
1108
+
1109
+ static int cookie_sb_add(cookie_sbuf *b, const char *s, size_t n) {
1110
+ if (b->len + n + 1 > b->cap) {
1111
+ size_t cap = b->cap ? b->cap : 1024;
1112
+ char *np;
1113
+ while (cap < b->len + n + 1) cap *= 2;
1114
+ np = (char *)realloc(b->p, cap);
1115
+ if (!np) return 0;
1116
+ b->p = np;
1117
+ b->cap = cap;
1118
+ }
1119
+ memcpy(b->p + b->len, s, n);
1120
+ b->len += n;
1121
+ b->p[b->len] = '\0';
1122
+ return 1;
1123
+ }
1124
+
1125
+ static int cookie_sb_puts(cookie_sbuf *b, const char *s) {
1126
+ return cookie_sb_add(b, s ? s : "", s ? strlen(s) : 0);
1127
+ }
1128
+
1129
+ /* JSON 转义写入(>=0x20 的字节原样输出,UTF-8 多字节序列不会被破坏)*/
1130
+ static int cookie_sb_json(cookie_sbuf *b, const char *s) {
1131
+ const unsigned char *p = (const unsigned char *)(s ? s : "");
1132
+ if (!cookie_sb_add(b, "\"", 1)) return 0;
1133
+ for (; *p; p++) {
1134
+ char esc[8];
1135
+ switch (*p) {
1136
+ case '"': if (!cookie_sb_add(b, "\\\"", 2)) return 0; break;
1137
+ case '\\': if (!cookie_sb_add(b, "\\\\", 2)) return 0; break;
1138
+ case '\n': if (!cookie_sb_add(b, "\\n", 2)) return 0; break;
1139
+ case '\r': if (!cookie_sb_add(b, "\\r", 2)) return 0; break;
1140
+ case '\t': if (!cookie_sb_add(b, "\\t", 2)) return 0; break;
1141
+ default:
1142
+ if (*p < 0x20) {
1143
+ int n = snprintf(esc, sizeof(esc), "\\u%04x", (unsigned)*p);
1144
+ if (n > 0 && !cookie_sb_add(b, esc, (size_t)n)) return 0;
1145
+ } else if (!cookie_sb_add(b, (const char *)p, 1)) {
1146
+ return 0;
1147
+ }
1148
+ }
1149
+ }
1150
+ return cookie_sb_add(b, "\"", 1);
1151
+ }
1152
+
1153
+ static char *cookie_dup(const char *s) {
1154
+ size_t n;
1155
+ char *p;
1156
+ if (!s) s = "";
1157
+ n = strlen(s);
1158
+ p = (char *)malloc(n + 1);
1159
+ if (!p) return NULL;
1160
+ memcpy(p, s, n + 1);
1161
+ return p;
1162
+ }
1163
+
1164
+ static void cookie_call_free(cookie_call *c) {
1165
+ if (!c) return;
1166
+ free(c->filter);
1167
+ free(c->json);
1168
+ DeleteCriticalSection(&c->cs);
1169
+ free(c);
1170
+ }
1171
+
1172
+ /* 结果回填:等待方还在就交出去;已超时放弃就由这里回收结构 */
1173
+ static void cookie_call_set_result(cookie_call *c, char *json) {
1174
+ int abandon;
1175
+ EnterCriticalSection(&c->cs);
1176
+ abandon = c->abandoned;
1177
+ if (!abandon) {
1178
+ c->json = json;
1179
+ c->ready = 1;
1180
+ WakeConditionVariable(&c->cv);
1181
+ }
1182
+ LeaveCriticalSection(&c->cs);
1183
+ if (abandon) {
1184
+ free(json);
1185
+ cookie_call_free(c);
1186
+ }
1187
+ }
1188
+
1189
+ static void cookie_call_set_error(cookie_call *c, const char *msg) {
1190
+ cookie_sbuf b;
1191
+ memset(&b, 0, sizeof(b));
1192
+ if (!cookie_sb_puts(&b, "{\"ok\":false,\"error\":") || !cookie_sb_json(&b, msg) ||
1193
+ !cookie_sb_puts(&b, "}")) {
1194
+ free(b.p);
1195
+ cookie_call_set_result(c, cookie_dup("{\"ok\":false,\"error\":\"out of memory\"}"));
1196
+ return;
1197
+ }
1198
+ cookie_call_set_result(c, b.p);
1199
+ }
1200
+
1201
+ /* --- 完成 handler(真引用计数,最后一个 Release 才释放)---
1202
+ ⚠ 不要改回「Invoke 里 free(self)」的一次性写法:WebView2 在 Invoke 返回后仍会
1203
+ AddRef/Release 这个对象,而对象已经 free 掉——实测(2026-11-05)表现是
1204
+ `0xc0000005` 崩在 EmbeddedBrowserWebView.dll 里,随后所有 GetCookies 都不再回调
1205
+ (worker 侧只看到 5s 超时)。uri 也挂在 handler 上,让它和对象同生共死。 */
1206
+
1207
+ typedef struct cookies_hr {
1208
+ ICoreWebView2GetCookiesCompletedHandler iface;
1209
+ cookie_call *call;
1210
+ wchar_t *uri;
1211
+ LONG refs;
1212
+ } cookies_hr;
1213
+
1214
+ static HRESULT STDMETHODCALLTYPE cookies_QueryInterface(
1215
+ ICoreWebView2GetCookiesCompletedHandler *This, REFIID riid, void **ppvObject) {
1216
+ (void)riid;
1217
+ if (ppvObject) *ppvObject = This;
1218
+ return S_OK;
1219
+ }
1220
+
1221
+ static ULONG STDMETHODCALLTYPE cookies_AddRef(ICoreWebView2GetCookiesCompletedHandler *This) {
1222
+ cookies_hr *self = (cookies_hr *)This;
1223
+ LONG n = InterlockedIncrement(&self->refs);
1224
+ fprintf(stderr, "[cj-bridge] cookies: handler addref -> %ld\n", (long)n);
1225
+ return (ULONG)n;
1226
+ }
1227
+
1228
+ static ULONG STDMETHODCALLTYPE cookies_Release(ICoreWebView2GetCookiesCompletedHandler *This) {
1229
+ cookies_hr *self = (cookies_hr *)This;
1230
+ LONG left = InterlockedDecrement(&self->refs);
1231
+ fprintf(stderr, "[cj-bridge] cookies: handler release -> %ld\n", (long)left);
1232
+ if (left == 0) {
1233
+ free(self->uri);
1234
+ free(self);
1235
+ }
1236
+ return (ULONG)left;
1237
+ }
1238
+
1239
+ static HRESULT STDMETHODCALLTYPE cookies_Invoke(
1240
+ ICoreWebView2GetCookiesCompletedHandler *This, HRESULT errorCode,
1241
+ ICoreWebView2CookieList *result) {
1242
+ cookies_hr *self = (cookies_hr *)This;
1243
+ cookie_call *c = self ? self->call : NULL;
1244
+ cookie_sbuf b;
1245
+ UINT count = 0;
1246
+ UINT i;
1247
+ int first = 1;
1248
+ int ok = 1;
1249
+
1250
+ if (!c) {
1251
+ This->lpVtbl->Release(This);
1252
+ return S_OK;
1253
+ }
1254
+
1255
+ if (FAILED(errorCode) || !result) {
1256
+ char msg[96];
1257
+ snprintf(msg, sizeof(msg), "cookie read failed: hr=0x%08lx", (unsigned long)errorCode);
1258
+ fprintf(stderr, "[cj-bridge] cookies: complete failed hr=0x%08lx\n",
1259
+ (unsigned long)errorCode);
1260
+ cookie_call_set_error(c, msg);
1261
+ /* 不要 Release(result):回调参数是**借用**给 handler 的,运行时自己管它的引用。
1262
+ 释放它会让 WebView2 随后用到已销毁的 cookie list——实测崩在
1263
+ EmbeddedBrowserWebView.dll 里 0xc0000005(2026-11-05,两次同偏移)。 */
1264
+ This->lpVtbl->Release(This);
1265
+ return S_OK;
1266
+ }
1267
+
1268
+ if (FAILED(result->lpVtbl->get_Count(result, &count))) count = 0;
1269
+ fprintf(stderr, "[cj-bridge] cookies: complete count=%u\n", (unsigned)count);
1270
+
1271
+ memset(&b, 0, sizeof(b));
1272
+ {
1273
+ /* 前缀固定 31 字节 + 最多 10 位计数:32 会截断掉 "cookies": [,得到非法 JSON */
1274
+ char num[64];
1275
+ snprintf(num, sizeof(num), "{\"ok\":true,\"count\":%u,\"cookies\":[", (unsigned)count);
1276
+ ok = cookie_sb_puts(&b, num);
1277
+ }
1278
+
1279
+ for (i = 0; ok && i < count; i++) {
1280
+ ICoreWebView2Cookie *ck = NULL;
1281
+ LPWSTR wn = NULL, wv = NULL, wd = NULL, wp = NULL;
1282
+ char *n, *v, *d, *pa;
1283
+ BOOL http_only = FALSE, secure = FALSE, is_session = FALSE;
1284
+ DOUBLE expires = 0.0;
1285
+ char num[80];
1286
+
1287
+ if (FAILED(result->lpVtbl->GetValueAtIndex(result, i, &ck)) || !ck) continue;
1288
+
1289
+ ck->lpVtbl->get_Name(ck, &wn);
1290
+ ck->lpVtbl->get_Value(ck, &wv);
1291
+ ck->lpVtbl->get_Domain(ck, &wd);
1292
+ ck->lpVtbl->get_Path(ck, &wp);
1293
+ ck->lpVtbl->get_IsHttpOnly(ck, &http_only);
1294
+ ck->lpVtbl->get_IsSecure(ck, &secure);
1295
+ ck->lpVtbl->get_IsSession(ck, &is_session);
1296
+ ck->lpVtbl->get_Expires(ck, &expires);
1297
+
1298
+ n = wide_to_utf8(wn);
1299
+ v = wide_to_utf8(wv);
1300
+ d = wide_to_utf8(wd);
1301
+ pa = wide_to_utf8(wp);
1302
+
1303
+ if (!first) ok = cookie_sb_add(&b, ",", 1);
1304
+ first = 0;
1305
+ ok = ok && cookie_sb_puts(&b, "{\"name\":") && cookie_sb_json(&b, n)
1306
+ && cookie_sb_puts(&b, ",\"value\":") && cookie_sb_json(&b, v)
1307
+ && cookie_sb_puts(&b, ",\"domain\":") && cookie_sb_json(&b, d)
1308
+ && cookie_sb_puts(&b, ",\"path\":") && cookie_sb_json(&b, pa)
1309
+ && cookie_sb_puts(&b, secure ? ",\"secure\":true" : ",\"secure\":false")
1310
+ && cookie_sb_puts(&b, http_only ? ",\"httpOnly\":true" : ",\"httpOnly\":false");
1311
+ if (ok) {
1312
+ if (is_session || expires <= 0.0) {
1313
+ snprintf(num, sizeof(num), ",\"expires\":0,\"session\":true");
1314
+ } else {
1315
+ snprintf(num, sizeof(num), ",\"expires\":%lld", (long long)expires);
1316
+ }
1317
+ ok = cookie_sb_puts(&b, num);
1318
+ }
1319
+ ok = ok && cookie_sb_add(&b, "}", 1);
1320
+
1321
+ if (wn) CoTaskMemFree(wn);
1322
+ if (wv) CoTaskMemFree(wv);
1323
+ if (wd) CoTaskMemFree(wd);
1324
+ if (wp) CoTaskMemFree(wp);
1325
+ free(n);
1326
+ free(v);
1327
+ free(d);
1328
+ free(pa);
1329
+ ck->lpVtbl->Release(ck);
1330
+ }
1331
+
1332
+ ok = ok && cookie_sb_puts(&b, "]}");
1333
+ /* 同上:result 是借用的,不在这里 Release */
1334
+
1335
+ if (!ok) {
1336
+ free(b.p);
1337
+ cookie_call_set_error(c, "out of memory building cookie json");
1338
+ This->lpVtbl->Release(This);
1339
+ return S_OK;
1340
+ }
1341
+ cookie_call_set_result(c, b.p);
1342
+ This->lpVtbl->Release(This);
1343
+ return S_OK;
1344
+ }
1345
+
1346
+ /* 与 g_ctrl_vtbl / g_drop_vtbl 同款:非 const,直接挂到 iface.lpVtbl 上 */
1347
+ static ICoreWebView2GetCookiesCompletedHandlerVtbl cookies_handler_vtbl = {
1348
+ cookies_QueryInterface,
1349
+ cookies_AddRef,
1350
+ cookies_Release,
1351
+ cookies_Invoke
1352
+ };
1353
+
1354
+ /* UI 线程:发起 GetCookies */
1355
+ static void cookie_ui_start(void *ud) {
1356
+ cookie_call *c = (cookie_call *)ud;
1357
+ plat_host *p = (c && c->h) ? (plat_host *)c->h->plat : NULL;
1358
+ ICoreWebView2_2 *wv2 = NULL;
1359
+ ICoreWebView2CookieManager *cm = NULL;
1360
+ wchar_t *uri = NULL;
1361
+ cookies_hr *hr;
1362
+
1363
+ if (!c) return;
1364
+ if (!p || !p->webview) {
1365
+ cookie_call_set_error(c, "webview not ready");
1366
+ return;
1367
+ }
1368
+ fprintf(stderr, "[cj-bridge] cookies: ui thread running read\n");
1369
+ if (FAILED(p->webview->lpVtbl->QueryInterface(
1370
+ p->webview, &IID_ICoreWebView2_2, (void **)&wv2)) || !wv2) {
1371
+ cookie_call_set_error(c, "ICoreWebView2_2 unavailable (cookie store needs WebView2 88+)");
1372
+ return;
1373
+ }
1374
+ if (FAILED(wv2->lpVtbl->get_CookieManager(wv2, &cm)) || !cm) {
1375
+ wv2->lpVtbl->Release(wv2);
1376
+ cookie_call_set_error(c, "cookie manager unavailable");
1377
+ return;
1378
+ }
1379
+
1380
+ if (c->filter && *c->filter) {
1381
+ cookie_sbuf b;
1382
+ memset(&b, 0, sizeof(b));
1383
+ if (cookie_sb_puts(&b, "https://") && cookie_sb_puts(&b, c->filter) &&
1384
+ cookie_sb_puts(&b, "/")) {
1385
+ uri = utf8_to_wide(b.p);
1386
+ }
1387
+ free(b.p);
1388
+ } else {
1389
+ /* 空 filter = 「同 profile 下的全部 cookie」,**uri 必须给空串**:SDK 文档明写
1390
+ 「If uri is empty string or null, all cookies under the same profile are returned」。
1391
+ 别回落到当前页 URL——本类工具的主页面是 NavigateToString 出来的 about:blank,
1392
+ 拿它去匹配一个站点都命不中,已登录也读出 count=0(2026-11-05 实机复现:
1393
+ 内嵌视图登录 CSDN 后 probe 仍报「还没有 cookie」)。Linux 侧走 get_all_cookies,
1394
+ 本来就不按 uri 过滤,两平台在此口径一致。 */
1395
+ uri = utf8_to_wide("");
1396
+ }
1397
+
1398
+ hr = (cookies_hr *)calloc(1, sizeof(*hr));
1399
+ if (!hr || !uri) {
1400
+ free(hr);
1401
+ free(uri);
1402
+ cm->lpVtbl->Release(cm);
1403
+ wv2->lpVtbl->Release(wv2);
1404
+ cookie_call_set_error(c, "out of memory building cookie request");
1405
+ return;
1406
+ }
1407
+ /* uri 交给 handler 持有:异步读期间它得活着,随 handler 的最后一个 Release 释放 */
1408
+ hr->iface.lpVtbl = &cookies_handler_vtbl;
1409
+ hr->call = c;
1410
+ hr->uri = uri;
1411
+ hr->refs = 1;
1412
+ {
1413
+ HRESULT ghr = cm->lpVtbl->GetCookies(cm, uri, &hr->iface);
1414
+ cm->lpVtbl->Release(cm);
1415
+ wv2->lpVtbl->Release(wv2);
1416
+ if (FAILED(ghr)) {
1417
+ fprintf(stderr, "[cj-bridge] cookies: GetCookies failed hr=0x%08lx\n",
1418
+ (unsigned long)ghr);
1419
+ cookie_call_set_error(c, "GetCookies call failed");
1420
+ hr->iface.lpVtbl->Release(&hr->iface);
1421
+ return;
1422
+ }
1423
+ /* 我们这一份引用留到 Invoke 里交还:先不放。放早了(若运行时其实没 AddRef)
1424
+ 就是「回调里还被指着的对象已经销毁」,与 free(self) 那条同一种崩法。 */
1425
+ }
1426
+ }
1427
+
1428
+ char *cj_plat_get_cookies(cj_host *h, const char *filter) {
1429
+ plat_host *p = h ? (plat_host *)h->plat : NULL;
1430
+ cookie_call *c;
1431
+ char *json = NULL;
1432
+
1433
+ if (!p || !p->webview) {
1434
+ return cookie_dup("{\"ok\":false,\"error\":\"webview not ready\"}");
1435
+ }
1436
+ if (p->thread_set && GetCurrentThreadId() == p->thread_id) {
1437
+ /* 等待的事件得由 UI 线程处理:站在这里阻塞 = 自己把自己锁死 */
1438
+ return cookie_dup("{\"ok\":false,\"error\":\"get_cookies must be called from a worker thread\"}");
1439
+ }
1440
+
1441
+ c = (cookie_call *)calloc(1, sizeof(*c));
1442
+ if (!c) return cookie_dup("{\"ok\":false,\"error\":\"out of memory\"}");
1443
+ c->h = h;
1444
+ c->filter = cookie_dup(filter ? filter : "");
1445
+ if (!c->filter) {
1446
+ free(c);
1447
+ return cookie_dup("{\"ok\":false,\"error\":\"out of memory\"}");
1448
+ }
1449
+ InitializeCriticalSection(&c->cs);
1450
+ InitializeConditionVariable(&c->cv);
1451
+
1452
+ if (!cj_plat_post_ui(h, cookie_ui_start, c)) {
1453
+ cookie_call_free(c);
1454
+ return cookie_dup("{\"ok\":false,\"error\":\"ui thread unavailable\"}");
1455
+ }
1456
+ fprintf(stderr, "[cj-bridge] cookies: posted read filter=\"%s\"\n",
1457
+ (c->filter && *c->filter) ? c->filter : "(all)");
1458
+
1459
+ EnterCriticalSection(&c->cs);
1460
+ while (!c->ready) {
1461
+ if (!SleepConditionVariableCS(&c->cv, &c->cs, 5000)) break; /* 超时:放弃等待 */
1462
+ }
1463
+ if (c->ready) {
1464
+ json = c->json;
1465
+ c->json = NULL;
1466
+ LeaveCriticalSection(&c->cs);
1467
+ cookie_call_free(c);
1468
+ } else {
1469
+ /* 超时不能释放结构:异步回调可能还在路上,交给它回收 */
1470
+ c->abandoned = 1;
1471
+ LeaveCriticalSection(&c->cs);
1472
+ fprintf(stderr, "[cj-bridge] cookies: timeout after 5000ms, abandoning\n");
1473
+ json = cookie_dup("{\"ok\":false,\"error\":\"timeout waiting for cookie store\"}");
1474
+ }
1475
+ return json;
1476
+ }
1477
+
1080
1478
  /* ===== 剪贴板(plugin_clipboard 的平台层):Win32 clipboard =====
1081
1479
  调用方保证已在宿主 UI 线程上(core 的 UI 线程分流负责)。OpenClipboard 带重试:
1082
1480
  剪贴板是系统单例,别的进程可能正占着(MSDN 建议的做法)。 */
@@ -476,6 +476,21 @@ int cj_plat_pid_alive(long long pid) {
476
476
  return 0; /* 桩平台没有真进程 */
477
477
  }
478
478
 
479
+ /* ===== Cookie 读取桩:桩平台没有真 cookie store,只为让 core 的**入口校验与转发**可调可断言 =====
480
+ 「投 UI 线程 → 异步读 → 回填唤醒」那条路由 + 超时兜底由平台实机验证(Linux / Windows 各一份)。 */
481
+ static int g_cookie_calls = 0;
482
+ static char *g_cookie_last_filter = NULL;
483
+ static int g_cookie_null = 0; /* 扳成 1 时模拟「平台回 NULL」*/
484
+
485
+ char *cj_plat_get_cookies(cj_host *h, const char *filter) {
486
+ (void)h;
487
+ g_cookie_calls++;
488
+ free(g_cookie_last_filter);
489
+ g_cookie_last_filter = strdup(filter ? filter : "");
490
+ if (g_cookie_null) return NULL;
491
+ return strdup("{\"ok\":true,\"count\":0,\"cookies\":[]}");
492
+ }
493
+
479
494
  /* ===== 内嵌资源桩:桩平台没有 PE 资源表,如实返回 0 或留一句原因,
480
495
  让 core 的三条分支(参数校验 / 无资源 / 失败)都能在无 SDK 的机器上被断言。 ===== */
481
496
  int cj_plat_extract_assets(const char *dir, char *err, int err_len) {
@@ -1267,7 +1282,40 @@ int main(void) {
1267
1282
  CHECK(cj_bridge_pid_alive(0) == 0, "pid_alive(0) 恒为 0(不落到平台原语)");
1268
1283
  }
1269
1284
 
1270
- /* ===== 内嵌资源释放:单文件包随包资源(core 负责校验与错误出口) ===== */
1285
+ /* ===== Cookie 读取:core 只做入口校验与转发(投递 / 等待 / 超时在平台层,实机验证) ===== */
1286
+ {
1287
+ char *j;
1288
+ case_begin("get cookies");
1289
+ g_cookie_calls = 0;
1290
+ j = cj_bridge_get_cookies(NULL, "");
1291
+ CHECK(j != NULL && strstr(j, "host not ready") != NULL,
1292
+ "host 为 NULL 时回失败 JSON(不落平台原语)");
1293
+ CHECK(g_cookie_calls == 0, "host 不可用时不触达平台原语");
1294
+ cj_bridge_cookies_free(j);
1295
+
1296
+ h->ready = 1;
1297
+ j = cj_bridge_get_cookies(h, NULL);
1298
+ CHECK(j != NULL && strstr(j, "cookies") != NULL, "NULL filter 原样转成空串并转发");
1299
+ CHECK(g_cookie_calls == 1, "就绪后转交平台原语恰好一次");
1300
+ CHECK(g_cookie_last_filter && g_cookie_last_filter[0] == '\0',
1301
+ "NULL filter 落到平台层是空串(= 全量)");
1302
+ cj_bridge_cookies_free(j);
1303
+
1304
+ j = cj_bridge_get_cookies(h, "zhihu.com");
1305
+ CHECK(g_cookie_last_filter && strcmp(g_cookie_last_filter, "zhihu.com") == 0,
1306
+ "filter 原样转发给平台(不做改写)");
1307
+ CHECK(j != NULL && strstr(j, "\"ok\":true") != NULL, "平台 JSON 原样回给上层");
1308
+ cj_bridge_cookies_free(j);
1309
+
1310
+ g_cookie_null = 1;
1311
+ j = cj_bridge_get_cookies(h, "");
1312
+ CHECK(j != NULL && strstr(j, "platform returned null") != NULL,
1313
+ "平台回 NULL 时 core 自己补失败 JSON(绝不给上层空指针)");
1314
+ cj_bridge_cookies_free(j);
1315
+ g_cookie_null = 0;
1316
+ h->ready = 0;
1317
+ }
1318
+
1271
1319
  {
1272
1320
  case_begin("extract assets");
1273
1321
  CHECK(cj_bridge_extract_assets(NULL) == -1, "extract_assets(NULL) 被拒");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cj-tauri",
3
- "version": "2.1.1",
3
+ "version": "2.1.3",
4
4
  "description": "Tauri for the Cangjie language: a scaffold CLI for hybrid desktop apps — Cangjie backend (statically compiled) plus a system WebView frontend (HTML/CSS/JS), with a bidirectional IPC bridge and a capability-based security model. Windows, Linux and HarmonyOS PC.",
5
5
  "keywords": [
6
6
  "cangjie",
@@ -0,0 +1,42 @@
1
+ package cjTauri
2
+
3
+ /**
4
+ * Cookie 读取桥(「一键导出各平台登录态」类工具的平台面)。
5
+ *
6
+ * ## 为什么必须走原生,而不是注入 JS 读 `document.cookie`
7
+ *
8
+ * **httpOnly**。各平台的会话令牌(知乎 `z_c0`、掘金 `sessionid`、开源中国 `oscid`、
9
+ * 百家号 `BDUSS` …)基本都是 httpOnly Cookie,JS 侧完全看不见。用 `document.cookie`
10
+ * 那条路导出来的文件「字段看着齐全」,发文却 401——比导不出来更难查。cookie store 才是全量快照。
11
+ *
12
+ * ## 平台差异在哪
13
+ *
14
+ * 两平台导出同名同签名(AGENTS §2 的硬约束),差异全在 `native/platforms/` 下的平台文件:
15
+ * Linux = `webkit_cookie_manager_get_all_cookies`(异步,GList<SoupCookie>),
16
+ * Windows = `ICoreWebView2CookieManager::GetCookies`(异步,ICoreWebView2CookieList)。
17
+ *
18
+ * ## 鸿蒙侧为什么整段门禁掉
19
+ *
20
+ * 鸿蒙没有 C 桥产物,这两个符号无处解析;留着的风险不是编译报错,而是**模块加载期
21
+ * SIGSEGV**(同 `clipboard_bridge.cj` 那次白屏,AGENTS §4 最后一条)。
22
+ */
23
+
24
+ /**
25
+ * 读宿主 WebView 的 cookie 仓库。返回 **malloc 的 JSON**,必须经 `cj_bridge_cookies_free` 释放。
26
+ *
27
+ * 成功:`{"ok":true,"count":N,"cookies":[{"name","value","domain","path","secure","httpOnly","expires","session"}]}`
28
+ * 失败:`{"ok":false,"error":"…"}` —— 失败也返回 JSON,调用方永远不必判空指针。
29
+ *
30
+ * `filter` = 域名后缀(`"csdn.net"` 命中 `.csdn.net` / `www.csdn.net`),空串 = 全部。
31
+ *
32
+ * **线程口径**:必须在命令 worker 线程调用——内部投 UI 线程发起异步读并带 5s 超时;
33
+ * 站在 UI 线程上调用会直接拿到错误 JSON(等待的事件得由 UI 线程处理,阻塞即自死锁)。
34
+ */
35
+ @When[env != "ohos"]
36
+ @C
37
+ foreign func cj_bridge_get_cookies(h: CPointer<Unit>, filter: CString): CString
38
+
39
+ /** 释放 get_cookies 返回的缓冲(NULL 安全,幂等) */
40
+ @When[env != "ohos"]
41
+ @C
42
+ foreign func cj_bridge_cookies_free(s: CString): Unit
package/src/host.cj CHANGED
@@ -402,6 +402,20 @@ public interface WebViewHost {
402
402
  */
403
403
  func clipboardReadText(): Option<String>
404
404
 
405
+ /**
406
+ * 读宿主 WebView 的 cookie 仓库,返回 JSON 文本(**含 httpOnly**——这正是它存在的理由,
407
+ * 会话令牌基本都在 httpOnly 里,`document.cookie` 看不见)。
408
+ *
409
+ * 成功:`{"ok":true,"count":N,"cookies":[{"name","value","domain","path","secure","httpOnly","expires","session"}]}`
410
+ * 失败:`{"ok":false,"error":"…"}` —— 失败也返回合法 JSON,调用方不必判 null/异常。
411
+ *
412
+ * `filter` 是域名后缀(`"csdn.net"` 命中 `.csdn.net`/`www.csdn.net`),空串 = 全部。
413
+ *
414
+ * **线程口径**:在命令 worker 线程调用——内部投 UI 线程发起异步读取并带超时等待;
415
+ * 站在 UI 线程上调用会直接拿到错误 JSON(等待的事件得由 UI 线程自己处理,阻塞即自死锁)。
416
+ */
417
+ func cookiesJson(filter: String): String
418
+
405
419
  /**
406
420
  * 发一条系统通知(发后即忘:提交即返回,显示成败不回传)。
407
421
  * 本平台未实现时返回 false(`system:host` 的能力位会同口径如实上报)。
@@ -523,6 +523,31 @@ public class WebKitHost <: WebViewHost {
523
523
  return Some(text)
524
524
  }
525
525
 
526
+ /**
527
+ * 读宿主 WebView 的 cookie 仓库(JSON 文本,**含 httpOnly**)。
528
+ *
529
+ * filter = 域名后缀(如 `"csdn.net"`;`".csdn.net"` 也命中),空串 = 全部。
530
+ * 失败也返回 JSON(`{"ok":false,"error":…}`),调用方永远不必判 null。
531
+ *
532
+ * **线程口径**:请在命令 worker 线程调用——桥内部投 UI 线程发起异步读并带 5s 超时;
533
+ * 站在 UI 线程上调用会直接拿到错误 JSON(等待的事件得由 UI 线程处理,阻塞即自死锁)。
534
+ */
535
+ public func cookiesJson(filter: String): String {
536
+ let f = unsafe { LibC.mallocCString(filter) }
537
+ let cs = unsafe { cj_bridge_get_cookies(this.handle, f) }
538
+ unsafe {
539
+ LibC.free(f) // C 侧只拷贝,不接管入参所有权
540
+ }
541
+ if (cs.isNull()) {
542
+ return "{\"ok\":false,\"error\":\"bridge returned null\"}"
543
+ }
544
+ let json = cs.toString()
545
+ unsafe {
546
+ cj_bridge_cookies_free(cs) // 归还缓冲:malloc 家族分配,必须走桥的 free
547
+ }
548
+ return json
549
+ }
550
+
526
551
  public func notify(title: String, body: String): Bool {
527
552
  var rc: Int32 = -1
528
553
  unsafe {
@@ -523,6 +523,31 @@ public class WebView2Host <: WebViewHost {
523
523
  return Some(text)
524
524
  }
525
525
 
526
+ /**
527
+ * 读宿主 WebView 的 cookie 仓库(JSON 文本,**含 httpOnly**)。
528
+ *
529
+ * filter = 域名后缀(如 `"csdn.net"`;`".csdn.net"` 也命中),空串 = 全部。
530
+ * 失败也返回 JSON(`{"ok":false,"error":…}`),调用方永远不必判 null。
531
+ *
532
+ * **线程口径**:请在命令 worker 线程调用——桥内部投 UI 线程发起异步读并带 5s 超时;
533
+ * 站在 UI 线程上调用会直接拿到错误 JSON(等待的事件得由 UI 线程处理,阻塞即自死锁)。
534
+ */
535
+ public func cookiesJson(filter: String): String {
536
+ let f = unsafe { LibC.mallocCString(filter) }
537
+ let cs = unsafe { cj_bridge_get_cookies(this.handle, f) }
538
+ unsafe {
539
+ LibC.free(f) // C 侧只拷贝,不接管入参所有权
540
+ }
541
+ if (cs.isNull()) {
542
+ return "{\"ok\":false,\"error\":\"bridge returned null\"}"
543
+ }
544
+ let json = cs.toString()
545
+ unsafe {
546
+ cj_bridge_cookies_free(cs) // 归还缓冲:malloc 家族分配,必须走桥的 free
547
+ }
548
+ return json
549
+ }
550
+
526
551
  public func notify(title: String, body: String): Bool {
527
552
  var rc: Int32 = -1
528
553
  unsafe {
@@ -167,6 +167,14 @@ class FakeHost <: WebViewHost {
167
167
  return true
168
168
  }
169
169
 
170
+ /** cookie 桥回包:测试直接塞一段 JSON(默认空仓库);filter 由调用方自己过滤,这里不模拟 */
171
+ public var cookieJson: String = "{\"ok\":true,\"count\":0,\"cookies\":[]}"
172
+
173
+ public func cookiesJson(filter: String): String {
174
+ let _ = filter
175
+ return this.cookieJson
176
+ }
177
+
170
178
  public func clipboardReadText(): Option<String> {
171
179
  return this.clipboardReadValue
172
180
  }
package/src/version.cj CHANGED
@@ -9,7 +9,7 @@ package cjTauri
9
9
  * - cli/src/project.cj 的 cliVersion()
10
10
  * - CHANGELOG.md 顶部第一个已发版段
11
11
  */
12
- public let CJ_TAURI_VERSION = "2.1.1"
12
+ public let CJ_TAURI_VERSION = "2.1.3"
13
13
 
14
14
  /**
15
15
  * IPC 报文协议版本(报文形状是跨层契约,加版本字段是协议治理惯例):事件 / 回执信封的 `protocol` 字段