krillplayer-plugin 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/LICENSE +2 -1
  2. package/README.md +1 -0
  3. package/dist/cli.js +351 -73
  4. package/dist/crypto.js +37 -11
  5. package/dist/engine/engine.c +6 -3
  6. package/kernel/Sources/CQuickJS/include/kernel_qjs.h +8 -1
  7. package/kernel/Sources/CQuickJS/kernel_internal.h +54 -0
  8. package/kernel/Sources/CQuickJS/kernel_qjs.c +17 -29
  9. package/kernel/Sources/CQuickJS/kernel_wasm.c +1155 -0
  10. package/kernel/Sources/CWAMR/include/kernel_wamr.h +151 -0
  11. package/kernel/Sources/CWAMR/include/kernel_wamr_config.h +66 -0
  12. package/kernel/Sources/CWAMR/vendor/LICENSE +219 -0
  13. package/kernel/Sources/CWAMR/vendor/core/config.h +727 -0
  14. package/kernel/Sources/CWAMR/vendor/core/iwasm/aot/aot_runtime.h +899 -0
  15. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/arch/invokeNative_general.c +123 -0
  16. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_application.c +933 -0
  17. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_blocking_op.c +92 -0
  18. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_c_api.c +5391 -0
  19. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_c_api_internal.h +246 -0
  20. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_exec_env.c +336 -0
  21. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_exec_env.h +328 -0
  22. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_loader_common.c +242 -0
  23. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_loader_common.h +62 -0
  24. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_memory.c +1999 -0
  25. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_memory.h +154 -0
  26. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_native.c +1532 -0
  27. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_native.h +117 -0
  28. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_runtime_common.c +8070 -0
  29. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_runtime_common.h +1396 -0
  30. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_shared_memory.c +477 -0
  31. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_shared_memory.h +63 -0
  32. package/kernel/Sources/CWAMR/vendor/core/iwasm/common/wasm_suspend_flags.h +52 -0
  33. package/kernel/Sources/CWAMR/vendor/core/iwasm/compilation/aot.h +366 -0
  34. package/kernel/Sources/CWAMR/vendor/core/iwasm/include/lib_export.h +60 -0
  35. package/kernel/Sources/CWAMR/vendor/core/iwasm/include/wasm_c_api.h +910 -0
  36. package/kernel/Sources/CWAMR/vendor/core/iwasm/include/wasm_export.h +2440 -0
  37. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm.h +1492 -0
  38. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_interp.h +122 -0
  39. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_interp_fast.c +7998 -0
  40. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_loader.c +16909 -0
  41. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_loader.h +80 -0
  42. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_opcode.h +1043 -0
  43. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_runtime.c +5174 -0
  44. package/kernel/Sources/CWAMR/vendor/core/iwasm/interpreter/wasm_runtime.h +912 -0
  45. package/kernel/Sources/CWAMR/vendor/core/iwasm/libraries/thread-mgr/thread_manager.c +1569 -0
  46. package/kernel/Sources/CWAMR/vendor/core/iwasm/libraries/thread-mgr/thread_manager.h +256 -0
  47. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/ems/ems_alloc.c +1169 -0
  48. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/ems/ems_gc.c +497 -0
  49. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/ems/ems_gc.h +350 -0
  50. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/ems/ems_gc_internal.h +384 -0
  51. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/ems/ems_hmu.c +95 -0
  52. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/ems/ems_kfc.c +547 -0
  53. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/mem_alloc.c +252 -0
  54. package/kernel/Sources/CWAMR/vendor/core/shared/mem-alloc/mem_alloc.h +96 -0
  55. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/memory/mremap.c +12 -0
  56. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/posix/posix_blocking_op.c +70 -0
  57. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/posix/posix_malloc.c +72 -0
  58. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/posix/posix_memmap.c +302 -0
  59. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/posix/posix_sleep.c +20 -0
  60. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/posix/posix_thread.c +784 -0
  61. package/kernel/Sources/CWAMR/vendor/core/shared/platform/common/posix/posix_time.c +28 -0
  62. package/kernel/Sources/CWAMR/vendor/core/shared/platform/darwin/platform_init.c +43 -0
  63. package/kernel/Sources/CWAMR/vendor/core/shared/platform/darwin/platform_internal.h +126 -0
  64. package/kernel/Sources/CWAMR/vendor/core/shared/platform/include/platform_api_extension.h +1676 -0
  65. package/kernel/Sources/CWAMR/vendor/core/shared/platform/include/platform_api_vmcore.h +192 -0
  66. package/kernel/Sources/CWAMR/vendor/core/shared/platform/include/platform_common.h +204 -0
  67. package/kernel/Sources/CWAMR/vendor/core/shared/platform/include/platform_wasi_types.h +610 -0
  68. package/kernel/Sources/CWAMR/vendor/core/shared/platform/linux/platform_init.c +43 -0
  69. package/kernel/Sources/CWAMR/vendor/core/shared/platform/linux/platform_internal.h +139 -0
  70. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_assert.c +25 -0
  71. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_assert.h +42 -0
  72. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_atomic.h +300 -0
  73. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_bitmap.c +27 -0
  74. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_bitmap.h +114 -0
  75. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_common.c +217 -0
  76. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_common.h +83 -0
  77. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_hashmap.c +339 -0
  78. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_hashmap.h +168 -0
  79. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_leb128.c +77 -0
  80. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_leb128.h +30 -0
  81. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_list.c +111 -0
  82. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_list.h +109 -0
  83. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_log.c +111 -0
  84. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_log.h +94 -0
  85. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_platform.h +38 -0
  86. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_queue.c +256 -0
  87. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_queue.h +80 -0
  88. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_vector.c +279 -0
  89. package/kernel/Sources/CWAMR/vendor/core/shared/utils/bh_vector.h +126 -0
  90. package/kernel/Sources/CWAMR/vendor/core/shared/utils/gnuc.h +14 -0
  91. package/kernel/Sources/CWAMR/vendor/core/shared/utils/runtime_timer.c +469 -0
  92. package/kernel/Sources/CWAMR/vendor/core/shared/utils/runtime_timer.h +51 -0
  93. package/kernel/Sources/CWAMR/vendor/core/version.h +24 -0
  94. package/kernel/Sources/CWAMR/wamr_bh_assert.c +98 -0
  95. package/kernel/Sources/CWAMR/wamr_bh_bitmap.c +98 -0
  96. package/kernel/Sources/CWAMR/wamr_bh_common.c +98 -0
  97. package/kernel/Sources/CWAMR/wamr_bh_hashmap.c +98 -0
  98. package/kernel/Sources/CWAMR/wamr_bh_leb128.c +98 -0
  99. package/kernel/Sources/CWAMR/wamr_bh_list.c +98 -0
  100. package/kernel/Sources/CWAMR/wamr_bh_log.c +98 -0
  101. package/kernel/Sources/CWAMR/wamr_bh_queue.c +98 -0
  102. package/kernel/Sources/CWAMR/wamr_bh_vector.c +98 -0
  103. package/kernel/Sources/CWAMR/wamr_ems_alloc.c +98 -0
  104. package/kernel/Sources/CWAMR/wamr_ems_gc.c +98 -0
  105. package/kernel/Sources/CWAMR/wamr_ems_hmu.c +98 -0
  106. package/kernel/Sources/CWAMR/wamr_ems_kfc.c +98 -0
  107. package/kernel/Sources/CWAMR/wamr_invokeNative_general.c +98 -0
  108. package/kernel/Sources/CWAMR/wamr_mem_alloc.c +98 -0
  109. package/kernel/Sources/CWAMR/wamr_mremap.c +98 -0
  110. package/kernel/Sources/CWAMR/wamr_platform_init_darwin.c +100 -0
  111. package/kernel/Sources/CWAMR/wamr_platform_init_linux.c +100 -0
  112. package/kernel/Sources/CWAMR/wamr_posix_blocking_op.c +98 -0
  113. package/kernel/Sources/CWAMR/wamr_posix_malloc.c +98 -0
  114. package/kernel/Sources/CWAMR/wamr_posix_memmap.c +98 -0
  115. package/kernel/Sources/CWAMR/wamr_posix_sleep.c +98 -0
  116. package/kernel/Sources/CWAMR/wamr_posix_thread.c +98 -0
  117. package/kernel/Sources/CWAMR/wamr_posix_time.c +98 -0
  118. package/kernel/Sources/CWAMR/wamr_runtime_timer.c +98 -0
  119. package/kernel/Sources/CWAMR/wamr_thread_manager.c +98 -0
  120. package/kernel/Sources/CWAMR/wamr_wasm_application.c +98 -0
  121. package/kernel/Sources/CWAMR/wamr_wasm_blocking_op.c +98 -0
  122. package/kernel/Sources/CWAMR/wamr_wasm_c_api.c +98 -0
  123. package/kernel/Sources/CWAMR/wamr_wasm_exec_env.c +98 -0
  124. package/kernel/Sources/CWAMR/wamr_wasm_interp_fast.c +98 -0
  125. package/kernel/Sources/CWAMR/wamr_wasm_loader.c +98 -0
  126. package/kernel/Sources/CWAMR/wamr_wasm_loader_common.c +98 -0
  127. package/kernel/Sources/CWAMR/wamr_wasm_memory.c +98 -0
  128. package/kernel/Sources/CWAMR/wamr_wasm_native.c +98 -0
  129. package/kernel/Sources/CWAMR/wamr_wasm_runtime.c +98 -0
  130. package/kernel/Sources/CWAMR/wamr_wasm_runtime_common.c +98 -0
  131. package/kernel/Sources/CWAMR/wamr_wasm_shared_memory.c +98 -0
  132. package/kernel/Sources/Kernel/PluginPrelude.js +5 -2
  133. package/kernel/Tests/KernelTests/CasePins.js +50 -0
  134. package/package.json +2 -2
  135. package/skill/krillplayer-plugin/SKILL.md +2 -0
  136. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-content-rejected.json +8 -4
  137. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-login-expired.json +8 -4
  138. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-muted.json +8 -4
  139. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-other.json +8 -4
  140. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-rate-limited.json +8 -4
  141. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-sent.json +8 -4
  142. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/play-live-logged-in.json +39 -0
  143. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/play-live-selected-backup-line.json +8 -0
  144. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/play-live-selected-line-gone.json +8 -0
  145. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/play-live.json +8 -0
  146. package/skill/krillplayer-plugin/assets/samples/live-video-platform/plugin.ts +26 -9
  147. package/skill/krillplayer-plugin/references/cases.md +19 -1
  148. package/skill/krillplayer-plugin/references/contract.d.ts +104 -11
  149. package/skill/krillplayer-plugin/references/crypto-tools.md +104 -0
  150. package/skill/krillplayer-plugin/references/errors-and-fixes.md +5 -1
