krillplayer-plugin 0.5.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 +2 -0
  3. package/dist/cli.js +397 -80
  4. package/dist/crypto.js +38 -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 +46 -0
  144. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/play-live-selected-line-gone.json +46 -0
  145. package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/play-live.json +21 -1
  146. package/skill/krillplayer-plugin/assets/samples/live-video-platform/plugin.ts +39 -4
  147. package/skill/krillplayer-plugin/references/cases.md +20 -2
  148. package/skill/krillplayer-plugin/references/contract.d.ts +114 -12
  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,16 +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
- streams: array(PlayableStream)
427
+ streams: array(PlayableStream),
428
+ qualities: optional(array(string)),
429
+ loginQualities: optional(array(string))
400
430
  });
401
431
  var Playable = object("Playable", {
402
432
  timing: enumeration("PlayableTiming", ["live", "onDemand"]),
@@ -411,11 +441,7 @@ var Playable = object("Playable", {
411
441
  end: number,
412
442
  title: optional(string)
413
443
  }))),
414
- decryption: optional(object("PlayableDecryption", {
415
- method: enumeration("PlayableDecryptionMethod", ["cencAesCtr"]),
416
- key: string,
417
- keyId: optional(string)
418
- })),
444
+ decryption: optional(PlayableDecryption),
419
445
  subtitles: optional(array(PlayableSubtitle)),
420
446
  // 这一路的原始文件名,给字幕插件与弹幕插件匹配用(contract.md 3.1);不给时内核用条目的文件名或标题。
421
447
  filename: optional(string)
@@ -819,6 +845,8 @@ var SLOT_RULES = {
819
845
  // 组件页面 page 去掉了(ADR 0040),剩下播放器面板与卡片操作,都交数据(#753)。面板与操作各一项能力,
820
846
  // 不再是 views:交组件格式的旧插件打的是 views,新内核不认识、跳过,不会按数据去解它;旧内核也不认识这两项,不会按组件格式去解新插件。
821
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"] } },
822
850
  // 顶层的 parameters 不算能力(contract.md 第 2 节)。
823
851
  parameters: { functions: ["options"], required: ["options"], pairs: [], capabilities: {} }
824
852
  };
@@ -864,6 +892,7 @@ var SLOT_RETURNS = {
864
892
  account: { schema: LoginAccount, nullable: true }
865
893
  },
866
894
  views: { panel: { schema: PanelPage }, action: { schema: ActionResult } },
895
+ decrypt: { push: { schema: array(bytes) }, finish: { schema: array(bytes) } },
867
896
  parameters: { options: { schema: array(Option) } },
868
897
  resolve: { "": { schema: Resolved, nullable: true } }
869
898
  };
@@ -1387,12 +1416,14 @@ var PREFIX = {
1387
1416
  playback: "playback",
1388
1417
  "playback-follow": "playback",
1389
1418
  "playback-probe": "playback",
1419
+ "playback-decrypt": "playback",
1390
1420
  subtitle: "subtitle",
1391
1421
  image: "image",
1392
1422
  "system-image": "image",
1393
1423
  danmaku: "danmaku",
1394
1424
  login: "login",
1395
- "plugin-link": "plugin link"
1425
+ "plugin-link": "plugin link",
1426
+ module: "module"
1396
1427
  };
1397
1428
  var lower = (values) => new Set((values ?? []).map((value) => value.toLowerCase()));
1398
1429
  var Chain = class {
@@ -1439,6 +1470,9 @@ var Chain = class {
1439
1470
  if (this.use === "login" && hostClass !== "declared") {
1440
1471
  throw this.refuse("login-page", address, `${this.label(address)} is not declared in the plugin manifest`);
1441
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
+ }
1442
1476
  this.startsAtUserAddress = (this.grants.userAddresses ?? []).some((value) => normalForm(value)?.href === address.href);
1443
1477
  const headers2 = remembered ? only(request.headers ?? {}, SAFELIST) : { ...request.headers };
1444
1478
  return this.settle({ address, hostClass, method, headers: headers2, body: request.body === true, frames: request.frames });
@@ -1465,10 +1499,14 @@ var Chain = class {
1465
1499
  const granted = hostClass !== "derived" || Object.hasOwn(this.remembered, address.host) || this.once.has(address.host) || this.use === "request" && this.startsAtUserAddress;
1466
1500
  if (!granted) throw this.refuse("redirect-stays-granted", address, `${this.label(address)} is not declared in the plugin manifest`);
1467
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
+ }
1468
1505
  const upgrade = hostClass === "user" && address.host === previous.address.host && previous.address.scheme === "http" && address.scheme === "https";
1469
1506
  if (this.leftOrigin || address.origin !== previous.address.origin && !upgrade) {
1470
1507
  this.leftOrigin = true;
1471
- 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);
1472
1510
  }
1473
1511
  return this.settle({ address, hostClass, method, headers: headers2, body, downgrade });
1474
1512
  }
