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
@@ -1,10 +1,11 @@
1
1
  // 样例:既直播又发视频的平台。数据写死在这里,不出网;主机名都是不存在的 .example。
2
2
  // 看点:创作者是频道,带可选的 live(正在播才有)与分栏;直播条目的 id 由插件给(这里是场次号,和频道 id 没有关系),
3
3
  // 状态槽位用 liveId 报同一个 id;预告开播后变成直播、结束后变成回放(点播);普通视频归进播放列表;顶层的 resolve 认链接。
4
- // 直播间有两条线路、各两档,起播只取用户选的那一路(start 的 selection,#857),别的列在 qualities 里。
4
+ // 直播间有两条线路、各三档,起播只取用户选的那一路(start 的 selection,#857),别的列在 qualities 里;最高的「蓝光」要登录,没登录时标在 loginQualities 里(#826)。
5
5
  // 直播间有弹幕:connect 给连接规格、decode 一次解一帧;登录后能 send 发一条(#704),平台的回答按 code 换成契约的错误种类。
6
+ // 发送接口要在查询串里带时间戳、随机串与签名(#895):用例的 clock 与 random 定住这两样,录下的地址回放时对得上。
6
7
  import type {
7
- BrowseSlot, ChannelRef, Creator, DanmakuSlot, Entry, Live, OnDemand, Paged, Playable, PluginError, Playlist, PlaySelection, PlaySlot, ResolveFunction, StatusSlot, Upcoming,
8
+ BrowseSlot, ChannelRef, KrillPlayer, Creator, DanmakuSlot, Entry, Live, OnDemand, Paged, Playable, PluginError, Playlist, PlaySelection, PlaySlot, ResolveFunction, StatusSlot, Upcoming,
8
9
  } from "krillplayer-plugin";
9
10
 
10
11
  const CDN = "https://cdn.example";
@@ -113,26 +114,31 @@ export const status = {
113
114
  },
114
115
  } satisfies StatusSlot;
115
116
 
116
- // 直播间有两条线路、各两档,平台每一路地址要单独签一次名(直播平台常见的样子;这里不出网,签名就是拼地址)。
117
+ // 直播间有两条线路、各三档,平台每一路地址要单独签一次名(直播平台常见的样子;这里不出网,签名就是拼地址)。
117
118
  // 起播只取一路:用户选过时取 selection 那一路,没选过或平台没有那一路时取主线路的第一档;别的线路与档位写进 qualities,
118
119
  // 菜单照样列,用户选中时内核带着它再调 start(PlaySlot 的说明)。这样一次起播的请求数不随线路数、档位数增长。
120
+ // 「蓝光」登录后才有:没登录时照样列在 qualities 里,另写进 loginQualities,App 在菜单里标出要登录,用户选它时先请他登录;
121
+ // 登录了就不写。没登录时选到它(App 不会这样做)照没给 selection 时那样交。
119
122
  const LIVE_LINES = [{ name: "主线路", path: "main" }, { name: "备用线路", path: "backup" }];
120
- const LIVE_QUALITIES = [{ name: "原画", path: "source" }, { name: "高清", path: "720p" }];
123
+ const LIVE_QUALITIES = [{ name: "蓝光", path: "1080p", login: true }, { name: "原画", path: "source" }, { name: "高清", path: "720p" }];
121
124
 