package/dist/cli.js CHANGED
@@ -14,6 +14,7 @@ var integer = { kind: "integer" };
14
14
  var number = { kind: "number" };
15
15
  var boolean = { kind: "boolean" };
16
16
  var bytes = { kind: "bytes" };
17
+ var json = { kind: "json" };
17
18
  function constant(value) {
18
19
  return { kind: "constant", value };
19
20
  }
@@ -59,6 +60,17 @@ function paged(of) {
59
60
  var CONTRACT = { interfaceLevel: 0, revision: 2 };
60
61
  var STORAGE_LIMITS = { keyBytes: 256, valueBytes: 64 * 1024, pluginBytes: 1024 * 1024 };
61
62
  var RUNTIME_LIMITS = { memoryBytes: 64 * 1024 * 1024, callSeconds: 20, stackBytes: 256 * 1024, callDepth: 64 };
63
+ var WASM_LIMITS = { moduleBytes: 8 * 1024 * 1024, modules: 4 };
64
+ var DECRYPT_LIMITS = {
65
+ contextBytes: 32 * 1024 * 1024,
66
+ pushBytes: 64 * 1024,
67
+ outputBytes: 4 * 1024 * 1024,
68
+ waitingBytes: 1024 * 1024,
69
+ contexts: 4,
70
+ tvContexts: 2,
71
+ segmentBytes: 64 * 1024 * 1024,
72
+ mapBytes: 1024 * 1024
73
+ };
62
74
  var FORMAT_LIMITS = { xmlDepth: 64, guideBytes: 48 * 1024 * 1024, decompressedBytes: 64 * 1024 * 1024 };
63
75
  var VALUE_LIMITS = { depth: 160 };
64
76
  var FILE_LIMITS = { readBytes: 4 * 1024 * 1024 };
@@ -81,7 +93,8 @@ var Capability = enumeration("Capability", [
81
93
  "browseLists",
82
94
  "playerPanels",
83
95
  "cardActions",
84
- "danmakuSendSession"
96
+ "danmakuSendSession",
97
+ "decrypt"
85
98
  ]);
86
99
  var Media = enumeration("Media", ["video", "audio"]);
87
100
  var ChannelKind = enumeration("ChannelKind", ["creator", "station", "podcast"]);
@@ -332,6 +345,12 @@ var PlatformCapabilities = object("PlatformCapabilities", {
332
345
  macOS: optional(array(Capability)),
333
346
  tvOS: optional(array(Capability))
334
347
  });
348
+ var PluginModule = object("PluginModule", {
349
+ name: string,
350
+ url: string,
351
+ sha256: string,
352
+ size: integer
353
+ });
335
354
  var PluginManifest = object("PluginManifest", {
336
355
  id: string,
337
356
  sourceId: string,
@@ -353,6 +372,8 @@ var PluginManifest = object("PluginManifest", {
353
372
  files: optional(FilesProtocol),
354
373
  // 要用哪几把 App 自己的密钥(krillplayer.appKeys,contract.md 6.3)。只有预装插件拿得到;用户添加的插件写了也只拿到 null。
355
374
  appKeys: optional(array(string)),
375
+ // 要用 krillplayer.wasm 的模块,最多 WASM_LIMITS.modules 个(见 PluginModule)。
376
+ modules: optional(array(PluginModule)),
356
377
  parameters: optional(array(Parameter)),
357
378
  settings: optional(array(Parameter)),
358
379
  unsupported: optional(PlatformCapabilities),
@@ -387,17 +408,25 @@ var PlayableSubtitle = object("PlayableSubtitle", {
387
408
  url: string,
388
409
  headers: optional(map(string))
389
410
  });
411
+ var Container = enumeration("Container", ["mp4", "mov", "mkv", "ts", "flv", "hls", "dash", "webm", "mp3", "aac", "flac", "ogg"]);
412
+ var PlayableDecryption = union("PlayableDecryption", "method", [
413
+ object("CencDecryption", { method: constant("cencAesCtr"), key: string, keyId: optional(string) }),
414
+ object("PluginDecryption", { method: constant("plugin"), state: optional(json) })
415
+ ]);
390
416
  var PlayableStream = object("PlayableStream", {
391
417
  quality: string,
392
418
  url: string,
393
419
  headers: optional(map(string)),
394
420
  audioURL: optional(string),
395
- container: optional(enumeration("Container", ["mp4", "mov", "mkv", "ts", "flv", "hls", "dash", "webm", "mp3", "aac", "flac", "ogg"]))
421
+ container: optional(Container),
422
+ // 这一路自己的解密信息,盖过 Playable 上那一个:同一次应答里常有加密档与明文档。
423
+ decryption: optional(PlayableDecryption)
396
424
  });
397
425
  var PlayableLine = object("PlayableLine", {
398
426
  name: string,
399
427
  streams: array(PlayableStream),
400
- qualities: optional(array(string))
428
+ qualities: optional(array(string)),
429
+ loginQualities: optional(array(string))
401
430
  });
402
431
  var Playable = object("Playable", {
403
432
  timing: enumeration("PlayableTiming", ["live", "onDemand"]),
@@ -412,11 +441,7 @@ var Playable = object("Playable", {
412
441
  end: number,
413
442
  title: optional(string)
414
443
  }))),
415
- decryption: optional(object("PlayableDecryption", {
416
- method: enumeration("PlayableDecryptionMethod", ["cencAesCtr"]),
417
- key: string,
418
- keyId: optional(string)
419
- })),
444
+ decryption: optional(PlayableDecryption),
420
445
  subtitles: optional(array(PlayableSubtitle)),
421
446
  // 这一路的原始文件名,给字幕插件与弹幕插件匹配用(contract.md 3.1);不给时内核用条目的文件名或标题。
422
447
  filename: optional(string)
@@ -820,6 +845,8 @@ var SLOT_RULES = {
820
845
  // 组件页面 page 去掉了(ADR 0040),剩下播放器面板与卡片操作,都交数据(#753)。面板与操作各一项能力,
821
846
  // 不再是 views:交组件格式的旧插件打的是 views,新内核不认识、跳过,不会按数据去解它;旧内核也不认识这两项,不会按组件格式去解新插件。
822
847
  views: { functions: ["panel", "action"], required: [], pairs: [], capabilities: { playerPanels: ["panel"], cardActions: ["action"] } },
848
+ // 解密槽位(contract.md 6.5):play.start 交出 decryption: { method: "plugin" } 的一路,字节经它解开。每个单位一个新上下文。
849
+ decrypt: { functions: ["open", "push", "finish"], required: ["open", "push"], pairs: [], capabilities: { decrypt: ["open"] } },
823
850
  // 顶层的 parameters 不算能力(contract.md 第 2 节)。
824
851
  parameters: { functions: ["options"], required: ["options"], pairs: [], capabilities: {} }
825
852
  };
@@ -865,6 +892,7 @@ var SLOT_RETURNS = {
865
892
  account: { schema: LoginAccount, nullable: true }
866
893
  },
867
894
  views: { panel: { schema: PanelPage }, action: { schema: ActionResult } },
895
+ decrypt: { push: { schema: array(bytes) }, finish: { schema: array(bytes) } },
868
896
  parameters: { options: { schema: array(Option) } },
869
897
  resolve: { "": { schema: Resolved, nullable: true } }
870
898
  };
@@ -1388,12 +1416,14 @@ var PREFIX = {
1388
1416
  playback: "playback",
1389
1417
  "playback-follow": "playback",
1390
1418
  "playback-probe": "playback",
1419
+ "playback-decrypt": "playback",
1391
1420
  subtitle: "subtitle",
1392
1421
  image: "image",
1393
1422
  "system-image": "image",
1394
1423
  danmaku: "danmaku",
1395
1424
  login: "login",
1396
- "plugin-link": "plugin link"
1425
+ "plugin-link": "plugin link",
1426
+ module: "module"
1397
1427
  };
1398
1428
  var lower = (values) => new Set((values ?? []).map((value) => value.toLowerCase()));
1399
1429
  var Chain = class {
@@ -1440,6 +1470,9 @@ var Chain = class {
1440
1470
  if (this.use === "login" && hostClass !== "declared") {
1441
1471
  throw this.refuse("login-page", address, `${this.label(address)} is not declared in the plugin manifest`);
1442
1472
  }
1473
+ if (this.use === "module" && hostClass !== "declared") {
1474
+ throw this.refuse("host-grant", address, `${this.label(address)} is not declared in the plugin manifest`);
1475
+ }
1443
1476
  this.startsAtUserAddress = (this.grants.userAddresses ?? []).some((value) => normalForm(value)?.href === address.href);
1444
1477
  const headers2 = remembered ? only(request.headers ?? {}, SAFELIST) : { ...request.headers };
1445
1478
  return this.settle({ address, hostClass, method, headers: headers2, body: request.body === true, frames: request.frames });
@@ -1466,10 +1499,14 @@ var Chain = class {
1466
1499
  const granted = hostClass !== "derived" || Object.hasOwn(this.remembered, address.host) || this.once.has(address.host) || this.use === "request" && this.startsAtUserAddress;
1467
1500
  if (!granted) throw this.refuse("redirect-stays-granted", address, `${this.label(address)} is not declared in the plugin manifest`);
1468
1501
  }
1502
+ if (this.use === "module" && hostClass !== "declared") {
1503
+ throw this.refuse("redirect-stays-granted", address, `${this.label(address)} is not declared in the plugin manifest`);
1504
+ }
1469
1505
  const upgrade = hostClass === "user" && address.host === previous.address.host && previous.address.scheme === "http" && address.scheme === "https";
1470
1506
  if (this.leftOrigin || address.origin !== previous.address.origin && !upgrade) {
1471
1507
  this.leftOrigin = true;
1472
- headers2 = hostClass === "derived" ? only(headers2, SAFELIST) : this.withoutCredentials(headers2);
1508
+ const safelistOnly = hostClass === "derived" || this.use === "playback-decrypt";
1509
+ headers2 = safelistOnly ? only(headers2, SAFELIST) : this.withoutCredentials(headers2);
1473
1510
  }
1474
1511
  return this.settle({ address, hostClass, method, headers: headers2, body, downgrade });
1475
1512
  }
@@ -1480,10 +1517,11 @@ var Chain = class {
1480
1517
  const { sharedSpace } = pass.publicOnly;
1481
1518
  if (addresses.some((address) => restrictedAddress(address, sharedSpace))) throw this.privateAddress(pass.address);
1482
1519
  }
1483
- // 收到应答后:连上的地址再查一次(DNS 重绑定)。
1520
+ // 收到应答后:连上的地址再查一次(DNS 重绑定)。playback-decrypt 没有这一步:字节边收边交给插件,直播的连接不结束,
1521
+ // 等不到连上的地址(decrypt-https 代它挡重绑定)。
1484
1522
  connected(connection) {
1485
1523
  const pass = this.current;
1486
- if (pass === null || pass.publicOnly === null || connection === "proxied" || connection === "none") return;
1524
+ if (this.use === "playback-decrypt" || pass === null || pass.publicOnly === null || connection === "proxied" || connection === "none") return;
1487
1525
  if (connection === "unknown") {
1488
1526
  const followsOnly = this.use === "playback-follow" || this.use === "playback-probe";
1489
1527
  if (pass.address.scheme === "http" && !followsOnly) {
@@ -1517,6 +1555,9 @@ var Chain = class {
1517
1555
  throw new NetworkRefusal(prefix, this.use === "login" ? "login-page" : "scheme", "", this.schemeMessage());
1518
1556
  }
1519
1557
  if (!this.allowsScheme(address)) throw this.refuse(this.use === "login" ? "login-page" : "scheme", address, this.schemeMessage());
1558
+ if (this.use === "playback-decrypt" && address.scheme === "http" && this.classify(address.host) !== "user") {
1559
+ throw this.refuse("decrypt-https", address, `bytes a plugin decrypts are only fetched over https from ${this.label(address)}`);
1560
+ }
1520
1561
  return address;
1521
1562
  }
1522
1563
  allowsScheme({ scheme, host }) {
@@ -1526,6 +1567,7 @@ var Chain = class {
1526
1567
  case "danmaku":
1527
1568
  return scheme === "ws" || scheme === "wss";
1528
1569
  case "login":
1570
+ case "module":
1529
1571
  return scheme === "https";
1530
1572
  case "image":
1531
1573
  case "system-image":
@@ -1550,6 +1592,8 @@ var Chain = class {
1550
1592
  return "images are only fetched over https";
1551
1593
  case "plugin-link":
1552
1594
  return "only https links can be opened";
1595
+ case "module":
1596
+ return "modules are only downloaded over https";
1553
1597
  default:
1554
1598
  return "only network stream addresses are allowed";
1555
1599
  }
@@ -2394,12 +2438,12 @@ function pluginJSONText(bytes2) {
2394
2438
  return void 0;
2395
2439
  }
2396
2440
  }
2397
- function nestedTooDeep(json, limit = VALUE_LIMITS.depth) {
2441
+ function nestedTooDeep(json2, limit = VALUE_LIMITS.depth) {
2398
2442
  let depth = 0;
2399
2443
  let inString = false;
2400
2444
  let escaped = false;
2401
- for (let i = 0; i < json.length; i += 1) {
2402
- const code = json.charCodeAt(i);
2445
+ for (let i = 0; i < json2.length; i += 1) {
2446
+ const code = json2.charCodeAt(i);
2403
2447
  if (inString) {
2404
2448
  if (escaped) escaped = false;
2405
2449
  else if (code === 92) escaped = true;
@@ -3439,11 +3483,13 @@ function createKrillPlayer({
3439
3483
  parameters = null,
3440
3484
  secrets = [],
3441
3485
  appKeys = null,
3486
+ modules = null,
3442
3487
  metadata,
3443
3488
  files: files2,
3444
3489
  localization = { locale: "en", dictionaries: {} },
3445
3490
  log = () => {
3446
- }
3491
+ },
3492
+ randomBytes
3447
3493
  }) {
3448
3494
  let current = credentials;
3449
3495
  const handedKeys = /* @__PURE__ */ new Set();
@@ -3470,7 +3516,7 @@ function createKrillPlayer({
3470
3516
  }
3471
3517
  },
3472
3518
  decompress: (format2, data) => decompress(format2, data),
3473
- crypto: createCrypto(),
3519
+ crypto: randomBytes === void 0 ? createCrypto() : { ...createCrypto(), randomBytes },
3474
3520
  formats: {
3475
3521
  async m3u(data) {
3476
3522
  const playlist = parseM3U(data);
@@ -3516,6 +3562,8 @@ function createKrillPlayer({
3516
3562
  return key;
3517
3563
  }
3518
3564
  },
3565
+ // 引擎一侧的实例化在 kernel_wasm.c;这里只按清单的名字给出核对过的字节。
3566
+ wasm: { module: (name2) => wasmModuleBytes(modules, name2) },
3519
3567
  i18n(text, values, context) {
3520
3568
  const checked = i18nArguments(text, values, context);
3521
3569
  return translate(localization, checked.text, checked.values, checked.context);
@@ -3530,6 +3578,14 @@ function appKeyFor(appKeys, name2) {
3530
3578
  const key = appKeys.keys[name2];
3531
3579
  return typeof key === "string" && key !== "" ? key : null;
3532
3580
  }
3581
+ async function wasmModuleBytes(modules, name2) {
3582
+ if (typeof name2 !== "string" || name2 === "") throw new TypeError("krillplayer.wasm.instantiate takes a non-empty module name");
3583
+ const module = modules?.declared.find((declared) => declared.name === name2);
3584
+ if (modules === null || module === void 0) throw new TypeError(`krillplayer.wasm: the manifest declares no module named ${name2}`);
3585
+ const bytes2 = await modules.bytes(module);
3586
+ if (bytes2 === null) throw new TypeError(`krillplayer.wasm: module ${name2} is not available`);
3587
+ return bytes2;
3588
+ }
3533
3589
  function toBytes(data) {
3534
3590
  return typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
3535
3591
  }
@@ -3545,7 +3601,8 @@ function responseHeaders(response, url) {
3545
3601
  if (cookies.length > 0) headers2["set-cookie"] = cookies.join("\n");
3546
3602
  return headers2;
3547
3603
  }
3548
- async function send(fetch, { url, method = "GET", headers: headers2 = {}, body }, use, grants, lookup2, limit = HTTP_LIMITS.responseBytes, tooLarge = `krillplayer.http: the response is larger than ${limit} bytes`) {
3604
+ async function send(fetch, { url, method = "GET", headers: headers2 = {}, body, redirect }, use, grants, lookup2, limit = HTTP_LIMITS.responseBytes, tooLarge = `krillplayer.http: the response is larger than ${limit} bytes`) {
3605
+ const follows = followsRedirects(redirect);
3549
3606
  const bytes2 = body === void 0 ? void 0 : toBytes(body);
3550
3607
  const chain = new Chain(use, grants);
3551
3608
  let pass = chain.first({ url, method, headers: headers2, body: bytes2 !== void 0 });
@@ -3563,7 +3620,7 @@ async function send(fetch, { url, method = "GET", headers: headers2 = {}, body }
3563
3620
  }
3564
3621
  }
3565
3622
  const location = response.headers.get("location");
3566
- if (!REDIRECT_STATUSES.has(response.status) || location === null) {
3623
+ if (!follows || !REDIRECT_STATUSES.has(response.status) || location === null) {
3567
3624
  return {
3568
3625
  response: { status: response.status, url: target, headers: responseHeaders(response, pass.address.href), body: await readBody(response, limit, tooLarge) },
3569
3626
  remember: chain.finished(response.status)
@@ -3574,6 +3631,11 @@ async function send(fetch, { url, method = "GET", headers: headers2 = {}, body }
3574
3631
  target = pass.address.href;
3575
3632
  }
3576
3633
  }
3634
+ function followsRedirects(redirect) {
3635
+ if (redirect === void 0 || redirect === null || redirect === "follow") return true;
3636
+ if (redirect === "manual") return false;
3637
+ throw new TypeError('krillplayer.http.request redirect must be "follow" or "manual"');
3638
+ }
3577
3639
  async function readBody(response, limit, message) {
3578
3640
  const declared = Number(response.headers.get("content-length") ?? "");
3579
3641
  const tooLarge = () => new TypeError(message);
@@ -3739,6 +3801,8 @@ function describe(schema) {
3739
3801
  return "true or false";
3740
3802
  case "bytes":
3741
3803
  return "a Uint8Array";
3804
+ case "json":
3805
+ return "a JSON value";
3742
3806
  case "constant":
3743
3807
  return JSON.stringify(schema.value);
3744
3808
  case "enum":
@@ -3782,6 +3846,8 @@ var Checker = class {
3782
3846
  case "bytes":
3783
3847
  if (!(value instanceof Uint8Array)) this.mismatch(schema, value, path);
3784
3848
  return;
3849
+ case "json":
3850
+ return this.json(value, path);
3785
3851
  case "constant":
3786
3852
  if (value !== schema.value) this.mismatch(schema, value, path);
3787
3853
  return;
@@ -3801,6 +3867,20 @@ var Checker = class {
3801
3867
  return this.union(schema, value, path);
3802
3868
  }
3803
3869
  }
3870
+ // 任意的 JSON 值:逐层查,字节、undefined、函数与非有限的数都不是。
3871
+ json(value, path) {
3872
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
3873
+ if (typeof value === "number") {
3874
+ if (!Number.isFinite(value)) this.report(path, `is ${shown(value)}, expected a JSON value`, "write a finite number");
3875
+ return;
3876
+ }
3877
+ if (Array.isArray(value)) return value.forEach((item, index) => this.json(item, `${path}[${index}]`));
3878
+ if (isPlainObject(value)) {
3879
+ for (const [key, item] of Object.entries(value)) if (item !== void 0) this.json(item, `${path}[${JSON.stringify(key)}]`);
3880
+ return;
3881
+ }
3882
+ this.report(path, `is ${shown(value)}, expected a JSON value`, value instanceof Uint8Array ? "encode the bytes as a string, e.g. hex or base64" : "drop it");
3883
+ }
3804
3884
  // 标量类型不对:按常见的写错法给改法。
3805
3885
  mismatch(schema, value, path) {
3806
3886
  this.report(path, `is ${shown(value)}, expected ${describe(schema)}`, scalarFix(schema, value));
@@ -4187,7 +4267,29 @@ var SECRET_VALUES = [
4187
4267
  /\beyJ[\w-]{8,}\.eyJ[\w-]{8,}\.[\w-]+/,
4188
4268
  /\b(?:access_key|access_token)=(?!(?:REDACTED-0{10}|REDACTED)(?![\w.-]))[\w.-]{16,}/
4189
4269
  ];
4190
- var COOKIE_ATTRIBUTES = /* @__PURE__ */ new Set(["path", "domain", "expires", "max-age", "samesite", "secure", "httponly", "partitioned", "priority"]);
4270
+ var DAY = "(?:mon|tues?|wed(?:nes)?|thu(?:rs)?|fri|sat(?:ur)?|sun)(?:day)?";
4271
+ var MONTH = "(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)";
4272
+ var TIME = "\\d{1,2}:\\d{2}:\\d{2}";
4273
+ var HTTP_DATE = new RegExp(`^(?:(?:${DAY},?\\s+)?\\d{1,2}[ -]${MONTH}[ -]\\d{2,4}\\s+${TIME}(?:\\s+(?:gmt|utc|[+-]\\d{4}))?|${DAY}\\s+${MONTH}\\s+\\d{1,2}\\s+${TIME}\\s+\\d{4})$`, "i");
4274
+ var HOSTNAME = /^\.?[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*\.?$/i;
4275
+ var holdsCredential = (value, separator) => SECRET_VALUES.some((pattern) => pattern.test(value)) || value.split(separator).some(looksLikeToken);
4276
+ var flag = () => false;
4277
+ var COOKIE_ATTRIBUTES = /* @__PURE__ */ new Map([
4278
+ ["expires", (value) => HTTP_DATE.test(value)],
4279
+ ["max-age", (value) => /^-?\d+$/.test(value)],
4280
+ ["samesite", (value) => /^(?:strict|lax|none)$/i.test(value)],
4281
+ ["priority", (value) => /^(?:low|medium|high)$/i.test(value)],
4282
+ ["path", (value) => value.startsWith("/") && !holdsCredential(value, "/")],
4283
+ ["domain", (value) => HOSTNAME.test(value) && !holdsCredential(value, ".")],
4284
+ ["secure", flag],
4285
+ ["httponly", flag],
4286
+ ["partitioned", flag]
4287
+ ]);
4288
+ function isCookieAttribute(name2, value) {
4289
+ const shape = COOKIE_ATTRIBUTES.get(name2);
4290
+ const trimmed = value?.trim();
4291
+ return shape !== void 0 && (trimmed === void 0 || trimmed === "" || shape(trimmed));
4292
+ }
4191
4293
  function setCookieValueRanges(line) {
4192
4294
  const ranges = [];
4193
4295
  let start = 0;
@@ -4198,7 +4300,7 @@ function setCookieValueRanges(line) {
4198
4300
  if (index === 0) {
4199
4301
  if (equals < 0) return void 0;
4200
4302
  ranges.push([start + equals + 1, end]);
4201
- } else if (segment.trim() !== "" && !COOKIE_ATTRIBUTES.has(name2)) {
4303
+ } else if (segment.trim() !== "" && !isCookieAttribute(name2, equals < 0 ? void 0 : segment.slice(equals + 1))) {
4202
4304
  ranges.push(equals < 0 ? [start + segment.length - segment.trimStart().length, end] : [start + equals + 1, end]);
4203
4305
  }
4204
4306
  start = end + 1;
@@ -4427,6 +4529,42 @@ function replayFetch(exchanges) {
4427
4529
  };
4428
4530
  return { fetch, pending, unrecorded };
4429
4531
  }
4532
+ function clockProblem(clock) {
4533
+ return Number.isSafeInteger(clock) && Math.abs(clock) <= 864e13 ? void 0 : "clock must be the epoch time in milliseconds, an integer";
4534
+ }
4535
+ var BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
4536
+ function randomProblem(random) {
4537
+ return isBytesJSON(random) && BASE64.test(random.$bytes) ? void 0 : 'random must be {"$bytes": "<base64>"}';
4538
+ }
4539
+ var checkedLength = (length) => globalThis.crypto.getRandomValues(new Uint8Array(length));
4540
+ function replayRandom(random) {
4541
+ const bytes2 = new Uint8Array(Buffer.from(random.$bytes, "base64"));
4542
+ const problems = [];
4543
+ let offset = 0;
4544
+ const draw = (length) => {
4545
+ const wanted = checkedLength(length).length;
4546
+ if (offset + wanted > bytes2.length) {
4547
+ const problem = `random ran out: the plugin drew ${wanted} more byte(s) after ${offset}, the case's random holds ${bytes2.length}; record the case again`;
4548
+ problems.push(problem);
4549
+ throw new Error(problem);
4550
+ }
4551
+ offset += wanted;
4552
+ return bytes2.slice(offset - wanted, offset);
4553
+ };
4554
+ return {
4555
+ draw,
4556
+ problems: () => [...problems, ...problems.length === 0 && offset < bytes2.length ? [`random has ${bytes2.length - offset} byte(s) the plugin did not draw`] : []]
4557
+ };
4558
+ }
4559
+ function recordingRandom() {
4560
+ const drawn = [];
4561
+ const draw = (length) => {
4562
+ const bytes2 = checkedLength(length);
4563
+ drawn.push(bytes2.slice());
4564
+ return bytes2;
4565
+ };
4566
+ return { draw, bytes: () => Buffer.concat(drawn) };
4567
+ }
4430
4568
  var TRANSPORT_HEADERS = /* @__PURE__ */ new Set(["content-encoding", "content-length", "transfer-encoding", "connection", "keep-alive"]);
4431
4569
  function recordingFetch(fetch) {
4432
4570
  const exchanges = [];
@@ -4461,7 +4599,7 @@ async function readCases(directory) {
4461
4599
  }));
4462
4600
  }
4463
4601
  var frameJSON = (frame2) => frame2.data === void 0 ? { text: frame2.text ?? "" } : { data: bytesToJSON(frame2.data) };
4464
- var frameOf = (json) => "data" in json ? { data: new Uint8Array(Buffer.from(json.data.$bytes, "base64")) } : { text: json.text };
4602
+ var frameOf = (json2) => "data" in json2 ? { data: new Uint8Array(Buffer.from(json2.data.$bytes, "base64")) } : { text: json2.text };
4465
4603
  function scriptedSockets(script) {
4466
4604
  const problems = [];
4467
4605
  let opened = false;
@@ -4622,18 +4760,18 @@ function encode(value) {
4622
4760
  }
4623
4761
  return item;
4624
4762
  };
4625
- const json = JSON.stringify(plain(value)) ?? "null";
4763
+ const json2 = JSON.stringify(plain(value)) ?? "null";
4626
4764
  const blob = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));
4627
4765
  let offset = 0;
4628
4766
  for (const part of parts) {
4629
4767
  blob.set(part, offset);
4630
4768
  offset += part.length;
4631
4769
  }
4632
- return [`[${json},${JSON.stringify(parts.map((part) => part.length))}]`, blob];
4770
+ return [`[${json2},${JSON.stringify(parts.map((part) => part.length))}]`, blob];
4633
4771
  }
4634
- function decode(json, blob) {
4635
- if (nestedTooDeep(json)) throw new TypeError(`krillplayer: a message from the plugin is nested deeper than ${VALUE_LIMITS.depth} levels`);
4636
- const [message, sizes] = JSON.parse(json);
4772
+ function decode(json2, blob) {
4773
+ if (nestedTooDeep(json2)) throw new TypeError(`krillplayer: a message from the plugin is nested deeper than ${VALUE_LIMITS.depth} levels`);
4774
+ const [message, sizes] = JSON.parse(json2);
4637
4775
  const parts = [];
4638
4776
  let offset = 0;
4639
4777
  for (const size of sizes) {
@@ -4672,9 +4810,28 @@ async function files(directory) {
4672
4810
  return entries.filter((entry) => entry.isFile()).map((entry) => join3(entry.parentPath, entry.name)).sort();
4673
4811
  }
4674
4812
  var DRIVER = join3(here, "engine/engine.c");
4675
- async function engineSourceHash(quickjs = join3(kernelDirectory(), "Sources/CQuickJS")) {
4676
- const hash = createHash("sha256").update(JSON.stringify(FLAGS)).update("engine.c").update(await readFile3(DRIVER));
4677
- for (const file of await files(quickjs)) hash.update(relative2(quickjs, file)).update(await readFile3(file));
4813
+ var WAMR_FLAGS = ["-O2", "-w"];
4814
+ function wamrIncludes(wamr) {
4815
+ const core = join3(wamr, "vendor/core");
4816
+ const platform = process.platform === "linux" ? "linux" : "darwin";
4817
+ return [
4818
+ join3(wamr, "include"),
4819
+ "iwasm/include",
4820
+ "iwasm/common",
4821
+ "iwasm/interpreter",
4822
+ "iwasm/libraries/thread-mgr",
4823
+ "shared/utils",
4824
+ "shared/mem-alloc",
4825
+ "shared/platform/include",
4826
+ `shared/platform/${platform}`
4827
+ ].map((directory, index) => `-I${index === 0 ? directory : join3(core, directory)}`);
4828
+ }
4829
+ async function engineSourceHash(kernel = kernelDirectory()) {
4830
+ const hash = createHash("sha256").update(JSON.stringify([FLAGS, WAMR_FLAGS])).update("engine.c").update(await readFile3(DRIVER));
4831
+ for (const target of ["CQuickJS", "CWAMR"]) {
4832
+ const directory = join3(kernel, "Sources", target);
4833
+ for (const file of await files(directory)) hash.update(join3(target, relative2(directory, file))).update(await readFile3(file));
4834
+ }
4678
4835
  return hash.digest("hex");
4679
4836
  }
4680
4837
  var ENGINE_PACKAGE = (platform = process.platform, arch = process.arch) => `@krillplayer/plugin-engine-${platform}-${arch}`;
@@ -4698,36 +4855,56 @@ async function executable(file) {
4698
4855
  }
4699
4856
  var environment = (name2) => process.env[name2] || void 0;
4700
4857
  async function build() {
4701
- const quickjs = join3(kernelDirectory(), "Sources/CQuickJS");
4858
+ const kernel = join3(kernelDirectory(), "Sources");
4702
4859
  const compiler = environment("CC") ?? "cc";
4703
- const source = await engineSourceHash(quickjs).catch((error) => {
4704
- throw new EngineFailure(`could not read the QuickJS-ng engine sources in ${quickjs}: ${error.message}`);
4860
+ const source = await engineSourceHash().catch((error) => {
4861
+ throw new EngineFailure(`could not read the QuickJS-ng engine sources in ${kernel}: ${error.message}`);
4705
4862
  });
4706
4863
  const found = await prebuilt(source);
4707
4864
  if (found !== void 0) return found;
4708
4865
  try {
4709
- return await compile(quickjs, compiler, source);
4866
+ return await compile(compiler, source);
4710
4867
  } catch (error) {
4711
- throw new EngineFailure(`could not compile the QuickJS-ng engine from ${quickjs} with ${compiler} (needs a C compiler): ${error.message}`);
4868
+ throw new EngineFailure(`could not compile the QuickJS-ng engine from ${kernel} with ${compiler} (needs a C compiler): ${error.message}`);
4712
4869
  }
4713
4870
  }
4714
4871
  async function compileEngine(output, { compiler = environment("CC") ?? "cc", arch } = {}) {
4715
4872
  const quickjs = join3(kernelDirectory(), "Sources/CQuickJS");
4716
- await run3(compiler, [
4717
- ...FLAGS,
4718
- ...arch === void 0 ? [] : ["-arch", arch],
4719
- `-I${join3(quickjs, "include")}`,
4720
- `-I${quickjs}`,
4721
- DRIVER,
4722
- join3(quickjs, "kernel_qjs.c"),
4723
- join3(quickjs, "quickjs_vendor.c"),
4724
- "-lm",
4725
- "-lpthread",
4726
- "-o",
4727
- output
4728
- ], { maxBuffer: 16 << 20 });
4729
- }
4730
- async function compile(quickjs, compiler, source) {
4873
+ const wamr = join3(kernelDirectory(), "Sources/CWAMR");
4874
+ const target = arch === void 0 ? [] : ["-arch", arch];
4875
+ const objects = await mkdtemp(join3(dirname(output), "wamr-"));
4876
+ try {
4877
+ const wrappers = (await readdir2(wamr)).filter((name2) => /^wamr_.*\.c$/.test(name2)).sort();
4878
+ await Promise.all(wrappers.map((name2) => run3(compiler, [
4879
+ ...WAMR_FLAGS,
4880
+ ...target,
4881
+ ...wamrIncludes(wamr),
4882
+ "-c",
4883
+ join3(wamr, name2),
4884
+ "-o",
4885
+ join3(objects, `${name2}.o`)
4886
+ ], { maxBuffer: 16 << 20 })));
4887
+ await run3(compiler, [
4888
+ ...FLAGS,
4889
+ ...target,
4890
+ `-I${join3(quickjs, "include")}`,
4891
+ `-I${quickjs}`,
4892
+ `-I${join3(wamr, "include")}`,
4893
+ DRIVER,
4894
+ join3(quickjs, "kernel_qjs.c"),
4895
+ join3(quickjs, "kernel_wasm.c"),
4896
+ join3(quickjs, "quickjs_vendor.c"),
4897
+ ...wrappers.map((name2) => join3(objects, `${name2}.o`)),
4898
+ "-lm",
4899
+ "-lpthread",
4900
+ "-o",
4901
+ output
4902
+ ], { maxBuffer: 16 << 20 });
4903
+ } finally {
4904
+ await rm(objects, { recursive: true, force: true });
4905
+ }
4906
+ }
4907
+ async function compile(compiler, source) {
4731
4908
  const version = (await run3(compiler, ["--version"])).stdout;
4732
4909
  const key = createHash("sha256").update(source).update(version).digest("hex");
4733
4910
  const cache = environment("KRILLPLAYER_ENGINE_CACHE") ?? join3(environment("XDG_CACHE_HOME") ?? join3(homedir(), ".cache"), "krillplayer-plugin/engine");
@@ -4764,6 +4941,16 @@ function preludeSource() {
4764
4941
  );
4765
4942
  return prelude;
4766
4943
  }
4944
+ var pinsTemplate;
4945
+ async function pinnedPrelude(pins) {
4946
+ const path = join3(kernelDirectory(), "Tests/KernelTests/CasePins.js");
4947
+ pinsTemplate ??= readFile3(path, "utf8").catch((error) => {
4948
+ throw new EngineFailure(`could not read the case pins ${path}: ${error.message}`);
4949
+ });
4950
+ const template = await pinsTemplate;
4951
+ const source = await preludeSource();
4952
+ return template.replaceAll("__CLOCK__", pins.clock === null ? "null" : String(pins.clock)).replaceAll("__RANDOM__", String(pins.random)).replace("__PRELUDE__", () => source);
4953
+ }
4767
4954
  var KQ_OK = 0;
4768
4955
  var KQ_INTERRUPTED = 2;
4769
4956
  var KQ_OUT_OF_MEMORY = 3;
@@ -4839,11 +5026,12 @@ var EngineProcess = class {
4839
5026
  this.#pending = void 0;
4840
5027
  }
4841
5028
  // remaining 是距期限的秒数;0 表示不设期限。
4842
- op(tag, remaining, a = "", b = "") {
5029
+ // W 帧的 number 是模块的字节数,不是期限。
5030
+ op(tag, remaining, a = "", b = "", size = 0) {
4843
5031
  if (this.#exit) return Promise.reject(this.#exit);
4844
5032
  return new Promise((resolve4, reject) => {
4845
5033
  this.#pending = { resolve: resolve4, reject };
4846
- this.#child.stdin.write(frame(tag, remaining, a, b));
5034
+ this.#child.stdin.write(frame(tag, tag === "W" ? size : remaining, a, b));
4847
5035
  });
4848
5036
  }
4849
5037
  close() {
@@ -4858,9 +5046,9 @@ var EngineProcess = class {
4858
5046
  this.#pending = void 0;
4859
5047
  pending?.resolve({ status: number2, error: a.toString("utf8") });
4860
5048
  } else if (tag === "H") {
4861
- const json = a.toString("utf8");
5049
+ const json2 = a.toString("utf8");
4862
5050
  this.#queue = this.#queue.then(async () => {
4863
- const reply = await this.#host(json, b);
5051
+ const reply = await this.#host(json2, b);
4864
5052
  this.#child.stdin.write("error" in reply ? frame("e", 0, reply.error, "") : frame("h", 0, reply.json, reply.blob));
4865
5053
  });
4866
5054
  }
@@ -4907,7 +5095,7 @@ var CALLS = {
4907
5095
  const value = k.cache.get(key);
4908
5096
  return value === null ? null : JSON.stringify(value);
4909
5097
  },
4910
- "cache.set": (k, [key, json, ttl]) => k.cache.set(key, JSON.parse(json), ttl),
5098
+ "cache.set": (k, [key, json2, ttl]) => k.cache.set(key, JSON.parse(json2), ttl),
4911
5099
  "storage.get": (k, [key]) => storage(k).get(key),
4912
5100
  "storage.set": (k, [key, value]) => storage(k).set(key, value),
4913
5101
  "storage.delete": (k, [key]) => storage(k).delete(key),
@@ -4921,6 +5109,7 @@ var CALLS = {
4921
5109
  var STARTS = {
4922
5110
  "http.request": (k, [request]) => k.http.request(request),
4923
5111
  "appKeys.get": (k, [name2]) => k.appKeys.get(name2),
5112
+ "wasm.module": (k, [name2]) => k.wasm.module(name2),
4924
5113
  "formats.xmltv.channels": (k, [source]) => k.formats.xmltv.channels(source),
4925
5114
  "formats.xmltv.programmes": (k, [source, query]) => k.formats.xmltv.programmes(source, query),
4926
5115
  "metadata.search": (k, [kind, query, options]) => k.metadata.search(kind, query, options),
@@ -4951,13 +5140,16 @@ var EngineContext = class _EngineContext {
4951
5140
  this.#krillplayer = options.krillplayer;
4952
5141
  this.#slot = options.slot;
4953
5142
  this.#limits = options.limits ?? KERNEL_LIMITS;
4954
- this.#process = new EngineProcess(path, this.#limits, (json, blob) => this.#host(json, blob));
5143
+ this.#process = new EngineProcess(path, this.#limits, (json2, blob) => this.#host(json2, blob));
4955
5144
  }
4956
5145
  static async open(options) {
4957
5146
  const context = new _EngineContext(await engineBinary(), options);
4958
5147
  try {
4959
5148
  context.#deadline = now() + context.#limits.callSeconds;
4960
- await context.#enter("I", await preludeSource());
5149
+ for (const module of options.modules ?? []) {
5150
+ if (/^[0-9a-f]{64}$/.test(module.sha256)) await context.#enter("W", module.name, Buffer.from(module.sha256, "hex"), module.size);
5151
+ }
5152
+ await context.#enter("I", options.pins === void 0 ? await preludeSource() : await pinnedPrelude(options.pins));
4961
5153
  await context.#enter("M", options.source, options.name);
4962
5154
  return context;
4963
5155
  } catch (error) {
@@ -5013,13 +5205,13 @@ var EngineContext = class _EngineContext {
5013
5205
  });
5014
5206
  }
5015
5207
  #dispatch(message) {
5016
- const [json, blob] = encode(message);
5017
- return this.#enter("D", json, blob);
5208
+ const [json2, blob] = encode(message);
5209
+ return this.#enter("D", json2, blob);
5018
5210
  }
5019
5211
  // 进引擎的唯一入口:期限每次重设;跑过期限或超了内存就关掉子进程并停用这个上下文。
5020
- async #enter(tag, a = "", b = "") {
5212
+ async #enter(tag, a = "", b = "", size = 0) {
5021
5213
  if (this.#breach) throw new EngineError({ stopped: this.#breach });
5022
- const { status, error } = await this.#process.op(tag, Math.max(this.#deadline - now(), 1e-6), a, b);
5214
+ const { status, error } = await this.#process.op(tag, Math.max(this.#deadline - now(), 1e-6), a, b, size);
5023
5215
  if (status === KQ_OK) return;
5024
5216
  if (status === KQ_INTERRUPTED || status === KQ_OUT_OF_MEMORY) {
5025
5217
  this.#breach = status === KQ_INTERRUPTED ? "timeout" : "memory";
@@ -5028,9 +5220,9 @@ var EngineContext = class _EngineContext {
5028
5220
  }
5029
5221
  throw new EngineError({ threw: error });
5030
5222
  }
5031
- async #host(json, blob) {
5223
+ async #host(json2, blob) {
5032
5224
  try {
5033
- const [replyJSON, replyBlob] = encode(await this.#handle(decode(json, blob)));
5225
+ const [replyJSON, replyBlob] = encode(await this.#handle(decode(json2, blob)));
5034
5226
  return { json: replyJSON, blob: replyBlob };
5035
5227
  } catch (error) {
5036
5228
  return { error: error instanceof Error ? error.message : `krillplayer: ${String(error)}` };
@@ -5364,7 +5556,7 @@ function checkPlugin(source) {
5364
5556
  var RESERVED_PARAMETER_PREFIX = "krillplayer.files.";
5365
5557
  function checkManifest(manifest) {
5366
5558
  const parameters = Array.isArray(manifest.parameters) ? manifest.parameters : [];
5367
- const problems = [];
5559
+ const problems = checkModules(manifest.modules, manifest.hosts);
5368
5560
  if (manifest.loginRequired === true && Array.isArray(manifest.capabilities) && !manifest.capabilities.includes("login")) {
5369
5561
  problems.push("loginRequired needs a login slot: export login so the user can log in when adding a source, or drop loginRequired");
5370
5562
  }
@@ -5388,6 +5580,35 @@ function checkManifest(manifest) {
5388
5580
  }
5389
5581
  return problems;
5390
5582
  }
5583
+ function checkModules(modules, hosts) {
5584
+ if (!Array.isArray(modules)) return [];
5585
+ const declaredHosts = new Set((Array.isArray(hosts) ? hosts : []).filter((host) => typeof host === "string").map((host) => host.toLowerCase()));
5586
+ const problems = [];
5587
+ if (modules.length > WASM_LIMITS.modules) {
5588
+ problems.push(`modules declares ${modules.length} WebAssembly modules; a plugin may declare at most ${WASM_LIMITS.modules}`);
5589
+ }
5590
+ const seen = /* @__PURE__ */ new Set();
5591
+ for (const module of modules) {
5592
+ if (typeof module !== "object" || module === null) continue;
5593
+ const { name: name2, url, sha256, size } = module;
5594
+ const label = `module ${String(name2)}`;
5595
+ if (typeof name2 === "string") {
5596
+ if (name2 === "") problems.push("a module in modules has an empty name");
5597
+ if (seen.has(name2)) problems.push(`${label} is declared twice in modules`);
5598
+ seen.add(name2);
5599
+ }
5600
+ if (typeof url === "string") {
5601
+ const parsed = URL.canParse(url) ? new URL(url) : void 0;
5602
+ if (parsed?.protocol !== "https:") problems.push(`${label}: url ${url} must be an https URL`);
5603
+ else if (!declaredHosts.has(parsed.hostname)) problems.push(`${label}: url host ${parsed.hostname} must be listed in hosts`);
5604
+ }
5605
+ if (typeof sha256 === "string" && !/^[0-9a-f]{64}$/.test(sha256)) problems.push(`${label}: sha256 must be 64 lowercase hexadecimal digits`);
5606
+ if (typeof size === "number" && !(Number.isInteger(size) && size > 0 && size <= WASM_LIMITS.moduleBytes)) {
5607
+ problems.push(`${label}: size ${size} must be a whole number of bytes from 1 to ${WASM_LIMITS.moduleBytes} (8 MiB)`);
5608
+ }
5609
+ }
5610
+ return problems;
5611
+ }
5391
5612
 
5392
5613
  // trial-runner/trial.ts
5393
5614
  async function readFiles(path) {
@@ -5406,6 +5627,22 @@ async function readFiles(path) {
5406
5627
  }));
5407
5628
  }
5408
5629
  var LOCALES = "locales";
5630
+ var MODULES = "modules";
5631
+ function localModules(plugin2) {
5632
+ return {
5633
+ declared: plugin2.modules,
5634
+ bytes: async (module) => {
5635
+ if (plugin2.moduleDirectory === void 0) return null;
5636
+ return readFile4(join4(plugin2.moduleDirectory, `${module.name}.wasm`)).then(
5637
+ (data) => new Uint8Array(data),
5638
+ (error) => {
5639
+ if (error.code === "ENOENT") return null;
5640
+ throw error;
5641
+ }
5642
+ );
5643
+ }
5644
+ };
5645
+ }
5409
5646
  function dictionariesIn(files2) {
5410
5647
  return Object.fromEntries([...files2].flatMap(([name2, text]) => {
5411
5648
  const match = /^locales\/([^/]+)\.json$/.exec(name2);
@@ -5429,6 +5666,8 @@ async function readPlugin(path) {
5429
5666
  parameters: manifest.parameters ?? [],
5430
5667
  appKeys: manifest.appKeys ?? [],
5431
5668
  files: manifest.files,
5669
+ modules: Array.isArray(manifest.modules) ? manifest.modules : [],
5670
+ ...path.endsWith(".zip") ? {} : { moduleDirectory: join4(path, MODULES) },
5432
5671
  language: manifest.language,
5433
5672
  dictionaries: dictionariesIn(files2),
5434
5673
  exports: checked.exports,
@@ -5448,7 +5687,7 @@ function skipReason(testCase) {
5448
5687
  if (testCase.slot === "status" && testCase.credentials) return "status with credentials runs only in the App kernel";
5449
5688
  return void 0;
5450
5689
  }
5451
- function openSlot(plugin2, testCase, fetch, credentials, onWrite, metadata = scriptedMetadata(testCase.metadata), files2 = scriptedFiles(testCase.files)) {
5690
+ function openSlot(plugin2, testCase, fetch, credentials, onWrite, metadata = scriptedMetadata(testCase.metadata), files2 = scriptedFiles(testCase.files), pins) {
5452
5691
  const parameters = testCase.parameters ?? null;
5453
5692
  const krillplayer = createKrillPlayer({
5454
5693
  fetch,
@@ -5460,19 +5699,28 @@ function openSlot(plugin2, testCase, fetch, credentials, onWrite, metadata = scr
5460
5699
  parameters,
5461
5700
  secrets: plugin2.parameters.filter((parameter) => parameter.secret).map((parameter) => parameter.name),
5462
5701
  appKeys: testCase.appKeys === void 0 ? null : { declared: plugin2.appKeys, keys: testCase.appKeys },
5702
+ modules: localModules(plugin2),
5463
5703
  cache: createCache().scope({ pluginId: plugin2.id, sourceId: plugin2.id }),
5464
5704
  storage: createStorage().scope({ pluginId: plugin2.id, sourceId: plugin2.id }),
5465
5705
  credentials: testCase.slot === "status" ? null : credentials,
5466
5706
  ...testCase.slot === "status" ? {} : { writeCredentials: onWrite },
5467
5707
  metadata: metadata.service,
5468
5708
  ...plugin2.files === void 0 ? {} : { files: { protocol: plugin2.files, service: files2.service } },
5469
- localization: { locale: testCase.locale ?? plugin2.language ?? "en", language: plugin2.language, dictionaries: plugin2.dictionaries }
5709
+ localization: { locale: testCase.locale ?? plugin2.language ?? "en", language: plugin2.language, dictionaries: plugin2.dictionaries },
5710
+ ...pins?.random === void 0 ? {} : { randomBytes: pins.random }
5711
+ });
5712
+ return EngineContext.open({
5713
+ source: plugin2.source,
5714
+ name: plugin2.name,
5715
+ krillplayer,
5716
+ modules: plugin2.modules,
5717
+ slot: testCase.slot,
5718
+ ...pins === void 0 ? {} : { pins: { clock: pins.clock, random: pins.random !== void 0 } }
5470
5719
  });
5471
- return EngineContext.open({ source: plugin2.source, name: plugin2.name, krillplayer, slot: testCase.slot });
5472
5720
  }
5473
5721
  async function invokeSlot(plugin2, testCase, fetch, credentials, onWrite = () => {
5474
- }) {
5475
- const context = await openSlot(plugin2, testCase, fetch, credentials, onWrite);
5722
+ }, pins) {
5723
+ const context = await openSlot(plugin2, testCase, fetch, credentials, onWrite, void 0, void 0, pins);
5476
5724
  try {
5477
5725
  return await context.call(testCase.slot, testCase.call ?? "", testCase.args.map(fromJSON));
5478
5726
  } finally {
@@ -5488,9 +5736,17 @@ function describeError(error) {
5488
5736
  function contractProblems(testCase, output) {
5489
5737
  return validateOutput(testCase.slot, testCase.call ?? "", output).map((problem) => `contract: ${problem}`);
5490
5738
  }
5739
+ var UNPINNED_HINT = "if the address or body carries a timestamp or a random value, the case needs clock and random: record it again, record writes them";
5491
5740
  async function runSlotCase(plugin2, testCase) {
5492
5741
  const skip = skipReason(testCase);
5493
5742
  if (skip) return { status: "skipped", reason: skip };
5743
+ const malformed = [
5744
+ testCase.clock === void 0 ? void 0 : clockProblem(testCase.clock),
5745
+ testCase.random === void 0 ? void 0 : randomProblem(testCase.random)
5746
+ ].filter((problem) => problem !== void 0);
5747
+ if (malformed.length > 0) return { status: "failed", reason: malformed.join("\n ") };
5748
+ const random = testCase.random === void 0 ? void 0 : replayRandom(testCase.random);
5749
+ const pins = testCase.clock === void 0 && random === void 0 ? void 0 : { clock: testCase.clock ?? null, random: random?.draw };
5494
5750
  const replay = replayFetch(testCase.exchanges ?? []);
5495
5751
  const metadata = scriptedMetadata(testCase.metadata);
5496
5752
  const files2 = scriptedFiles(testCase.files);
@@ -5500,7 +5756,7 @@ async function runSlotCase(plugin2, testCase) {
5500
5756
  const sockets = scriptedSockets(testCase.socket);
5501
5757
  const context = await openSlot(plugin2, testCase, replay.fetch, testCase.credentials ?? null, (write) => {
5502
5758
  written = write;
5503
- }, metadata, files2);
5759
+ }, metadata, files2, pins);
5504
5760
  try {
5505
5761
  const value = await context.call(testCase.slot, testCase.call ?? "", testCase.args.map(fromJSON));
5506
5762
  const contract = contractProblems(testCase, value);
@@ -5535,10 +5791,12 @@ async function runSlotCase(plugin2, testCase) {
5535
5791
  }
5536
5792
  problems.push(
5537
5793
  ...replay.unrecorded.map((request) => `unrecorded request ${request}`),
5794
+ ...replay.unrecorded.length > 0 && testCase.clock === void 0 ? [UNPINNED_HINT] : [],
5538
5795
  ...replay.pending.map(({ request }) => `recorded request not sent ${request.method} ${request.url}`),
5539
5796
  ...metadata.problems(),
5540
5797
  ...files2.problems(),
5541
- ...sockets.problems()
5798
+ ...sockets.problems(),
5799
+ ...random?.problems() ?? []
5542
5800
  );
5543
5801
  if ("output" in outcome) {
5544
5802
  if (testCase.error !== void 0) problems.push(`should throw ${canonical(testCase.error)}, returned ${canonical(outcome.output)}`);
@@ -5620,7 +5878,11 @@ async function recordCommand(pluginDirectory, { slot, call: callName, args, cred
5620
5878
  }
5621
5879
  return { output: toJSON(value) };
5622
5880
  };
5623
- await settle(invokeSlot(plugin2, { slot, call: callName, args, parameters, appKeys, output: null }, recording.fetch, credentials));
5881
+ const clock = Date.now();
5882
+ const drawn = recordingRandom();
5883
+ await settle(invokeSlot(plugin2, { slot, call: callName, args, parameters, appKeys, output: null }, recording.fetch, credentials, void 0, { clock, random: drawn.draw }));
5884
+ const randomBytes = drawn.bytes();
5885
+ const random = randomBytes.length === 0 ? void 0 : bytesToJSON(randomBytes);
5624
5886
  const own = credentials === null ? [] : Object.values(credentials).filter((value) => typeof value === "string" && value !== "").map((value, index) => ({ value, fake: fakeValue(value, index) }));
5625
5887
  const redacted = credentials === null ? null : Object.fromEntries(Object.entries(credentials).map(([key, value]) => [key, typeof value === "string" ? withOwnValuesReplaced(value, own) : REDACTED]));
5626
5888
  const keptArgs = withOwnValuesReplaced(args, own);
@@ -5638,7 +5900,19 @@ async function recordCommand(pluginDirectory, { slot, call: callName, args, cred
5638
5900
  if (unacceptable.length > 0) throw new RecordRefused(`a request body cannot be replayed the same way on both runners, nothing was recorded:
5639
5901
  ${unacceptable.join("\n ")}`);
5640
5902
  const replay = replayFetch(exchanges);
5641
- const outcome = await settle(invokeSlot(plugin2, { slot, call: callName, args: keptArgs, parameters: kept, appKeys: keptKeys, output: null }, replay.fetch, redacted));
5903
+ const replayedRandom = replayRandom(random ?? { $bytes: "" });
5904
+ const outcome = await settle(invokeSlot(
5905
+ plugin2,
5906
+ { slot, call: callName, args: keptArgs, parameters: kept, appKeys: keptKeys, output: null },
5907
+ replay.fetch,
5908
+ redacted,
5909
+ void 0,
5910
+ { clock, random: replayedRandom.draw }
5911
+ ));
5912
+ if (replayedRandom.problems().length > 0) {
5913
+ throw new RecordRefused(`replaying with the credentials replaced drew random bytes differently, nothing was recorded:
5914
+ ${replayedRandom.problems().join("\n ")}`);
5915
+ }
5642
5916
  const testCase = {
5643
5917
  slot,
5644
5918
  ...callName === void 0 ? {} : { call: callName },
@@ -5646,6 +5920,8 @@ async function recordCommand(pluginDirectory, { slot, call: callName, args, cred
5646
5920
  ...redacted === null ? {} : { credentials: redacted },
5647
5921
  ...kept === void 0 ? {} : { parameters: kept },
5648
5922
  ...keptKeys === void 0 ? {} : { appKeys: keptKeys },
5923
+ clock,
5924
+ ...random === void 0 ? {} : { random },
5649
5925
  exchanges,
5650
5926
  ...outcome
5651
5927
  };
@@ -6050,6 +6326,8 @@ var COMMANDS = {
6050
6326
  " call the real service once, redact credentials, replay the recording and save it as a case",
6051
6327
  " a krillplayer.error thrown by the plugin is saved as the case's error; nothing is written when the output",
6052
6328
  " breaks the contract, the plugin throws anything else, or the redacted case still looks like it holds credentials",
6329
+ " the case pins the clock to when recording started and keeps the random bytes the plugin drew (clock, random),",
6330
+ " so requests signed with a timestamp or a nonce replay the same",
6053
6331
  " --slot <slot> browse, play, status, ...; for the top-level resolve write resolve and no --call",
6054
6332
  " --call <fn> the function in the slot, e.g. list",
6055
6333
  ` --args <json> the arguments after krillplayer, as a JSON array, e.g. '[{}]' or '[{}, "<next>"]'`,