@@ -1479,10 +1517,11 @@ var Chain = class {
1479
1517
  const { sharedSpace } = pass.publicOnly;
1480
1518
  if (addresses.some((address) => restrictedAddress(address, sharedSpace))) throw this.privateAddress(pass.address);
1481
1519
  }
1482
- // 收到应答后:连上的地址再查一次(DNS 重绑定)。
1520
+ // 收到应答后:连上的地址再查一次(DNS 重绑定)。playback-decrypt 没有这一步:字节边收边交给插件,直播的连接不结束,
1521
+ // 等不到连上的地址(decrypt-https 代它挡重绑定)。
1483
1522
  connected(connection) {
1484
1523
  const pass = this.current;
1485
- 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;
1486
1525
  if (connection === "unknown") {
1487
1526
  const followsOnly = this.use === "playback-follow" || this.use === "playback-probe";
1488
1527
  if (pass.address.scheme === "http" && !followsOnly) {
@@ -1516,6 +1555,9 @@ var Chain = class {
1516
1555
  throw new NetworkRefusal(prefix, this.use === "login" ? "login-page" : "scheme", "", this.schemeMessage());
1517
1556
  }
1518
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
+ }
1519
1561
  return address;
1520
1562
  }
1521
1563
  allowsScheme({ scheme, host }) {
@@ -1525,6 +1567,7 @@ var Chain = class {
1525
1567
  case "danmaku":
1526
1568
  return scheme === "ws" || scheme === "wss";
1527
1569
  case "login":
1570
+ case "module":
1528
1571
  return scheme === "https";
1529
1572
  case "image":
1530
1573
  case "system-image":
@@ -1549,6 +1592,8 @@ var Chain = class {
1549
1592
  return "images are only fetched over https";
1550
1593
  case "plugin-link":
1551
1594
  return "only https links can be opened";
1595
+ case "module":
1596
+ return "modules are only downloaded over https";
1552
1597
  default:
1553
1598
  return "only network stream addresses are allowed";
1554
1599
  }
@@ -2393,12 +2438,12 @@ function pluginJSONText(bytes2) {
2393
2438
  return void 0;
2394
2439
  }
2395
2440
  }
2396
- function nestedTooDeep(json, limit = VALUE_LIMITS.depth) {
2441
+ function nestedTooDeep(json2, limit = VALUE_LIMITS.depth) {
2397
2442
  let depth = 0;
2398
2443
  let inString = false;
2399
2444
  let escaped = false;
2400
- for (let i = 0; i < json.length; i += 1) {
2401
- const code = json.charCodeAt(i);
2445
+ for (let i = 0; i < json2.length; i += 1) {
2446
+ const code = json2.charCodeAt(i);
2402
2447
  if (inString) {
2403
2448
  if (escaped) escaped = false;
2404
2449
  else if (code === 92) escaped = true;
@@ -3438,11 +3483,13 @@ function createKrillPlayer({
3438
3483
  parameters = null,
3439
3484
  secrets = [],
3440
3485
  appKeys = null,
3486
+ modules = null,
3441
3487
  metadata,
3442
3488
  files: files2,
3443
3489
  localization = { locale: "en", dictionaries: {} },
3444
3490
  log = () => {
3445
- }
3491
+ },
3492
+ randomBytes
3446
3493
  }) {
3447
3494
  let current = credentials;
3448
3495
  const handedKeys = /* @__PURE__ */ new Set();
@@ -3469,7 +3516,7 @@ function createKrillPlayer({
3469
3516
  }
3470
3517
  },
3471
3518
  decompress: (format2, data) => decompress(format2, data),
3472
- crypto: createCrypto(),
3519
+ crypto: randomBytes === void 0 ? createCrypto() : { ...createCrypto(), randomBytes },
3473
3520
  formats: {
3474
3521
  async m3u(data) {
3475
3522
  const playlist = parseM3U(data);
@@ -3515,6 +3562,8 @@ function createKrillPlayer({
3515
3562
  return key;
3516
3563
  }
3517
3564
  },
3565
+ // 引擎一侧的实例化在 kernel_wasm.c;这里只按清单的名字给出核对过的字节。
3566
+ wasm: { module: (name2) => wasmModuleBytes(modules, name2) },
3518
3567
  i18n(text, values, context) {
3519
3568
  const checked = i18nArguments(text, values, context);
3520
3569
  return translate(localization, checked.text, checked.values, checked.context);
@@ -3529,6 +3578,14 @@ function appKeyFor(appKeys, name2) {
3529
3578
  const key = appKeys.keys[name2];
3530
3579
  return typeof key === "string" && key !== "" ? key : null;
3531
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
+ }
3532
3589
  function toBytes(data) {
3533
3590
  return typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
3534
3591
  }
@@ -3544,7 +3601,8 @@ function responseHeaders(response, url) {
3544
3601
  if (cookies.length > 0) headers2["set-cookie"] = cookies.join("\n");
3545
3602
  return headers2;
3546
3603
  }
3547
- 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);
3548
3606
  const bytes2 = body === void 0 ? void 0 : toBytes(body);
3549
3607
  const chain = new Chain(use, grants);
3550
3608
  let pass = chain.first({ url, method, headers: headers2, body: bytes2 !== void 0 });
@@ -3562,7 +3620,7 @@ async function send(fetch, { url, method = "GET", headers: headers2 = {}, body }
3562
3620
  }
3563
3621
  }
3564
3622
  const location = response.headers.get("location");
3565
- if (!REDIRECT_STATUSES.has(response.status) || location === null) {
3623
+ if (!follows || !REDIRECT_STATUSES.has(response.status) || location === null) {
3566
3624
  return {
3567
3625
  response: { status: response.status, url: target, headers: responseHeaders(response, pass.address.href), body: await readBody(response, limit, tooLarge) },
3568
3626
  remember: chain.finished(response.status)
@@ -3573,6 +3631,11 @@ async function send(fetch, { url, method = "GET", headers: headers2 = {}, body }
3573
3631
  target = pass.address.href;
3574
3632
  }
3575
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
+ }
3576
3639
  async function readBody(response, limit, message) {
3577
3640
  const declared = Number(response.headers.get("content-length") ?? "");
3578
3641
  const tooLarge = () => new TypeError(message);
@@ -3738,6 +3801,8 @@ function describe(schema) {
3738
3801
  return "true or false";
3739
3802
  case "bytes":
3740
3803
  return "a Uint8Array";
3804
+ case "json":
3805
+ return "a JSON value";
3741
3806
  case "constant":
3742
3807
  return JSON.stringify(schema.value);
3743
3808
  case "enum":
@@ -3781,6 +3846,8 @@ var Checker = class {
3781
3846
  case "bytes":
3782
3847
  if (!(value instanceof Uint8Array)) this.mismatch(schema, value, path);
3783
3848
  return;
3849
+ case "json":
3850
+ return this.json(value, path);
3784
3851
  case "constant":
3785
3852
  if (value !== schema.value) this.mismatch(schema, value, path);
3786
3853
  return;
@@ -3800,6 +3867,20 @@ var Checker = class {
3800
3867
  return this.union(schema, value, path);
3801
3868
  }
3802
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
+ }
3803
3884
  // 标量类型不对:按常见的写错法给改法。
3804
3885
  mismatch(schema, value, path) {
3805
3886
  this.report(path, `is ${shown(value)}, expected ${describe(schema)}`, scalarFix(schema, value));
@@ -3980,11 +4061,21 @@ var BadJSON = class extends Error {
3980
4061
  var JSON_DEPTH = 128;
3981
4062
  var NUMBER = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
3982
4063
  function parseJSONBody(text) {
4064
+ return readJSON(text, true, () => {
4065
+ throw new BadJSON("duplicate key");
4066
+ });
4067
+ }
4068
+ function duplicateKeys(text) {
4069
+ const keys = [];
4070
+ readJSON(text, false, (key) => keys.push(key));
4071
+ return keys;
4072
+ }
4073
+ function readJSON(text, strict, onDuplicate) {
3983
4074
  let index = 0;
3984
4075
  let depth = 0;
3985
4076
  const enter = () => {
3986
4077
  depth += 1;
3987
- if (depth > JSON_DEPTH) throw new BadJSON(`nesting deeper than ${JSON_DEPTH}`);
4078
+ if (strict && depth > JSON_DEPTH) throw new BadJSON(`nesting deeper than ${JSON_DEPTH}`);
3988
4079
  };
3989
4080
  const space = () => {
3990
4081
  while (index < text.length && " \n\r".includes(text[index])) index += 1;
@@ -4041,7 +4132,7 @@ function parseJSONBody(text) {
4041
4132
  space();
4042
4133
  expect(":");
4043
4134
  const entry = value();
4044
- if (object2.has(key)) throw new BadJSON("duplicate key");
4135
+ if (object2.has(key)) onDuplicate(key);
4045
4136
  object2.set(key, entry);
4046
4137
  space();
4047
4138
  if (text[index] === ",") {
@@ -4087,7 +4178,7 @@ function parseJSONBody(text) {
4087
4178
  if (match === null) throw new NotJSON();
4088
4179
  index += match[0].length;
4089
4180
  const number2 = Number(match[0]);
4090
- if (!Number.isFinite(number2)) throw new BadJSON("number is not a finite double");
4181
+ if (strict && !Number.isFinite(number2)) throw new BadJSON("number is not a finite double");
4091
4182
  return number2;
4092
4183
  };
4093
4184
  const result = value();
@@ -4099,7 +4190,7 @@ function parseJSONBody(text) {
4099
4190
  if (item instanceof Map) return [...item].some(([key, entry]) => !key.isWellFormed() || loneSurrogate(entry));
4100
4191
  return false;
4101
4192
  };
4102
- if (loneSurrogate(result)) throw new BadJSON("lone surrogate in a string");
4193
+ if (strict && loneSurrogate(result)) throw new BadJSON("lone surrogate in a string");
4103
4194
  return result;
4104
4195
  }
4105
4196
  function bodyKind(bytes2) {
@@ -4176,8 +4267,57 @@ var SECRET_VALUES = [
4176
4267
  /\beyJ[\w-]{8,}\.eyJ[\w-]{8,}\.[\w-]+/,
4177
4268
  /\b(?:access_key|access_token)=(?!(?:REDACTED-0{10}|REDACTED)(?![\w.-]))[\w.-]{16,}/
4178
4269
  ];
4179
- var redactSetCookie = (lines) => lines.split("\n").map((line) => line.replace(/^([^=;]*)=[^;]*/, `$1=${REDACTED}`)).join("\n");
4180
- var isRedactedSetCookie = (lines) => lines.split("\n").every((line) => new RegExp(`^[^=;]*=${REDACTED}(;|$)`).test(line));
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
+ }
4293
+ function setCookieValueRanges(line) {
4294
+ const ranges = [];
4295
+ let start = 0;
4296
+ for (const [index, segment] of line.split(";").entries()) {
4297
+ const end = start + segment.length;
4298
+ const equals = segment.indexOf("=");
4299
+ const name2 = (equals < 0 ? segment : segment.slice(0, equals)).trim().toLowerCase();
4300
+ if (index === 0) {
4301
+ if (equals < 0) return void 0;
4302
+ ranges.push([start + equals + 1, end]);
4303
+ } else if (segment.trim() !== "" && !isCookieAttribute(name2, equals < 0 ? void 0 : segment.slice(equals + 1))) {
4304
+ ranges.push(equals < 0 ? [start + segment.length - segment.trimStart().length, end] : [start + equals + 1, end]);
4305
+ }
4306
+ start = end + 1;
4307
+ }
4308
+ return ranges;
4309
+ }
4310
+ var redactSetCookie = (lines) => lines.split("\n").map((line) => {
4311
+ const ranges = setCookieValueRanges(line);
4312
+ return ranges === void 0 ? line : ranges.reduceRight((text, [from, to]) => `${text.slice(0, from)}${REDACTED}${text.slice(to)}`, line);
4313
+ }).join("\n");
4314
+ var isPlaceholder = (value) => isRedacted(value) || isFakeId(value);
4315
+ var COOKIE_PAIR = /^[^=;]*=([^;]*)$/;
4316
+ function cookieValues(header, value) {
4317
+ const values = header === "set-cookie" ? value.split("\n").flatMap((line) => setCookieValueRanges(line)?.map(([from, to]) => line.slice(from, to)) ?? [void 0]) : value.split(/;[ \t]*/).map((pair) => COOKIE_PAIR.exec(pair)?.[1]);
4318
+ return values.every((entry) => entry !== void 0) ? values : void 0;
4319
+ }
4320
+ var isRedactedCookie = (header, value) => (header === "cookie" || header === "set-cookie") && cookieValues(header, value)?.every((entry) => entry === "" || isPlaceholder(entry)) === true;
4181
4321
  function redactHeaders(headers2) {
4182
4322
  return Object.fromEntries(Object.entries(headers2).flatMap(([name2, value]) => {
4183
4323
  if (name2.toLowerCase() === "set-cookie") return [[name2, redactSetCookie(value)]];
@@ -4283,8 +4423,7 @@ function findingsIn(value, path, findings) {
4283
4423
  return;
4284
4424
  }
4285
4425
  for (const [key, entry] of Object.entries(value)) {
4286
- const redacted = isRedacted(entry) || typeof entry === "string" && isFakeId(entry) || key.toLowerCase() === "set-cookie" && typeof entry === "string" && isRedactedSetCookie(entry);
4287
- if (isSecretName(key) && typeof entry === "string" && !redacted && entry !== "") {
4426
+ if (isSecretName(key) && typeof entry === "string" && entry !== "" && !isPlaceholder(entry) && !isRedactedCookie(key.toLowerCase(), entry)) {
4288
4427
  findings.push(`${path}.${key}: ${key}`);
4289
4428
  }
4290
4429
  findingsIn(entry, `${path}.${key}`, findings);
@@ -4301,7 +4440,9 @@ async function scanDirectories(directories) {
4301
4440
  for (const directory of directories) {
4302
4441
  for (const file of await jsonFiles(directory)) {
4303
4442
  files2 += 1;
4304
- for (const finding of scanValue(JSON.parse(await readFile(file, "utf8")))) findings.push(`${file} ${finding}`);
4443
+ const text = await readFile(file, "utf8");
4444
+ for (const finding of scanValue(JSON.parse(text))) findings.push(`${file} ${finding}`);
4445
+ for (const key of duplicateKeys(text)) findings.push(`${file} duplicate key ${JSON.stringify(key)}`);
4305
4446
  }
4306
4447
  }
4307
4448
  return { files: files2, findings };
@@ -4388,6 +4529,42 @@ function replayFetch(exchanges) {
4388
4529
  };
4389
4530
  return { fetch, pending, unrecorded };
4390
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
+ }
4391
4568
  var TRANSPORT_HEADERS = /* @__PURE__ */ new Set(["content-encoding", "content-length", "transfer-encoding", "connection", "keep-alive"]);
4392
4569
  function recordingFetch(fetch) {
4393
4570
  const exchanges = [];
@@ -4422,7 +4599,7 @@ async function readCases(directory) {
4422
4599
  }));
4423
4600
  }
4424
4601
  var frameJSON = (frame2) => frame2.data === void 0 ? { text: frame2.text ?? "" } : { data: bytesToJSON(frame2.data) };
4425
- 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 };
4426
4603
  function scriptedSockets(script) {
4427
4604
  const problems = [];
4428
4605
  let opened = false;
@@ -4583,18 +4760,18 @@ function encode(value) {
4583
4760
  }
4584
4761
  return item;
4585
4762
  };
4586
- const json = JSON.stringify(plain(value)) ?? "null";
4763
+ const json2 = JSON.stringify(plain(value)) ?? "null";
4587
4764
  const blob = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));
4588
4765
  let offset = 0;
4589
4766
  for (const part of parts) {
4590
4767
  blob.set(part, offset);
4591
4768
  offset += part.length;
4592
4769
  }
4593
- return [`[${json},${JSON.stringify(parts.map((part) => part.length))}]`, blob];
4770
+ return [`[${json2},${JSON.stringify(parts.map((part) => part.length))}]`, blob];
4594
4771
  }
4595
- function decode(json, blob) {
4596
- if (nestedTooDeep(json)) throw new TypeError(`krillplayer: a message from the plugin is nested deeper than ${VALUE_LIMITS.depth} levels`);
4597
- 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);
4598
4775
  const parts = [];
4599
4776
  let offset = 0;
4600
4777
  for (const size of sizes) {
@@ -4633,9 +4810,28 @@ async function files(directory) {
4633
4810
  return entries.filter((entry) => entry.isFile()).map((entry) => join3(entry.parentPath, entry.name)).sort();
4634
4811
  }
4635
4812
  var DRIVER = join3(here, "engine/engine.c");
4636
- async function engineSourceHash(quickjs = join3(kernelDirectory(), "Sources/CQuickJS")) {
4637
- const hash = createHash("sha256").update(JSON.stringify(FLAGS)).update("engine.c").update(await readFile3(DRIVER));
4638
- 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
+ }
4639
4835
  return hash.digest("hex");
4640
4836
  }
4641
4837
  var ENGINE_PACKAGE = (platform = process.platform, arch = process.arch) => `@krillplayer/plugin-engine-${platform}-${arch}`;
@@ -4659,36 +4855,56 @@ async function executable(file) {
4659
4855
  }
4660
4856
  var environment = (name2) => process.env[name2] || void 0;
4661
4857
  async function build() {
4662
- const quickjs = join3(kernelDirectory(), "Sources/CQuickJS");
4858
+ const kernel = join3(kernelDirectory(), "Sources");
4663
4859
  const compiler = environment("CC") ?? "cc";
4664
- const source = await engineSourceHash(quickjs).catch((error) => {
4665
- 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}`);
4666
4862
  });
4667
4863
  const found = await prebuilt(source);
4668
4864
  if (found !== void 0) return found;
4669
4865
  try {
4670
- return await compile(quickjs, compiler, source);
4866
+ return await compile(compiler, source);
4671
4867
  } catch (error) {
4672
- 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}`);
4673
4869
  }
4674
4870
  }
4675
4871
  async function compileEngine(output, { compiler = environment("CC") ?? "cc", arch } = {}) {
4676
4872
  const quickjs = join3(kernelDirectory(), "Sources/CQuickJS");
4677
- await run3(compiler, [
4678
- ...FLAGS,
4679
- ...arch === void 0 ? [] : ["-arch", arch],
4680
- `-I${join3(quickjs, "include")}`,
4681
- `-I${quickjs}`,
4682
- DRIVER,
4683
- join3(quickjs, "kernel_qjs.c"),
4684
- join3(quickjs, "quickjs_vendor.c"),
4685
- "-lm",
4686
- "-lpthread",
4687
- "-o",
4688
- output
4689
- ], { maxBuffer: 16 << 20 });
4690
- }
4691
- 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) {
4692
4908
  const version = (await run3(compiler, ["--version"])).stdout;
4693
4909
  const key = createHash("sha256").update(source).update(version).digest("hex");
4694
4910
  const cache = environment("KRILLPLAYER_ENGINE_CACHE") ?? join3(environment("XDG_CACHE_HOME") ?? join3(homedir(), ".cache"), "krillplayer-plugin/engine");
@@ -4725,6 +4941,16 @@ function preludeSource() {
4725
4941
  );
4726
4942
  return prelude;
4727
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
+ }
4728
4954
  var KQ_OK = 0;
4729
4955
  var KQ_INTERRUPTED = 2;
4730
4956
  var KQ_OUT_OF_MEMORY = 3;
@@ -4800,11 +5026,12 @@ var EngineProcess = class {
4800
5026
  this.#pending = void 0;
4801
5027
  }
4802
5028
  // remaining 是距期限的秒数;0 表示不设期限。
4803
- op(tag, remaining, a = "", b = "") {
5029
+ // W 帧的 number 是模块的字节数,不是期限。
5030
+ op(tag, remaining, a = "", b = "", size = 0) {
4804
5031
  if (this.#exit) return Promise.reject(this.#exit);
4805
5032
  return new Promise((resolve4, reject) => {
4806
5033
  this.#pending = { resolve: resolve4, reject };
4807
- this.#child.stdin.write(frame(tag, remaining, a, b));
5034
+ this.#child.stdin.write(frame(tag, tag === "W" ? size : remaining, a, b));
4808
5035
  });
4809
5036
  }
4810
5037
  close() {
@@ -4819,9 +5046,9 @@ var EngineProcess = class {
4819
5046
  this.#pending = void 0;
4820
5047
  pending?.resolve({ status: number2, error: a.toString("utf8") });
4821
5048
  } else if (tag === "H") {
4822
- const json = a.toString("utf8");
5049
+ const json2 = a.toString("utf8");
4823
5050
  this.#queue = this.#queue.then(async () => {
4824
- const reply = await this.#host(json, b);
5051
+ const reply = await this.#host(json2, b);
4825
5052
  this.#child.stdin.write("error" in reply ? frame("e", 0, reply.error, "") : frame("h", 0, reply.json, reply.blob));
4826
5053
  });
4827
5054
  }
@@ -4868,7 +5095,7 @@ var CALLS = {
4868
5095
  const value = k.cache.get(key);
4869
5096
  return value === null ? null : JSON.stringify(value);
4870
5097
  },
4871
- "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),
4872
5099
  "storage.get": (k, [key]) => storage(k).get(key),
4873
5100
  "storage.set": (k, [key, value]) => storage(k).set(key, value),
4874
5101
  "storage.delete": (k, [key]) => storage(k).delete(key),
@@ -4882,6 +5109,7 @@ var CALLS = {
4882
5109
  var STARTS = {
4883
5110
  "http.request": (k, [request]) => k.http.request(request),
4884
5111
  "appKeys.get": (k, [name2]) => k.appKeys.get(name2),
5112
+ "wasm.module": (k, [name2]) => k.wasm.module(name2),
4885
5113
  "formats.xmltv.channels": (k, [source]) => k.formats.xmltv.channels(source),
4886
5114
  "formats.xmltv.programmes": (k, [source, query]) => k.formats.xmltv.programmes(source, query),
4887
5115
  "metadata.search": (k, [kind, query, options]) => k.metadata.search(kind, query, options),
@@ -4912,13 +5140,16 @@ var EngineContext = class _EngineContext {
4912
5140
  this.#krillplayer = options.krillplayer;
4913
5141
  this.#slot = options.slot;
4914
5142
  this.#limits = options.limits ?? KERNEL_LIMITS;
4915
- 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));
4916
5144
  }
4917
5145
  static async open(options) {
4918
5146
  const context = new _EngineContext(await engineBinary(), options);
4919
5147
  try {
4920
5148
  context.#deadline = now() + context.#limits.callSeconds;
4921
- 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));
4922
5153
  await context.#enter("M", options.source, options.name);
4923
5154
  return context;
4924
5155
  } catch (error) {
@@ -4974,13 +5205,13 @@ var EngineContext = class _EngineContext {
4974
5205
  });
4975
5206
  }
4976
5207
  #dispatch(message) {
4977
- const [json, blob] = encode(message);
4978
- return this.#enter("D", json, blob);
5208
+ const [json2, blob] = encode(message);
5209
+ return this.#enter("D", json2, blob);
4979
5210
  }
4980
5211
  // 进引擎的唯一入口:期限每次重设;跑过期限或超了内存就关掉子进程并停用这个上下文。
4981
- async #enter(tag, a = "", b = "") {
5212
+ async #enter(tag, a = "", b = "", size = 0) {
4982
5213
  if (this.#breach) throw new EngineError({ stopped: this.#breach });
4983
- 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);
4984
5215
  if (status === KQ_OK) return;
4985
5216
  if (status === KQ_INTERRUPTED || status === KQ_OUT_OF_MEMORY) {
4986
5217
  this.#breach = status === KQ_INTERRUPTED ? "timeout" : "memory";
@@ -4989,9 +5220,9 @@ var EngineContext = class _EngineContext {
4989
5220
  }
4990
5221
  throw new EngineError({ threw: error });
4991
5222
  }
4992
- async #host(json, blob) {
5223
+ async #host(json2, blob) {
4993
5224
  try {
4994
- const [replyJSON, replyBlob] = encode(await this.#handle(decode(json, blob)));
5225
+ const [replyJSON, replyBlob] = encode(await this.#handle(decode(json2, blob)));
4995
5226
  return { json: replyJSON, blob: replyBlob };
4996
5227
  } catch (error) {
4997
5228
  return { error: error instanceof Error ? error.message : `krillplayer: ${String(error)}` };
@@ -5325,7 +5556,7 @@ function checkPlugin(source) {
5325
5556
  var RESERVED_PARAMETER_PREFIX = "krillplayer.files.";
5326
5557
  function checkManifest(manifest) {
5327
5558
  const parameters = Array.isArray(manifest.parameters) ? manifest.parameters : [];
5328
- const problems = [];
5559
+ const problems = checkModules(manifest.modules, manifest.hosts);
5329
5560
  if (manifest.loginRequired === true && Array.isArray(manifest.capabilities) && !manifest.capabilities.includes("login")) {
5330
5561
  problems.push("loginRequired needs a login slot: export login so the user can log in when adding a source, or drop loginRequired");
5331
5562
  }
@@ -5349,6 +5580,35 @@ function checkManifest(manifest) {
5349
5580
  }
5350
5581
  return problems;
5351
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
+ }
5352
5612
 
5353
5613
  // trial-runner/trial.ts
5354
5614
  async function readFiles(path) {
@@ -5367,6 +5627,22 @@ async function readFiles(path) {
5367
5627
  }));
5368
5628
  }
5369
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
+ }
5370
5646
  function dictionariesIn(files2) {
5371
5647
  return Object.fromEntries([...files2].flatMap(([name2, text]) => {
5372
5648
  const match = /^locales\/([^/]+)\.json$/.exec(name2);
@@ -5390,6 +5666,8 @@ async function readPlugin(path) {
5390
5666
  parameters: manifest.parameters ?? [],
5391
5667
  appKeys: manifest.appKeys ?? [],
5392
5668
  files: manifest.files,
5669
+ modules: Array.isArray(manifest.modules) ? manifest.modules : [],
5670
+ ...path.endsWith(".zip") ? {} : { moduleDirectory: join4(path, MODULES) },
5393
5671
  language: manifest.language,
5394
5672
  dictionaries: dictionariesIn(files2),
5395
5673
  exports: checked.exports,
@@ -5409,7 +5687,7 @@ function skipReason(testCase) {
5409
5687
  if (testCase.slot === "status" && testCase.credentials) return "status with credentials runs only in the App kernel";
5410
5688
  return void 0;
5411
5689
  }
5412
- 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) {
5413
5691
  const parameters = testCase.parameters ?? null;
5414
5692
  const krillplayer = createKrillPlayer({
5415
5693
  fetch,
@@ -5421,19 +5699,28 @@ function openSlot(plugin2, testCase, fetch, credentials, onWrite, metadata = scr
5421
5699
  parameters,
5422
5700
  secrets: plugin2.parameters.filter((parameter) => parameter.secret).map((parameter) => parameter.name),
5423
5701
  appKeys: testCase.appKeys === void 0 ? null : { declared: plugin2.appKeys, keys: testCase.appKeys },
5702
+ modules: localModules(plugin2),
5424
5703
  cache: createCache().scope({ pluginId: plugin2.id, sourceId: plugin2.id }),
5425
5704
  storage: createStorage().scope({ pluginId: plugin2.id, sourceId: plugin2.id }),
5426
5705
  credentials: testCase.slot === "status" ? null : credentials,
5427
5706
  ...testCase.slot === "status" ? {} : { writeCredentials: onWrite },
5428
5707
  metadata: metadata.service,
5429
5708
  ...plugin2.files === void 0 ? {} : { files: { protocol: plugin2.files, service: files2.service } },
5430
- 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 } }
5431
5719
  });
5432
- return EngineContext.open({ source: plugin2.source, name: plugin2.name, krillplayer, slot: testCase.slot });
5433
5720
  }
5434
5721
  async function invokeSlot(plugin2, testCase, fetch, credentials, onWrite = () => {
5435
- }) {
5436
- 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);
5437
5724
  try {
5438
5725
  return await context.call(testCase.slot, testCase.call ?? "", testCase.args.map(fromJSON));
5439
5726
  } finally {
@@ -5449,9 +5736,17 @@ function describeError(error) {
5449
5736
  function contractProblems(testCase, output) {
5450
5737
  return validateOutput(testCase.slot, testCase.call ?? "", output).map((problem) => `contract: ${problem}`);
5451
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";
5452
5740
  async function runSlotCase(plugin2, testCase) {
5453
5741
  const skip = skipReason(testCase);
5454
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 };
5455
5750
  const replay = replayFetch(testCase.exchanges ?? []);
5456
5751
  const metadata = scriptedMetadata(testCase.metadata);
5457
5752
  const files2 = scriptedFiles(testCase.files);
@@ -5461,7 +5756,7 @@ async function runSlotCase(plugin2, testCase) {
5461
5756
  const sockets = scriptedSockets(testCase.socket);
5462
5757
  const context = await openSlot(plugin2, testCase, replay.fetch, testCase.credentials ?? null, (write) => {
5463
5758
  written = write;
5464
- }, metadata, files2);
5759
+ }, metadata, files2, pins);
5465
5760
  try {
5466
5761
  const value = await context.call(testCase.slot, testCase.call ?? "", testCase.args.map(fromJSON));
5467
5762
  const contract = contractProblems(testCase, value);
@@ -5496,10 +5791,12 @@ async function runSlotCase(plugin2, testCase) {
5496
5791
  }
5497
5792
  problems.push(
5498
5793
  ...replay.unrecorded.map((request) => `unrecorded request ${request}`),
5794
+ ...replay.unrecorded.length > 0 && testCase.clock === void 0 ? [UNPINNED_HINT] : [],
5499
5795
  ...replay.pending.map(({ request }) => `recorded request not sent ${request.method} ${request.url}`),
5500
5796
  ...metadata.problems(),
5501
5797
  ...files2.problems(),
5502
- ...sockets.problems()
5798
+ ...sockets.problems(),
5799
+ ...random?.problems() ?? []
5503
5800
  );
5504
5801
  if ("output" in outcome) {
5505
5802
  if (testCase.error !== void 0) problems.push(`should throw ${canonical(testCase.error)}, returned ${canonical(outcome.output)}`);
@@ -5581,7 +5878,11 @@ async function recordCommand(pluginDirectory, { slot, call: callName, args, cred
5581
5878
  }
5582
5879
  return { output: toJSON(value) };
5583
5880
  };
5584
- 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);
5585
5886
  const own = credentials === null ? [] : Object.values(credentials).filter((value) => typeof value === "string" && value !== "").map((value, index) => ({ value, fake: fakeValue(value, index) }));
5586
5887
  const redacted = credentials === null ? null : Object.fromEntries(Object.entries(credentials).map(([key, value]) => [key, typeof value === "string" ? withOwnValuesReplaced(value, own) : REDACTED]));
5587
5888
  const keptArgs = withOwnValuesReplaced(args, own);
@@ -5599,7 +5900,19 @@ async function recordCommand(pluginDirectory, { slot, call: callName, args, cred
5599
5900
  if (unacceptable.length > 0) throw new RecordRefused(`a request body cannot be replayed the same way on both runners, nothing was recorded:
5600
5901
  ${unacceptable.join("\n ")}`);
5601
5902
  const replay = replayFetch(exchanges);
5602
- 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
+ }
5603
5916
  const testCase = {
5604
5917
  slot,
5605
5918
  ...callName === void 0 ? {} : { call: callName },
@@ -5607,6 +5920,8 @@ async function recordCommand(pluginDirectory, { slot, call: callName, args, cred
5607
5920
  ...redacted === null ? {} : { credentials: redacted },
5608
5921
  ...kept === void 0 ? {} : { parameters: kept },
5609
5922
  ...keptKeys === void 0 ? {} : { appKeys: keptKeys },
5923
+ clock,
5924
+ ...random === void 0 ? {} : { random },
5610
5925
  exchanges,
5611
5926
  ...outcome
5612
5927
  };
@@ -6011,6 +6326,8 @@ var COMMANDS = {
6011
6326
  " call the real service once, redact credentials, replay the recording and save it as a case",
6012
6327
  " a krillplayer.error thrown by the plugin is saved as the case's error; nothing is written when the output",
6013
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",
6014
6331
  " --slot <slot> browse, play, status, ...; for the top-level resolve write resolve and no --call",
6015
6332
  " --call <fn> the function in the slot, e.g. list",
6016
6333
  ` --args <json> the arguments after krillplayer, as a JSON array, e.g. '[{}]' or '[{}, "<next>"]'`,