122
- function liveLines(itemId: string, selection: PlaySelection | undefined): Playable["lines"] {
125
+ function liveLines(itemId: string, selection: PlaySelection | undefined, loggedIn: boolean): Playable["lines"] {
126
+ const open = LIVE_QUALITIES.filter((candidate) => loggedIn || candidate.login !== true);
123
127
  const line = LIVE_LINES.find((candidate) => candidate.name === selection?.line);
124
- const quality = LIVE_QUALITIES.find((candidate) => candidate.name === selection?.quality);
125
- const [signedLine, signedQuality] = line !== undefined && quality !== undefined ? [line, quality] : [LIVE_LINES[0], LIVE_QUALITIES[0]];
128
+ const quality = open.find((candidate) => candidate.name === selection?.quality);
129
+ const [signedLine, signedQuality] = line !== undefined && quality !== undefined ? [line, quality] : [LIVE_LINES[0], open[0]];
130
+ const locked = LIVE_QUALITIES.filter((candidate) => !open.includes(candidate)).map(({ name }) => name);
126
131
  return LIVE_LINES.map((candidate) => ({
127
132
  name: candidate.name,
128
133
  streams: candidate === signedLine ? [{ quality: signedQuality.name, url: `${CDN}/live/${itemId}/${candidate.path}/${signedQuality.path}.m3u8` }] : [],
129
134
  qualities: LIVE_QUALITIES.map(({ name }) => name),
135
+ ...(locked.length > 0 ? { loginQualities: locked } : {}),
130
136
  }));
131
137
  }
132
138
 
133
139
  export const play = {
134
140
  async start(krillplayer, itemId, selection) {
135
- if (itemId === LIVE.id) return { timing: "live", lines: liveLines(itemId, selection) };
141
+ if (itemId === LIVE.id) return { timing: "live", lines: liveLines(itemId, selection, krillplayer.credentials.get() !== null) };
136
142
  if (itemId === RADIO_ROOM.id) throw krillplayer.error("notStarted", "还没开播");
137
143
  if (itemId === PREMIERE.id) throw krillplayer.error("notStarted", "首映还没开始");
138
144
  const video = [...VIDEOS, ...REPLAYS].find((candidate) => candidate.id === itemId);
@@ -141,6 +147,16 @@ export const play = {
141
147
  },
142
148
  } satisfies PlaySlot;
143
149
 
150
+ // 发送接口的签名:HMAC-SHA256(应用密钥, "POST\n路径\nts=…&nonce=…") 的十六进制。应用密钥是平台发给客户端的公开值,不是用户的凭证。
151
+ const APP_SECRET = "sample-live-app-secret";
152
+ const hex = (bytes: Uint8Array) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
153
+
154
+ async function signedQuery(krillplayer: KrillPlayer, path: string): Promise<string> {
155
+ const query = `ts=${Math.floor(Date.now() / 1000)}&nonce=${hex(krillplayer.crypto.randomBytes(8))}`;
156
+ const key = await krillplayer.crypto.subtle.importKey("raw", APP_SECRET, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
157
+ return `${query}&sign=${hex(await krillplayer.crypto.subtle.sign("HMAC", key, `POST\n${path}\n${query}`))}`;
158
+ }
159
+
144
160
  // 弹幕:连接与解码不出网,帧是 JSON。发弹幕经平台的接口(https://live.example,用例里是录好的应答):
145
161
  // code 0 是发出去了;别的 code 换成契约的错误种类,message 原样交给内核显示。插件不重发,同一条不连发、发送间隔由内核守。
146
162
  const SEND_REFUSALS: Record<number, PluginError["kind"]> = { 1001: "loginRequired", 1003: "muted", 1005: "rateLimited", 1010: "contentRejected" };
@@ -161,9 +177,10 @@ export const danmaku = {
161
177
  async send(krillplayer, itemId, text) {
162
178
  const credentials = krillplayer.credentials.get();
163
179
  if (credentials === null) throw krillplayer.error("loginRequired", "登录后才能发弹幕");
180
+ const path = `/room/${itemId}/danmaku`;
164
181
  const response = await krillplayer.http.request({
165
182
  method: "POST",
166
- url: `https://live.example/room/${itemId}/danmaku`,
183
+ url: `https://live.example${path}?${await signedQuery(krillplayer, path)}`,
167
184
  headers: { authorization: `Bearer ${credentials.token}`, "content-type": "application/json" },
168
185
  body: JSON.stringify({ text }),
169
186
  });
@@ -37,6 +37,8 @@
37
37
  | `written` | 这次调用经 `krillplayer.credentials.set` 最后写入的凭证:`{ "values": { "token": "REDACTED" }, "expiresAt": 1767225600 }`。写了凭证而用例没写这个键判失败 |
38
38
  | `requires` | 试跑器没有的能力(例如 `webview`),写了就跳过这条,只在 App 里测 |
39
39
  | `socket` | `danmaku.send` 返回发送会话时连的假服务器,见下 |
40
+ | `clock` | 这次调用里的时刻,纪元毫秒数(整数)。`record` 总会写,见下「时刻与随机数」 |
41
+ | `random` | 这次调用里的随机数,`{"$bytes": "<base64>"}`。`record` 在插件取过随机数时写,见下 |
40
42
 
41
43
  状态槽位带凭证的用例在试跑器里跳过。
42
44
 
@@ -62,13 +64,29 @@ npx krillplayer-plugin record --slot <槽位> [--call <函数>] --args '<JSON
62
64
 
63
65
  真实出网跑一次,脱敏后再用录下的应答回放一次,得到 `output` 或 `error`,扫描通过才写文件。
64
66
 
65
- - 脱敏:去掉 Cookie、`authorization` 等请求与应答头;地址、JSON 正文与表单正文里名字像凭证的参数(`token`、`access_key`、`SESSDATA` 等)换成 `REDACTED`;凭证文件的每个值、清单里 `secret: true` 的实例参数值也换成 `REDACTED`;Set-Cookie 只留名字与认得的属性(Path、Domain、Expires、Max-Age、SameSite、Secure、HttpOnly、Partitioned、Priority),别的属性的值也换掉。扫描对 `cookie` 与 `set-cookie` 头逐对看,每一对「名=值」的值都得是 `REDACTED` 这类占位值,`set-cookie` 里认不出的属性也按一对看,写法认不出的也报。用例文件里同一个对象重名的键也报。
67
+ - 脱敏:去掉 Cookie、`authorization` 等请求与应答头;地址、JSON 正文与表单正文里名字像凭证的参数(`token`、`access_key`、`SESSDATA` 等)换成 `REDACTED`;凭证文件的每个值、清单里 `secret: true` 的实例参数值也换成 `REDACTED`;Set-Cookie 只留名字与认得的属性(Path、Domain、Expires、Max-Age、SameSite、Secure、HttpOnly、Partitioned、Priority,值得合各自的写法:日期、整数、固定的几个词、以 `/` 开头的路径、主机名,标志不带值),别的属性与对不上写法的属性的值也换掉。扫描对 `cookie` 与 `set-cookie` 头逐对看,每一对「名=值」的值都得是 `REDACTED` 这类占位值,`set-cookie` 里认不出的属性与值对不上写法的属性(例如 `Path=/<真值>`)也按一对看,写法认不出的也报。用例文件里同一个对象重名的键也报。
66
68
  - 插件经 `throw krillplayer.error(kind, message)` 失败时照样写文件,用例里是 `error` 而不是 `output`:真实来源能触发的失败(不存在的 id、下架的条目)就这样录。
67
69
  - 不写文件的情形:返回值不合契约(报错照 [errors-and-fixes.md](errors-and-fixes.md) 改);插件抛的不是 `krillplayer.error`(例如读了 `undefined` 的属性,报错带调用栈);脱敏后还像有凭证。
68
70
  - 凭证文件放在插件目录外,录完删掉。
69
71
  - 应答很大时(整张网页、几十 KB 的 JSON),删掉插件没用到的字段或段落,再跑一次 `trial` 确认这条照样通过。
70
72
  - `record` 不录 `krillplayer.metadata`:录制时调它会失败,录好后手工补上 `metadata`。
71
73
 
74
+ ## 时刻与随机数
75
+
76
+ 签名带时间戳与随机串(`ts`、`nonce`、`sign`,随机 iv 的密文)时,每次跑出来的地址或正文都不同,回放就对不上。用例的两个键把它们定住,插件代码照常写 `Date.now()`、`Math.random()` 与 `krillplayer.crypto.randomBytes`,不用为用例改:
77
+
78
+ ```json
79
+ "clock": 1767225600000,
80
+ "random": { "$bytes": "8CIqGuI/Yt4=" }
81
+ ```
82
+
83
+ - `clock`:调用里 `Date.now()`、`new Date()`、`Date()` 都是这一刻,时间不走。带参数的 `new Date(…)`、`Date.parse`、`Date.UTC` 照常。
84
+ - `random`:一串字节按取用顺序给,`randomBytes(n)` 取下 n 个,`Math.random()` 取 7 个。取完了还要取报 `random ran out`,没取完报 `random has N byte(s) the plugin did not draw`,两种都要重录。
85
+ - `record` 把时刻定在开始录的那一刻、记下插件取到的随机字节,写进这两个键,所以这类请求直接录就行。手写的用例从录好的复制,或自己定一个时刻与一串字节,再照它们算出请求里的值。
86
+ - 没写的键照旧是真的:返回值里带了当时时刻的用例(例如「今天」的节目单),写上 `clock` 才稳定。
87
+ - `subtle.generateKey` 生成的密钥与 RSA-PSS、ECDSA、RSA-OAEP 自带的随机不从 `random` 取,带它们的请求仍然回放不上。
88
+ - App 里不看这两个键,插件拿到的一直是真的时刻与随机数。
89
+
72
90
  ## 失败情形
73
91
 
74
92
  来源能稳定触发的失败照上面直接录。其余的(限流、服务器出错、改了格式)录不到:复制一条录好的用例,改 `exchanges` 里的应答(HTTP 状态、来源的错误码、空列表、缺字段),删掉 `output`,写上期望的 `error`。插件代码里每一处 `throw krillplayer.error(…)` 都该有一条用例走到它。
@@ -23,7 +23,7 @@ export interface Paged<T> {
23
23
  export type Ids = Record<string, string>;
24
24
 
25
25
  // 能力由打包器按导出的函数生成(SLOT_RULES),插件不手写。
26
- export type Capability = "browse" | "music" | "play" | "resolve" | "resources" | "subtitles" | "subtitleSearch" | "danmaku" | "danmakuMatch" | "status" | "login" | "playbackReport" | "danmakuSend" | "browseLists" | "playerPanels" | "cardActions" | "danmakuSendSession";
26
+ export type Capability = "browse" | "music" | "play" | "resolve" | "resources" | "subtitles" | "subtitleSearch" | "danmaku" | "danmakuMatch" | "status" | "login" | "playbackReport" | "danmakuSend" | "browseLists" | "playerPanels" | "cardActions" | "danmakuSendSession" | "decrypt";
27
27
 
28
28
  // 内容对象。通用域三样结构:频道、合集、条目,每个种类一个类型,只带属于它的字段。
29
29
  // 种类的取值是内核定死的词表,插件不能自造。比插件旧的 App 遇到不认识的种类时跳过数组里的那一项、把可选字段当作没给;
@@ -543,6 +543,16 @@ export interface PlatformCapabilities {
543
543
  // settings 是设置项,值由插件用 krillplayer.settings.get() 读;默认插件级,带 perSource 的那一项每个来源各一份。
544
544
  // loginRequired:导出了 login 的插件声明添加来源时必须登录;不写是可以登录、也可以不登录。没导出 login 的插件没有登录,不能写它。
545
545
  // singleSource:这个插件只能有一个来源实例;不写可以有多个(多个账号就是多个来源)。
546
+ // 清单钉住的 WebAssembly 模块:插件按 name 经 krillplayer.wasm.instantiate 拿实例,拿不到任意字节去编译(引擎编之前按这里的长度与 sha256 核对字节)。
547
+ // url 是 https,主机要在 hosts 里;sha256 是 64 位小写十六进制;size 是字节数,不超过 WASM_LIMITS.moduleBytes。
548
+ // 内核第一次用到时下载、核对、按哈希缓存;只改了已有模块的地址与哈希的更新不问用户,新增模块名才问。
549
+ export interface PluginModule {
550
+ name: string;
551
+ url: string;
552
+ sha256: string;
553
+ size: number; // 整数
554
+ }
555
+
546
556
  export interface PluginManifest {
547
557
  id: string;
548
558
  sourceId: string;
@@ -560,6 +570,7 @@ export interface PluginManifest {
560
570
  imageCacheIgnoredParameters?: string[];
561
571
  files?: FilesProtocol;
562
572
  appKeys?: string[];
573
+ modules?: PluginModule[];
563
574
  parameters?: Parameter[];
564
575
  settings?: Parameter[];
565
576
  unsupported?: PlatformCapabilities;
@@ -591,6 +602,26 @@ export interface PlayableSubtitle {
591
602
  headers?: Record<string, string>;
592
603
  }
593
604
 
605
+ export type Container = "mp4" | "mov" | "mkv" | "ts" | "flv" | "hls" | "dash" | "webm" | "mp3" | "aac" | "flac" | "ogg";
606
+
607
+ // 一路的字节怎么解。cencAesCtr:明文密钥的 CENC(cenc-aes-ctr)片源,key 与 keyId 都是 16 字节,
608
+ // 32 位十六进制或 base64,由播放引擎解。plugin:字节交给插件自己的解密槽位 decrypt 解开再交给播放引擎,
609
+ // state 原样交给 decrypt.open,其中每个字符串当播放的凭证登记进日志的凭证表;要联网取的密钥在 play.start 里取好放进 state。
610
+ // 能解的是一条读到底的流(不是 HLS 的直播);大小已知、能定位的文件与给了 audioURL 的一路带了它,起播时报不支持。
611
+ // 这类一路的联网比别的播放严:不是用户给的主机只走 https,不连局域网(decrypt-https)。
612
+ export type PlayableDecryption = CencDecryption | PluginDecryption;
613
+
614
+ export interface CencDecryption {
615
+ method: "cencAesCtr";
616
+ key: string;
617
+ keyId?: string;
618
+ }
619
+
620
+ export interface PluginDecryption {
621
+ method: "plugin";
622
+ state?: JSONValue;
623
+ }
624
+
594
625
  // container 知道就给,视频引擎把它当格式提示交给播放引擎,并用它认出 HLS;不认识的取值当作没给,引擎再看地址后缀。
595
626
  // audioURL 是这一路单独的音轨,给了它 url 就只有画面。两个地址都是 http 或 https(不收 krillplayer.files.playable 给的地址),
596
627
  // 都指向分片 MP4:第一个顶层盒子是 ftyp,moov 之后、第一个 moof 或 mdat 之前有顶层的 sidx,moov 在前 64 MiB 里;服务器认 Range。
@@ -601,16 +632,18 @@ export interface PlayableStream {
601
632
  headers?: Record<string, string>;
602
633
  audioURL?: string;
603
634
  container?: Container;
635
+ decryption?: PlayableDecryption;
604
636
  }
605
637
 
606
- export type Container = "mp4" | "mov" | "mkv" | "ts" | "flv" | "hls" | "dash" | "webm" | "mp3" | "aac" | "flac" | "ogg";
607
-
608
638
  // qualities 是这条线路的全部档位,按菜单里的顺序;streams 只放这次取了地址的几档。没给时档位就是 streams 里的那几档。
609
639
  // 每档都要单独取地址的平台用它列出没取的档位与线路(streams 可以为空):用户选中时内核重调 play.start 并带上那一路。
640
+ // loginQualities 是登录(或重新登录)后才拿得到的几档:没登录、登录失效时列出,也写进 qualities 放在菜单该在的位置;登录了、拿得到时不写。
641
+ // 菜单照列这几档、标出要登录;用户选中时内核不调 start,问用户要不要登录,登录后再带着这一档调 start。
610
642
  export interface PlayableLine {
611
643
  name: string;
612
644
  streams: PlayableStream[];
613
645
  qualities?: string[];
646
+ loginQualities?: string[];
614
647
  }
615
648
 
616
649
  // 时间都以秒计;expiresAt 是 Unix 时间戳。resume 是来源记下的续播位置(点播,秒),
@@ -642,16 +675,8 @@ export interface PlayableSegment {
642
675
  title?: string; // App 尚未使用
643
676
  }
644
677
 
645
- export interface PlayableDecryption {
646
- method: PlayableDecryptionMethod;
647
- key: string;
648
- keyId?: string;
649
- }
650
-
651
678
  export type PlayableSegmentKind = "intro" | "outro" | "chapter";
652
679
 
653
- export type PlayableDecryptionMethod = "cencAesCtr";
654
-
655
680
  // 面板里的一条评论(views.panel 交 comments 时):id 在这个条目的评论里唯一,翻页时内核按它去重;
656
681
  // author 是作者名,avatar 是作者头像,time 是发表时刻(Unix 秒),likes 是点赞数。怎么画由 App 定。
657
682
  export interface Comment {
@@ -1167,11 +1192,16 @@ export interface CryptoKeyPair {
1167
1192
 
1168
1193
  // krillplayer.http.request 的请求。只允许 http 与 https;每一跳(含重定向)的主机都要在清单 hosts 里,
1169
1194
  // 或是本来源实例 url 参数里的主机(清单声明了 userProvidedURLs 时)。
1195
+ // redirect 不给或是 "follow" 时宿主替插件跟跳转,交回最后一跳;跨源的一跳不带 Cookie 这类凭证请求头。
1196
+ // "manual" 时宿主只发这一跳,3xx 原样交回(status、location 头、这一跳的 set-cookie)。要接着走就自己再请求 location
1197
+ // (相对地址按 response.url 解析),想带什么请求头自己定;那次请求和别的请求一样,主机要在 hosts 里。
1198
+ // 用在每一跳都有要收的 Set-Cookie 的换票链上,例如登录续期。
1170
1199
  export interface KrillPlayerRequest {
1171
1200
  url: string;
1172
1201
  method?: string;
1173
1202
  headers?: Record<string, string>;
1174
1203
  body?: Uint8Array | string;
1204
+ redirect?: "follow" | "manual";
1175
1205
  }
1176
1206
 
1177
1207
  // 头名小写。set-cookie 是这次应答的全部 Set-Cookie,一条一行(Cookie 的 Expires 里有逗号,不能按逗号合并)。
@@ -1271,6 +1301,14 @@ export interface KrillPlayerSubtle {
1271
1301
  extractable: boolean, usages: CryptoKeyUsage[]): Promise<CryptoKey>;
1272
1302
  }
1273
1303
 
1304
+ // krillplayer.wasm:形状照 WebAssembly 的 JS 接口。i32、f32、f64 是 Number,i64 是 BigInt。
1305
+ // 宿主函数是插件自己写的 JS 函数,按 { 模块名: { 函数名: 函数 } } 交;模块要的每一个都得给,缺了实例化就失败并报出名字与签名。
1306
+ // 导出里的函数可以直接调,导出的内存是 { buffer }:buffer 每次取都是当前的那段线性内存,内存涨过以后旧的 buffer 被分离。
1307
+ // 模块陷阱(unreachable、越界、除零)是接得住的 RuntimeError;超时与超内存接不住,这次调用失败。
1308
+ export type WasmValue = number | bigint;
1309
+ export type WasmImports = Record<string, Record<string, (...args: WasmValue[]) => WasmValue | void>>;
1310
+ export type WasmExports = Record<string, ((...args: WasmValue[]) => WasmValue | WasmValue[] | void) | { readonly buffer: ArrayBuffer }>;
1311
+
1274
1312
  // 每个槽位函数的第一个参数。插件只能经它出网、存东西、读凭证与实例参数;除此之外只有 ECMAScript 的全局对象、
1275
1313
  // TextEncoder / TextDecoder(只支持 UTF-8)与 console(接到 log)。没有 fetch、setTimeout、URL、atob。
1276
1314
  export interface KrillPlayer {
@@ -1340,6 +1378,12 @@ export interface KrillPlayer {
1340
1378
  parameters: {
1341
1379
  get(): Record<string, string> | null;
1342
1380
  };
1381
+ // 跑清单 modules 里钉住的 WebAssembly 模块:name 是清单里的名字,长度与 SHA-256 和清单对不上的字节引擎不编。
1382
+ // 每次调用一个新实例。模块的内存与时间算在这个插件上下文的上限里(RUNTIME_LIMITS),状态槽位里调用会失败。
1383
+ // 没开的语言特性(SIMD、线程、GC、异常、memory64、尾调用)与 start 段的模块实例化失败并说明是哪一样。
1384
+ wasm: {
1385
+ instantiate(name: string, imports?: WasmImports): Promise<{ exports: WasmExports }>;
1386
+ };
1343
1387
  // App 自己的密钥,按名字取:只有预装插件、只有清单 appKeys 写了的名字拿得到,没有这把密钥时是 null,
1344
1388
  // 插件跳过要它的那家服务。密钥从哪里来由内核定,插件不用管。状态槽位里调用会失败。
1345
1389
  appKeys: {
@@ -1415,6 +1459,8 @@ export interface PlaySelection { line: string; quality: string }
1415
1459
  // 条目、版本都用自己的 id 起播;同一个来源实例里能起播的 id 不重复。
1416
1460
  // selection 是用户要的线路与档位:用户选过时内核才给,没选过时不给。每次换线路、换档位、失败重开都重新调 start,
1417
1461
  // 地址一路一个请求的平台可以只取 selection 那一路,别的线路与档位写进 PlayableLine.qualities 列出来、不取地址。
1462
+ // 没登录或登录失效、拿不到的几档写进 PlayableLine.loginQualities(也照常写进 qualities):菜单标出要登录,用户选它时 App 先请他登录,
1463
+ // 登录后再带着这一档调 start,所以不会收到没登录时选的这几档。登录了、拿得到时不写。
1418
1464
  // 给不出那一路(没有这条线路、这档,或取不到)时照没给 selection 时那样交,内核照常换一路,不要因为它报错。
1419
1465
  export interface PlaySlot {
1420
1466
  start(krillplayer: KrillPlayer, itemId: string, selection?: PlaySelection): Promise<Playable>;
@@ -1495,6 +1541,53 @@ export interface ViewsSlot {
1495
1541
  action?(krillplayer: KrillPlayer, request: ActionRequest): Promise<ActionResult>;
1496
1542
  }
1497
1543
 
1544
+ // 解密槽位:play.start 交出 decryption: { method: "plugin", state } 的一路,内核把它的字节按「单位」交给这里解开。
1545
+ // 一个单位是一段从能独立解的边界起头的字节,按 kind 分,不认识的 kind 抛错:
1546
+ // - stream:一条读到底的连接(不是 HLS 的直播 FLV、TS),从第 0 字节起。连接断了是新的连接、新的单位。
1547
+ // - segment:HLS 的一个分片(container 是 hls 的一路,内核读清单)。播放引擎要哪个分片内核取哪个、开一个单位,所以乱序、重取、
1548
+ // 并发都会有,单位之间不留状态。没有密钥行(或 METHOD=NONE)的分片也交来,key 不给,原样交回就是明文。
1549
+ export type DecryptUnit =
1550
+ | { kind: "stream" }
1551
+ | {
1552
+ kind: "segment";
1553
+ // 分片的地址:清单里写的那个,按清单的最终地址解析成绝对地址(跟跳转之前的)。
1554
+ url: string;
1555
+ // 出自主清单的哪一种:码率档(没有主清单时也是它),或 EXT-X-MEDIA 的备用音轨、备用画面。
1556
+ rendition: "variant" | "audio" | "video";
1557
+ // 媒体序号(从 EXT-X-MEDIA-SEQUENCE 起算),与不连续序号(从 EXT-X-DISCONTINUITY-SEQUENCE 起算)。
1558
+ sequence: number;
1559
+ discontinuity: number;
1560
+ // EXT-X-BYTERANGE:交来的字节只是这一段。
1561
+ byteRange?: { offset: number; length: number };
1562
+ // 管着这个分片的那一行 EXT-X-KEY,原样(uri 是写的那样,没解析);没有、或 METHOD=NONE 时不给。
1563
+ key?: { method: string; uri?: string; iv?: string; attributes: Record<string, string> };
1564
+ // EXT-X-MAP 指的初始化段(分片 MP4),已经是明文,最多 1 MiB;没有就不给。初始化段本身加密时,内核先另开一个单位解它
1565
+ // (url 是初始化段的地址,sequence 取它后面第一个分片的),那个单位不带 map。
1566
+ map?: Uint8Array;
1567
+ };
1568
+
1569
+ // state 是 play.start 写在 decryption 里的那个值,原样;container 是那一路的容器(给了时)。
1570
+ export interface DecryptOpenInput {
1571
+ state?: JSONValue;
1572
+ container?: Container;
1573
+ unit: DecryptUnit;
1574
+ }
1575
+
1576
+ // 解密上下文里的 krillplayer 只有这几样:没有 http、storage、credentials、cache,调了就失败。解密只看字节、state 与 unit,
1577
+ // 要联网取的密钥在 play.start 里取好放进 state。
1578
+ export type DecryptKrillPlayer = Pick<KrillPlayer, "wasm" | "crypto" | "log" | "error">;
1579
+
1580
+ // 每个单位一个新的插件上下文(同一份插件包,执行完顶层代码):open 一次、push 多次、finish 一次,之后销毁,状态不跨单位,
1581
+ // 模块级的变量就是这个单位自己的。push 交来的字节按顺序、每次最多 64 KiB;交回的数组按顺序接起来交给播放引擎,可以先攒着
1582
+ // 交空数组,到 finish 再交。交回的是同一种容器里播放引擎不用密钥就能播的字节。上下文每个 32 MiB;每次调用 20 秒;
1583
+ // 一次交回、或攒在内核里等播放引擎读的字节最多 4 MiB。HLS 的一个分片解开之前最多 64 MiB:整个分片攒在手里再解的,分片连同
1584
+ // 输出要放得进 32 MiB,也就是约 12 MiB 以内,更大的要边收边交。任何一步抛错,这个单位失败,已解开的半截也不交出,用户看到内容解不开。
1585
+ export interface DecryptSlot {
1586
+ open(krillplayer: DecryptKrillPlayer, input: DecryptOpenInput): void | Promise<void>;
1587
+ push(krillplayer: DecryptKrillPlayer, bytes: Uint8Array): Uint8Array[] | Promise<Uint8Array[]>;
1588
+ finish?(krillplayer: DecryptKrillPlayer): Uint8Array[] | Promise<Uint8Array[]>;
1589
+ }
1590
+
1498
1591
  // 插件里除 ECMAScript 的全局对象以外只有这几样;没有 fetch、setTimeout、URL、atob。
1499
1592
  declare global {
1500
1593
  interface TextEncoder { readonly encoding: "utf-8"; encode(input?: string): Uint8Array }
@@ -0,0 +1,104 @@
1
+ # 摘要、签名与加解密
2
+
3
+ 来源的接口要摘要、签名或加解密时,插件的 JS 自己算,工具全在 `krillplayer.crypto` 里。这份只讲工具有什么、怎么用、用例怎么保持可复现;来源用的是哪种方案、参数怎么拼,照来源自己的文档或你对它的分析来定。每个函数的参数与上限以 [contract.d.ts](contract.d.ts) 的 `KrillPlayer` 里 `crypto` 与 `KrillPlayerSubtle` 为准。
4
+
5
+ 交给播放器去解的流(`Playable.decryption`)不在这里,见 contract.d.ts 的 `PlayableDecryption`;更多种类的流解密还在设计中,定下来后写进契约。
6
+
7
+ ## 有什么、各自适合什么
8
+
9
+ | 要做的 | 用哪个 | 说明 |
10
+ |---|---|---|
11
+ | 摘要:SHA-1、SHA-256、SHA-384、SHA-512 | `krillplayer.crypto.digest("sha-256", data)` 或 `subtle.digest("SHA-256", data)` | 两个都行,名字不分大小写 |
12
+ | 摘要:MD5、SM3 | `krillplayer.crypto.digest("md5" 或 "sm3", data)` | `subtle.digest` 不收这两个。**MD5 不提供安全保证**(能造出碰撞),只为与已经在用它的协议互通 |
13
+ | HMAC 签名与验签 | `subtle.importKey("raw", 密钥, { name: "HMAC", hash: "SHA-256" }, false, ["sign"])`,再 `subtle.sign("HMAC", key, data)` | 不写 `length` 时取哈希的块长;`verify` 对不上时返回 `false`,不抛错 |
14
+ | 公钥签名与验签:RSASSA-PKCS1-v1_5、RSA-PSS、ECDSA(P-256、P-384、P-521)、Ed25519 | `subtle.importKey("spki" 或 "pkcs8", …)` 后 `sign` / `verify` | spki 与 pkcs8 也收 PEM 文本(只收一段)。ECDSA 的签名是 `r ‖ s` 定长拼接,不是 DER;RSA-PSS 的 `saltLength` 只能等于哈希长度 |
15
+ | 对称加解密:AES-GCM、AES-CBC、AES-CTR | `subtle.importKey("raw", 密钥, "AES-GCM", false, ["encrypt", "decrypt"])` 后 `encrypt` / `decrypt` | GCM 的 iv 只收 12 字节,标签接在密文后面;CBC 的 iv 16 字节,PKCS#7 补位。新协议用 AES-GCM |
16
+ | 对称加解密:RC4 | `krillplayer.crypto.rc4(key, data)` | 加密与解密是同一个调用,密钥 1 到 256 字节。**不提供安全保证**(密钥流有偏差、没有完整性校验),只为互通 |
17
+ | 公钥加密:RSA-OAEP | `subtle.encrypt({ name: "RSA-OAEP" }, 公钥, data)` | 不收 `label` |
18
+ | 密钥协商与派生:ECDH、X25519、HKDF、PBKDF2 | `subtle.deriveBits` / `deriveKey` | HKDF 与 PBKDF2 的密钥只能按 raw 导入、`extractable: false`;PBKDF2 的迭代次数乘输出块数不超过 2,000,000 |
19
+ | 包装密钥:AES-KW(也可用 RSA-OAEP、AES) | `subtle.wrapKey` / `unwrapKey` | |
20
+ | 随机字节(nonce、iv、自己生成的密钥) | `krillplayer.crypto.randomBytes(n)` | 同步返回。`Math.random()` 不是密码学随机数,不拿它做 nonce 与密钥 |
21
+
22
+ `subtle` 就是 `krillplayer.crypto.subtle`,名字与参数照 WebCrypto,现成的 WebCrypto 代码基本能照搬。不同之处:
23
+
24
+ - 入参的字节收 `Uint8Array` 或字符串,字符串按 UTF-8 编码;`subtle` 另外也收别的视图与 `ArrayBuffer`,`digest` 与 `rc4` 只收前两种。结果是 `Uint8Array`,不是 `ArrayBuffer`。
25
+ - 除了 `randomBytes`,都返回 Promise,要 `await`。
26
+ - 密钥不是 WebCrypto 的 `CryptoKey`,是普通对象:能 `JSON.stringify` 后存进 `krillplayer.storage`,取出来 `JSON.parse` 照样用。整个对象原样存,不读也不改它的 `material`。
27
+ - 插件里没有 `atob`、`btoa`、`Buffer`:十六进制与 Base64 自己写。十六进制一行就够:
28
+
29
+ ```ts
30
+ const hex = (bytes: Uint8Array) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
31
+ ```
32
+
33
+ ## 例子
34
+
35
+ 下面的写法都在试跑器里跑过,注释是它们的结果(标准里的测试向量,不是哪个平台的数据):
36
+
37
+ ```ts
38
+ const { digest, rc4, subtle, randomBytes } = krillplayer.crypto;
39
+
40
+ hex(await digest("sha-256", "abc")); // ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
41
+ hex(await digest("md5", "abc")); // 900150983cd24fb0d6963f7d28e17f72
42
+ hex(await digest("sm3", "abc")); // 66c7f0f462eeedd9d1f2d46bdc10e4e24167c4875cf2f7a2297da02b8f4ba8e0
43
+
44
+ // HMAC-SHA256(RFC 4231 的第 2 组)
45
+ const hmacKey = await subtle.importKey("raw", "Jefe", { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
46
+ hex(await subtle.sign("HMAC", hmacKey, "what do ya want for nothing?"));
47
+ // 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
48
+
49
+ // AES-GCM:16 字节的密钥、随机的 12 字节 iv
50
+ const aes = await subtle.importKey("raw", "0123456789abcdef", "AES-GCM", false, ["encrypt", "decrypt"]);
51
+ const iv = randomBytes(12);
52
+ const sealed = await subtle.encrypt({ name: "AES-GCM", iv }, aes, "hello"); // 5 字节密文 + 16 字节标签
53
+ new TextDecoder().decode(await subtle.decrypt({ name: "AES-GCM", iv }, aes, sealed)); // "hello"
54
+
55
+ hex(await rc4("Key", "Plaintext")); // bbf316e8d940af0ad3
56
+ ```
57
+
58
+ ## 时刻与随机数:用例怎么保持可复现
59
+
60
+ 时间戳、nonce 与签名照常写,用 `Date.now()`、`krillplayer.crypto.randomBytes` 或 `Math.random()`,不用为用例改写。用例的 `clock` 与 `random` 定住这两样([cases.md](cases.md)「时刻与随机数」),`record` 会把录的那一刻与插件取到的随机字节写进用例,回放时两个运行方都照它们给,所以签名不论放在请求头、地址还是正文里,录下的用例都回放得上:
61
+
62
+ ```ts
63
+ const timestamp = String(Math.floor(Date.now() / 1000));
64
+ const nonce = hex(krillplayer.crypto.randomBytes(8));
65
+ const key = await krillplayer.crypto.subtle.importKey("raw", APP_SECRET, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
66
+ const signature = hex(await krillplayer.crypto.subtle.sign("HMAC", key, `GET\n${path}\n${timestamp}\n${nonce}`));
67
+ const response = await krillplayer.http.request({ url: `https://api.example.com${path}?ts=${timestamp}&nonce=${nonce}&sign=${signature}` });
68
+ ```
69
+
70
+ - 签名的密钥是用户的凭证(令牌、登录后拿到的密钥)时,`record` 换成假凭证再回放的那一遍签出的值与录下的不同,录不成。这种签名写成函数,用下面的单元测试测。
71
+ - `subtle.generateKey` 生成的密钥、RSA-PSS、ECDSA 与 RSA-OAEP 自带的随机不从用例的 `random` 取。用它们的请求,回放时同样对不上。
72
+
73
+ 拿来源文档给的签名样例(已知的输入与输出)核对拼法时,把签名写成收时刻与随机串的函数,放在插件目录的 `src/` 下(`new` 建的 `tsconfig.json` 已经包含 `src/`,`bundle` 会把它打进包里),用 Node 的单元测试传定值:
74
+
75
+ ```ts
76
+ // src/sign.ts
77
+ import type { KrillPlayer } from "krillplayer-plugin";
78
+
79
+ export const hex = (bytes: Uint8Array) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
80
+
81
+ export async function signRequest(crypto: KrillPlayer["crypto"], key: string, path: string, timestamp: string, nonce: string) {
82
+ const hmac = await crypto.subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
83
+ return hex(await crypto.subtle.sign("HMAC", hmac, `GET\n${path}\n${timestamp}\n${nonce}`));
84
+ }
85
+ ```
86
+
87
+ ```ts
88
+ // test/sign.test.ts,用 node --test test/sign.test.ts 跑
89
+ import assert from "node:assert/strict";
90
+ import test from "node:test";
91
+ import { createCrypto } from "krillplayer-plugin/crypto";
92
+ import { signRequest } from "../src/sign.ts";
93
+
94
+ test("签名与来源文档的样例相同", async () => {
95
+ const signature = await signRequest(createCrypto(), "example-key", "/v1/search?q=news", "1767225600", "00112233");
96
+ assert.equal(signature, "<来源文档给的签名>");
97
+ });
98
+ ```
99
+
100
+ `createCrypto()` 与试跑器里插件拿到的 `krillplayer.crypto` 是同一份实现,参数、PEM 与报错都一样;测试文件要 Node 的类型(`@types/node`),放在 `src/` 外,免得 `check` 的类型检查去查它。
101
+
102
+ ## 报错
103
+
104
+ `krillplayer.crypto.subtle` 的报错以 `krillplayer.crypto.subtle.<函数>:` 开头并写明原因(算法不支持、密钥与用法不配、iv 长度、标签对不上、补位不对……),每一条的意思与改法在 [errors-and-fixes.md](errors-and-fixes.md) 里按报错文本查。`digest` 与 `rc4` 收到不是 `Uint8Array` 或字符串的入参时只报 `expected a Uint8Array or a string`,不说是密钥还是数据,两个都查;RC4 的密钥另要 1 到 256 字节。
@@ -24,7 +24,10 @@
24
24
  | 报错里有 | 意思 | 怎么改 |
25
25
  |---|---|---|
26
26
  | `contract: ` | 槽位的返回值不合契约。每一行写着位置(output.entries[0].item.kind)与 fix | 照那一行的 fix 改;下面「返回值不合契约」两张表是常见的几种 |
27
- | `unrecorded request` | 插件发了用例 exchanges 里没有的请求(按方法、地址与正文字节匹配,不比请求头) | 插件改了请求就重新录这条用例;不该发时查插件的地址拼接 |
27
+ | `unrecorded request` | 插件发了用例 exchanges 里没有的请求(按方法、地址与正文字节匹配,不比请求头) | 插件改了请求就重新录这条用例;不该发时查插件的地址拼接。地址或正文里带时间戳、随机串时,用例要有 clock 与 random(cases.md「时刻与随机数」,record 会写) |
28
+ | `the case needs clock and random` | 跟在 unrecorded request 后面,用例没写 clock 时给 | 签名里带时间戳、随机串的请求要用例定住时刻与随机数:用 record 重新录(cases.md「时刻与随机数」) |
29
+ | `random ran out` | 插件取的随机字节比用例的 random 多(randomBytes(n) 取 n 个,Math.random() 取 7 个) | 插件改了取随机数的地方就重新录这条用例 |
30
+ | `the plugin did not draw` | 用例的 random 有插件没取完的字节 | 同上,重新录这条用例 |
28
31
  | `recorded request not sent` | 用例里录着的请求插件没发 | 插件少发了请求,或用例该重新录 |
29
32
  | `output differs` | 返回值合契约,但与用例的 output 不同 | 比对 expected 与 actual 两行:插件错了改插件;平台的数据变了重新录 |
30
33
  | `error differs` | 抛出的结构化错误与用例的 error 不同 | 比对 kind 与 message;message 要逐字相同 |
@@ -37,6 +40,7 @@
37
40
  | `is not declared in the plugin manifest` | 请求的主机(含重定向的每一跳)不在清单 hosts 里 | 把主机名加进 manifest.ts 的 hosts(精确匹配,不含子域名);用户填的地址声明 userProvidedURLs: true 并做成 url 参数 |
38
41
  | `only fetches http and https URLs` | 地址不是 http 或 https | 拼出完整的 https:// 地址 |
39
42
  | `credentials may not be sent to` | 凭证或密钥参数要发往一台既没声明、也不是用户填的主机 | 不要给节目单、清单里的派生地址和跳转到的主机带凭证 |
43
+ | `redirect must be "follow" or "manual"` | krillplayer.http.request 的 redirect 写了别的值 | 不写(App 跟跳转),或写 "manual"(App 只发这一跳,3xx 原样交回,自己再请求 location) |
40
44
  | `a private, loopback or link-local address` | 声明的或跳转到的主机在本机、局域网(地址本身就是,或解析到、连上的是);报错里方括号中的是拦下它的规则名 | 局域网的服务让用户填地址:声明 userProvidedURLs: true 并做成 url 参数 |
41
45
  | `the address can be read as more than one host` | 地址里有反斜杠、夹在中间的制表符或换行,或主机前面不止一个 @:不同的实现会把它读成不同的主机 | 把地址写规整再请求:路径用正斜杠,去掉换行,账号密码里的 @ 写成 %40 |
42
46
  | `is not available to the status slot` | 状态槽位用了两宿主共有能力以外的东西(storage、metadata、files) | 状态槽位只用 http、decompress、crypto、formats、log、cache、credentials.get、parameters、error |