krillplayer-plugin 0.1.1 → 0.3.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 (36) hide show
  1. package/README.md +22 -0
  2. package/dist/cli.js +215 -196
  3. package/dist/crypto.d.ts +8 -0
  4. package/dist/crypto.js +1589 -0
  5. package/dist/zip.d.ts +13 -0
  6. package/dist/zip.js +68 -0
  7. package/package.json +11 -2
  8. package/skill/krillplayer-plugin/SKILL.md +2 -1
  9. package/skill/krillplayer-plugin/assets/samples/file-share/plugin.ts +1 -20
  10. package/skill/krillplayer-plugin/assets/samples/media-server/plugin.ts +1 -35
  11. package/skill/krillplayer-plugin/assets/samples/network-share/plugin.ts +1 -20
  12. package/skill/krillplayer-plugin/references/choosing-a-kind.md +2 -2
  13. package/skill/krillplayer-plugin/references/contract.d.ts +95 -129
  14. package/skill/krillplayer-plugin/references/errors-and-fixes.md +1 -1
  15. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-empty-folder.json +0 -11
  16. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-folder-gone-not-found.json +0 -12
  17. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-folder-lists-subfolders-and-media.json +0 -28
  18. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-folder-second-page.json +0 -22
  19. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-folder-skips-subtitles.json +0 -21
  20. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-root-first-page.json +0 -25
  21. package/skill/krillplayer-plugin/assets/samples/file-share/cases/library-root-second-page.json +0 -22
  22. package/skill/krillplayer-plugin/assets/samples/media-server/cases/library-changes-everything-first-page.json +0 -74
  23. package/skill/krillplayer-plugin/assets/samples/media-server/cases/library-changes-everything-last-page.json +0 -86
  24. package/skill/krillplayer-plugin/assets/samples/media-server/cases/library-changes-nothing-new.json +0 -12
  25. package/skill/krillplayer-plugin/assets/samples/media-server/cases/library-changes-since-a-token-with-a-removal.json +0 -88
  26. package/skill/krillplayer-plugin/assets/samples/media-server/cases/library-ids-first-page.json +0 -15
  27. package/skill/krillplayer-plugin/assets/samples/media-server/cases/library-ids-last-page.json +0 -14
  28. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-empty-folder.json +0 -60
  29. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-folder-gives-size-and-modified-time.json +0 -78
  30. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-folder-gone-not-found.json +0 -60
  31. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-folder-second-page.json +0 -71
  32. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-read-a-range.json +0 -62
  33. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-read-an-info-file.json +0 -62
  34. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-read-file-gone-not-found.json +0 -62
  35. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-root.json +0 -84
  36. package/skill/krillplayer-plugin/assets/samples/network-share/cases/library-source-offline-retryable.json +0 -61
package/dist/crypto.js ADDED
@@ -0,0 +1,1589 @@
1
+ // contract/schema.ts
2
+ var string = { kind: "string" };
3
+ var integer = { kind: "integer" };
4
+ var number = { kind: "number" };
5
+ var boolean = { kind: "boolean" };
6
+ var bytes = { kind: "bytes" };
7
+ function constant(value) {
8
+ return { kind: "constant", value };
9
+ }
10
+ function enumeration(name, values, unknown) {
11
+ return { kind: "enum", name, values, ...unknown === void 0 ? {} : { unknown } };
12
+ }
13
+ function array(of) {
14
+ return { kind: "array", of };
15
+ }
16
+ function map(of) {
17
+ return { kind: "map", of };
18
+ }
19
+ function optional(of) {
20
+ return { kind: "optional", of };
21
+ }
22
+ function object(name, fields, swift) {
23
+ return { kind: "object", name, fields, ...swift === void 0 ? {} : { swift } };
24
+ }
25
+ function union(name, tag, variants, swift) {
26
+ const byValue = {};
27
+ for (const variant of variants) {
28
+ const value = variant.fields[tag].value;
29
+ if (byValue[value] !== void 0) throw new Error(`union ${name} has two variants tagged ${value}`);
30
+ byValue[value] = variant;
31
+ }
32
+ return { kind: "union", name, tag, variants: byValue, wrapped: false, ...swift === void 0 ? {} : { swift } };
33
+ }
34
+ function wrapped(name, tag, variants) {
35
+ if (tag in variants) throw new Error(`union ${name} cannot have a variant named like its tag ${tag}`);
36
+ return { kind: "union", name, tag, variants, wrapped: true };
37
+ }
38
+ var pages = /* @__PURE__ */ new Map();
39
+ function paged(of) {
40
+ let page = pages.get(of);
41
+ if (page === void 0) {
42
+ page = object(`Paged${of.name}`, { entries: array(of), next: optional(string) }, `Paged${of.swift ?? of.name}`);
43
+ pages.set(of, page);
44
+ }
45
+ return page;
46
+ }
47
+
48
+ // contract/contract.ts
49
+ var STORAGE_LIMITS = { keyBytes: 256, valueBytes: 64 * 1024, pluginBytes: 1024 * 1024 };
50
+ var RUNTIME_LIMITS = { memoryBytes: 64 * 1024 * 1024, callSeconds: 20, stackBytes: 256 * 1024, callDepth: 64 };
51
+ var FORMAT_LIMITS = { xmlDepth: 64, guideBytes: 48 * 1024 * 1024, decompressedBytes: 64 * 1024 * 1024 };
52
+ var VALUE_LIMITS = { depth: 160 };
53
+ var FILE_LIMITS = { readBytes: 4 * 1024 * 1024 };
54
+ var HTTP_LIMITS = { responseBytes: 16 * 1024 * 1024, inFlight: 6 };
55
+ var SUBTITLE_LIMITS = { tracks: 32, contentBytes: 4 * 1024 * 1024 };
56
+ var Capability = enumeration("Capability", [
57
+ "browse",
58
+ "music",
59
+ "play",
60
+ "resolve",
61
+ "resources",
62
+ "subtitles",
63
+ "subtitleSearch",
64
+ "danmaku",
65
+ "danmakuMatch",
66
+ "status",
67
+ "login",
68
+ "playbackReport",
69
+ "danmakuSend",
70
+ "browseLists",
71
+ "playerPanels",
72
+ "cardActions"
73
+ ]);
74
+ var Media = enumeration("Media", ["video", "audio"]);
75
+ var ChannelKind = enumeration("ChannelKind", ["creator", "station", "podcast"]);
76
+ var CollectionKind = enumeration("CollectionKind", ["series", "season", "boxSet", "playlist", "folder"]);
77
+ var ItemKind = enumeration("ItemKind", ["movie", "episode", "podcastEpisode", "onDemand", "live", "upcoming", "file"]);
78
+ var Ids = map(string);
79
+ var Option = object("Option", { value: string, title: string });
80
+ var VersionInfo = object("VersionInfo", {
81
+ width: optional(integer),
82
+ height: optional(integer),
83
+ hdr: optional(enumeration("VersionHDR", ["sdr", "hdr10", "hdr10plus", "dolbyVision", "hlg"])),
84
+ videoCodec: optional(string),
85
+ audioCodec: optional(string),
86
+ audioChannels: optional(integer),
87
+ sampleRate: optional(integer),
88
+ bitDepth: optional(integer),
89
+ size: optional(integer),
90
+ bitrate: optional(integer),
91
+ languages: optional(array(string)),
92
+ label: optional(string)
93
+ });
94
+ var ResourceVersion = object("ResourceVersion", {
95
+ id: string,
96
+ title: optional(string),
97
+ filename: optional(string),
98
+ version: optional(VersionInfo)
99
+ });
100
+ var ChannelRef = object("ChannelRef", { id: string, kind: ChannelKind, title: string, image: optional(string) });
101
+ var CollectionRef = object("CollectionRef", {
102
+ id: string,
103
+ kind: CollectionKind,
104
+ title: string,
105
+ index: optional(integer),
106
+ ids: optional(Ids)
107
+ });
108
+ var itemBase = { id: string, title: string, image: optional(string), summary: optional(string) };
109
+ var published = { ...itemBase, media: Media, channels: optional(array(ChannelRef)), portrait: optional(boolean) };
110
+ var Movie = object("Movie", {
111
+ kind: constant("movie"),
112
+ ...itemBase,
113
+ year: optional(integer),
114
+ duration: optional(number),
115
+ ids: optional(Ids),
116
+ version: optional(VersionInfo),
117
+ versions: optional(array(ResourceVersion))
118
+ });
119
+ var Episode = object("Episode", {
120
+ kind: constant("episode"),
121
+ ...itemBase,
122
+ season: CollectionRef,
123
+ series: CollectionRef,
124
+ index: integer,
125
+ indexEnd: optional(integer),
126
+ absolute: optional(integer),
127
+ duration: optional(number),
128
+ published: optional(number),
129
+ version: optional(VersionInfo),
130
+ versions: optional(array(ResourceVersion))
131
+ });
132
+ var PodcastEpisode = object("PodcastEpisode", {
133
+ kind: constant("podcastEpisode"),
134
+ ...itemBase,
135
+ media: Media,
136
+ podcast: ChannelRef,
137
+ season: optional(integer),
138
+ index: optional(integer),
139
+ episodeType: optional(enumeration("PodcastEpisodeType", ["full", "trailer", "bonus"])),
140
+ duration: optional(number),
141
+ published: optional(number)
142
+ });
143
+ var OnDemand = object("OnDemand", {
144
+ kind: constant("onDemand"),
145
+ ...published,
146
+ duration: optional(number),
147
+ published: optional(number),
148
+ playlist: optional(CollectionRef),
149
+ index: optional(integer),
150
+ version: optional(VersionInfo)
151
+ });
152
+ var Live = object("Live", {
153
+ kind: constant("live"),
154
+ ...published,
155
+ started: optional(number),
156
+ rerun: optional(boolean),
157
+ offAir: optional(boolean)
158
+ });
159
+ var Upcoming = object("Upcoming", {
160
+ kind: constant("upcoming"),
161
+ ...published,
162
+ start: number,
163
+ end: optional(number)
164
+ });
165
+ var File = object("File", {
166
+ kind: constant("file"),
167
+ ...itemBase,
168
+ media: Media,
169
+ filename: optional(string),
170
+ folder: optional(CollectionRef),
171
+ duration: optional(number),
172
+ size: optional(integer),
173
+ modified: optional(number),
174
+ version: optional(VersionInfo)
175
+ });
176
+ var Item = union("Item", "kind", [Movie, Episode, PodcastEpisode, OnDemand, Live, Upcoming, File], "ItemContent");
177
+ var channelBase = { id: string, title: string, image: optional(string), summary: optional(string) };
178
+ var Creator = object("Creator", {
179
+ kind: constant("creator"),
180
+ ...channelBase,
181
+ live: optional(Live),
182
+ tabs: optional(array(Option))
183
+ });
184
+ var Station = object("Station", {
185
+ kind: constant("station"),
186
+ ...channelBase,
187
+ media: Media,
188
+ live: Live
189
+ });
190
+ var PodcastOrder = enumeration("PodcastOrder", ["episodic", "serial"]);
191
+ var Podcast = object("Podcast", {
192
+ kind: constant("podcast"),
193
+ ...channelBase,
194
+ order: optional(PodcastOrder),
195
+ tabs: optional(array(Option))
196
+ });
197
+ var Channel = union("Channel", "kind", [Creator, Station, Podcast], "ChannelContent");
198
+ var collectionBase = {
199
+ id: string,
200
+ title: string,
201
+ image: optional(string),
202
+ summary: optional(string),
203
+ count: optional(integer),
204
+ ancestors: optional(array(CollectionRef))
205
+ };
206
+ var Series = object("Series", { kind: constant("series"), ...collectionBase, year: optional(integer), ids: optional(Ids) });
207
+ var Season = object("Season", {
208
+ kind: constant("season"),
209
+ ...collectionBase,
210
+ index: integer,
211
+ series: CollectionRef,
212
+ ids: optional(Ids)
213
+ });
214
+ var BoxSet = object("BoxSet", { kind: constant("boxSet"), ...collectionBase, ids: optional(Ids) });
215
+ var Playlist = object("Playlist", { kind: constant("playlist"), ...collectionBase, channels: optional(array(ChannelRef)) });
216
+ var Folder = object("Folder", { kind: constant("folder"), ...collectionBase });
217
+ var Collection = union("Collection", "kind", [Series, Season, BoxSet, Playlist, Folder], "CollectionContent");
218
+ var Entry = wrapped("Entry", "type", { item: Item, channel: Channel, collection: Collection });
219
+ var PagedEntry = paged(Entry);
220
+ var BrowseListKind = enumeration("BrowseListKind", ["video", "live", "audio", "file"]);
221
+ var BrowseList = object("BrowseList", { id: string, title: string, kind: BrowseListKind });
222
+ var ArtistRef = object("ArtistRef", { id: string, name: string, image: optional(string) });
223
+ var albumRef = {
224
+ id: string,
225
+ title: string,
226
+ image: optional(string),
227
+ year: optional(integer),
228
+ artists: optional(array(ArtistRef)),
229
+ compilation: optional(boolean)
230
+ };
231
+ var AlbumRef = object("AlbumRef", albumRef);
232
+ var Artist = object("Artist", { id: string, name: string, image: optional(string), summary: optional(string), ids: optional(Ids) });
233
+ var Album = object("Album", {
234
+ ...albumRef,
235
+ summary: optional(string),
236
+ ids: optional(Ids),
237
+ count: optional(integer),
238
+ type: optional(enumeration("AlbumType", ["album", "single", "ep", "live"])),
239
+ discs: optional(array(object("AlbumDisc", { index: integer, title: optional(string) })))
240
+ });
241
+ var MusicPlaylist = object("MusicPlaylist", {
242
+ id: string,
243
+ title: string,
244
+ image: optional(string),
245
+ summary: optional(string),
246
+ count: optional(integer),
247
+ owner: optional(string)
248
+ });
249
+ var Song = object("Song", {
250
+ id: string,
251
+ title: string,
252
+ image: optional(string),
253
+ duration: optional(number),
254
+ artists: array(ArtistRef),
255
+ album: optional(AlbumRef),
256
+ disc: optional(integer),
257
+ index: optional(integer),
258
+ ids: optional(Ids),
259
+ version: optional(VersionInfo)
260
+ });
261
+ var MusicKind = enumeration("MusicKind", ["artist", "album", "playlist", "song", "station"]);
262
+ var MusicSection = object("MusicSection", { id: string, title: string, kind: MusicKind });
263
+ var MusicEntry = wrapped("MusicEntry", "type", { artist: Artist, album: Album, playlist: MusicPlaylist, song: Song, station: Station });
264
+ var PagedMusicEntry = paged(MusicEntry);
265
+ var PagedAlbum = paged(Album);
266
+ var PagedSong = paged(Song);
267
+ var ArtistPage = object("ArtistPage", { artist: Artist, albums: PagedAlbum, topSongs: optional(array(Song)) });
268
+ var AlbumPage = object("AlbumPage", { album: Album, songs: array(Song) });
269
+ var PlaylistPage = object("PlaylistPage", { playlist: MusicPlaylist, songs: PagedSong });
270
+ var Lyrics = object("Lyrics", {
271
+ synced: boolean,
272
+ lines: array(object("LyricsLine", { start: optional(number), end: optional(number), text: string, translation: optional(string) }))
273
+ });
274
+ var FilesProtocol = enumeration("FilesProtocol", ["smb", "local"]);
275
+ var FileEntry = object("FileEntry", {
276
+ name: string,
277
+ path: string,
278
+ isDirectory: boolean,
279
+ size: optional(integer),
280
+ modified: optional(number)
281
+ });
282
+ var PagedFileEntry = paged(FileEntry);
283
+ var ChannelPage = object("ChannelPage", { channel: Channel, entries: PagedEntry });
284
+ var CollectionPage = object("CollectionPage", { collection: Collection, entries: PagedEntry });
285
+ var ScheduleEntry = object("ScheduleEntry", {
286
+ id: optional(string),
287
+ start: number,
288
+ end: number,
289
+ title: string,
290
+ summary: optional(string),
291
+ image: optional(string),
292
+ item: optional(OnDemand)
293
+ });
294
+ var At = object("At", { tab: optional(string), cursor: optional(string), around: optional(string) });
295
+ var Resolved = union("Resolved", "domain", [object("ResolvedBrowse", { domain: constant("browse"), entry: Entry })]);
296
+ for (const [kinds, content] of [[ChannelKind, Channel], [CollectionKind, Collection], [ItemKind, Item]]) {
297
+ if (kinds.values.join() !== Object.keys(content.variants).join()) throw new Error(`${kinds.name} does not list the variants of ${content.name}`);
298
+ }
299
+ var Parameter = object("Parameter", {
300
+ name: string,
301
+ title: string,
302
+ kind: enumeration("ParameterKind", ["text", "url", "number", "toggle", "choice", "multiChoice", "constant"], "text"),
303
+ secret: optional(boolean),
304
+ defaultValue: optional(string),
305
+ optional: optional(boolean),
306
+ placeholder: optional(string),
307
+ options: optional(array(Option)),
308
+ dynamicOptions: optional(boolean),
309
+ dependsOn: optional(array(string)),
310
+ visibleWhen: optional(array(object("ParameterCondition", { name: string, values: array(string) }))),
311
+ perSource: optional(boolean)
312
+ });
313
+ var Contributions = object("Contributions", {
314
+ playerPanels: optional(array(object("PlayerPanelContribution", { id: string, title: string, kinds: array(ItemKind) }))),
315
+ cardActions: optional(array(object("CardActionContribution", { id: string, title: string, kinds: array(ItemKind) }))),
316
+ backgroundTasks: optional(array(object("BackgroundTaskContribution", { task: string, period: number })))
317
+ });
318
+ var PlatformCapabilities = object("PlatformCapabilities", {
319
+ iOS: optional(array(Capability)),
320
+ macOS: optional(array(Capability)),
321
+ tvOS: optional(array(Capability))
322
+ });
323
+ var PluginManifest = object("PluginManifest", {
324
+ id: string,
325
+ sourceId: string,
326
+ name: string,
327
+ author: string,
328
+ version: string,
329
+ // 原文是什么语言(BCP 47,打包器规范化,zh 一定带文字体系)。包里带了 locales/ 的词典时必须写(contract.md 第 5 节)。
330
+ language: optional(string),
331
+ interfaceLevel: integer,
332
+ contractRevision: integer,
333
+ hosts: array(string),
334
+ userProvidedURLs: optional(boolean),
335
+ readsCredentials: optional(boolean),
336
+ loginRequired: optional(boolean),
337
+ singleSource: optional(boolean),
338
+ // 图片地址里不参与缓存键的查询参数名(不分大小写),例如每次都换的令牌与盐(ADR 0015「图片」)。尺寸参数内核另外固定去掉,不用写。
339
+ imageCacheIgnoredParameters: optional(array(string)),
340
+ // 要用 krillplayer.files 时写哪种协议(contract.md 6.1)。连哪台主机、哪个共享、用什么账号由内核向用户要,不写在 parameters 里,插件也读不到。
341
+ files: optional(FilesProtocol),
342
+ // 要用哪几把 App 自己的密钥(krillplayer.appKeys,contract.md 6.3)。只有预装插件拿得到;用户添加的插件写了也只拿到 null。
343
+ appKeys: optional(array(string)),
344
+ parameters: optional(array(Parameter)),
345
+ settings: optional(array(Parameter)),
346
+ unsupported: optional(PlatformCapabilities),
347
+ feedbackURL: optional(string),
348
+ contributes: optional(Contributions),
349
+ capabilities: array(Capability)
350
+ });
351
+ var PluginErrorKind = enumeration("PluginErrorKind", [
352
+ "regionRestricted",
353
+ "loginRequired",
354
+ "verificationRequired",
355
+ "ended",
356
+ "notStarted",
357
+ "refused",
358
+ "retryable",
359
+ "notFound",
360
+ "muted",
361
+ "rateLimited",
362
+ "contentRejected",
363
+ "other"
364
+ ], "other");
365
+ var PluginError = object("PluginError", {
366
+ kind: PluginErrorKind,
367
+ message: optional(string)
368
+ });
369
+ var SubtitleFormat = enumeration("SubtitleFormat", ["srt", "webvtt", "ass"]);
370
+ var PlayableSubtitle = object("PlayableSubtitle", {
371
+ id: string,
372
+ language: string,
373
+ title: optional(string),
374
+ format: SubtitleFormat,
375
+ url: string,
376
+ headers: optional(map(string))
377
+ });
378
+ var PlayableStream = object("PlayableStream", {
379
+ quality: string,
380
+ url: string,
381
+ headers: optional(map(string)),
382
+ audioURL: optional(string),
383
+ container: optional(enumeration("Container", ["mp4", "mov", "mkv", "ts", "flv", "hls", "dash", "webm", "mp3", "aac", "flac", "ogg"]))
384
+ });
385
+ var PlayableLine = object("PlayableLine", {
386
+ name: string,
387
+ streams: array(PlayableStream)
388
+ });
389
+ var Playable = object("Playable", {
390
+ timing: enumeration("PlayableTiming", ["live", "onDemand"]),
391
+ duration: optional(number),
392
+ resume: optional(number),
393
+ lines: array(PlayableLine),
394
+ expiresAt: optional(number),
395
+ trial: optional(object("PlayableTrial", { seconds: number, message: optional(string) })),
396
+ segments: optional(array(object("PlayableSegment", {
397
+ kind: enumeration("PlayableSegmentKind", ["intro", "outro", "chapter"]),
398
+ start: number,
399
+ end: number,
400
+ title: optional(string)
401
+ }))),
402
+ decryption: optional(object("PlayableDecryption", {
403
+ method: enumeration("PlayableDecryptionMethod", ["cencAesCtr"]),
404
+ key: string,
405
+ keyId: optional(string)
406
+ })),
407
+ subtitles: optional(array(PlayableSubtitle)),
408
+ // 这一路的原始文件名,给字幕插件与弹幕插件匹配用(contract.md 3.1);不给时内核用条目的文件名或标题。
409
+ filename: optional(string)
410
+ });
411
+ var Comment = object("Comment", {
412
+ id: string,
413
+ author: string,
414
+ text: string,
415
+ avatar: optional(string),
416
+ time: optional(number),
417
+ likes: optional(integer)
418
+ });
419
+ var EntriesPanel = object("EntriesPanel", {
420
+ kind: constant("entries"),
421
+ title: optional(string),
422
+ entries: array(Entry),
423
+ next: optional(string),
424
+ maxAge: optional(number)
425
+ });
426
+ var CommentsPanel = object("CommentsPanel", {
427
+ kind: constant("comments"),
428
+ comments: array(Comment),
429
+ next: optional(string),
430
+ maxAge: optional(number)
431
+ });
432
+ var PanelPage = union("PanelPage", "kind", [EntriesPanel, CommentsPanel], "PanelContent");
433
+ var ActionMessage = object("ActionMessage", { kind: constant("message"), message: string });
434
+ var ActionEntries = object("ActionEntries", { kind: constant("entries"), title: optional(string), entries: array(Entry) });
435
+ var ActionResult = union("ActionResult", "kind", [ActionMessage, ActionEntries]);
436
+ var ChannelStatus = object("ChannelStatus", {
437
+ id: string,
438
+ live: enumeration("ChannelLive", ["online", "offline", "unknown"], "unknown"),
439
+ offlineReason: optional(enumeration("OfflineReason", ["notLive", "rerun", "gone"], "notLive")),
440
+ unknownReason: optional(enumeration("UnknownReason", ["failed", "rateLimited", "loginRequired", "verificationRequired"], "failed")),
441
+ retryAfter: optional(number),
442
+ title: optional(string),
443
+ session: optional(string),
444
+ liveId: optional(string),
445
+ latest: optional(object("LatestItemSignal", { id: string, published: number, title: optional(string) }))
446
+ });
447
+ var ChannelImage = object("ChannelImage", { id: string, image: string });
448
+ var DanmakuFrame = object("DanmakuFrame", {
449
+ text: optional(string),
450
+ data: optional(bytes)
451
+ });
452
+ var CommentImage = object("CommentImage", { url: string, width: number, height: number });
453
+ var DanmakuComment = object("DanmakuComment", {
454
+ content: string,
455
+ username: string,
456
+ color: optional(integer),
457
+ senderId: optional(string),
458
+ messageId: optional(string),
459
+ time: optional(number),
460
+ offset: optional(number),
461
+ paid: optional(object("CommentPaid", { amount: number, currency: string })),
462
+ gift: optional(object("CommentGift", { name: string, count: integer })),
463
+ medal: optional(object("CommentMedal", { name: string, level: integer, color: optional(integer) })),
464
+ userLevel: optional(integer),
465
+ emoticons: optional(map(CommentImage)),
466
+ sticker: optional(CommentImage),
467
+ position: optional(enumeration("DanmakuPosition", ["scroll", "top", "bottom"], "scroll"))
468
+ });
469
+ var LiveDanmakuConnection = object("LiveDanmakuConnection", {
470
+ url: string,
471
+ headers: optional(map(string)),
472
+ handshake: array(DanmakuFrame),
473
+ heartbeat: optional(object("DanmakuHeartbeat", { frame: DanmakuFrame, interval: number })),
474
+ recent: optional(array(DanmakuComment))
475
+ });
476
+ var DanmakuBatch = object("DanmakuBatch", {
477
+ messages: array(DanmakuComment),
478
+ replies: optional(array(DanmakuFrame)),
479
+ resume: optional(string)
480
+ });
481
+ var DanmakuSegment = object("DanmakuSegment", {
482
+ start: number,
483
+ end: number,
484
+ messages: array(DanmakuComment)
485
+ });
486
+ var WorkQuery = object("WorkQuery", {
487
+ kind: enumeration("WorkQueryKind", ["movie", "episode"]),
488
+ ids: Ids,
489
+ title: string,
490
+ originalTitle: optional(string),
491
+ year: optional(integer),
492
+ season: optional(integer),
493
+ episode: optional(integer),
494
+ episodeTitle: optional(string),
495
+ absoluteEpisode: optional(integer)
496
+ });
497
+ var MediaQuery = object("MediaQuery", {
498
+ work: optional(WorkQuery),
499
+ filename: optional(string),
500
+ size: optional(integer),
501
+ duration: optional(number),
502
+ hashes: optional(map(string)),
503
+ languages: array(string)
504
+ });
505
+ var DanmakuMatch = object("DanmakuMatch", {
506
+ id: string,
507
+ title: string,
508
+ subtitle: optional(string),
509
+ episode: optional(integer),
510
+ count: optional(integer)
511
+ });
512
+ var PlaybackReport = object("PlaybackReport", {
513
+ item: string,
514
+ event: enumeration("PlaybackReportEvent", ["start", "progress", "end"]),
515
+ position: number,
516
+ duration: optional(number)
517
+ });
518
+ var SubtitleTrack = object("SubtitleTrack", {
519
+ id: string,
520
+ language: string,
521
+ title: optional(string),
522
+ attribution: optional(object("SubtitleAttribution", {
523
+ text: string,
524
+ url: string
525
+ }))
526
+ });
527
+ var Subtitle = object("Subtitle", {
528
+ format: SubtitleFormat,
529
+ data: optional(bytes),
530
+ content: optional(string),
531
+ url: optional(string),
532
+ headers: optional(map(string))
533
+ });
534
+ var M3UEntry = object("M3UEntry", {
535
+ url: string,
536
+ title: string,
537
+ duration: number,
538
+ tvgId: optional(string),
539
+ tvgName: optional(string),
540
+ logo: optional(string),
541
+ group: optional(string),
542
+ headers: optional(map(string)),
543
+ attributes: map(string)
544
+ });
545
+ var M3UPlaylist = object("M3UPlaylist", {
546
+ guideURLs: array(string),
547
+ attributes: map(string),
548
+ entries: array(M3UEntry)
549
+ });
550
+ var XMLTVSource = object("XMLTVSource", {
551
+ url: string,
552
+ headers: optional(map(string)),
553
+ maxAge: optional(number)
554
+ });
555
+ var XMLTVQuery = object("XMLTVQuery", {
556
+ channels: array(string),
557
+ from: number,
558
+ to: number
559
+ });
560
+ var XMLTVChannel = object("XMLTVChannel", {
561
+ id: string,
562
+ names: array(string),
563
+ icon: optional(string)
564
+ });
565
+ var XMLTVProgramme = object("XMLTVProgramme", {
566
+ channel: string,
567
+ start: number,
568
+ stop: optional(number),
569
+ title: string,
570
+ subtitle: optional(string),
571
+ description: optional(string),
572
+ categories: array(string),
573
+ icon: optional(string)
574
+ });
575
+ var RSSEnclosure = object("RSSEnclosure", {
576
+ url: string,
577
+ type: optional(string),
578
+ length: optional(integer)
579
+ });
580
+ var RSSEpisode = object("RSSEpisode", {
581
+ title: string,
582
+ guid: optional(string),
583
+ description: optional(string),
584
+ link: optional(string),
585
+ published: optional(number),
586
+ duration: optional(number),
587
+ season: optional(integer),
588
+ episode: optional(integer),
589
+ episodeType: optional(string),
590
+ image: optional(string),
591
+ enclosure: optional(RSSEnclosure)
592
+ });
593
+ var RSSFeed = object("RSSFeed", {
594
+ title: string,
595
+ description: optional(string),
596
+ link: optional(string),
597
+ image: optional(string),
598
+ author: optional(string),
599
+ language: optional(string),
600
+ // 取自 itunes:type:episodic 新的在前,serial 旧的在前。源里没写或写了别的就不带,插件按 episodic 排。
601
+ order: optional(PodcastOrder),
602
+ episodes: array(RSSEpisode)
603
+ });
604
+ var WorkKind = enumeration("WorkKind", ["movie", "series"]);
605
+ var ListName = enumeration("ListName", ["trending", "popular", "topRated", "upcoming", "nowPlaying", "onAir"]);
606
+ var Genre = enumeration("Genre", [
607
+ "action",
608
+ "adventure",
609
+ "animation",
610
+ "comedy",
611
+ "crime",
612
+ "documentary",
613
+ "drama",
614
+ "family",
615
+ "fantasy",
616
+ "history",
617
+ "horror",
618
+ "kids",
619
+ "music",
620
+ "mystery",
621
+ "news",
622
+ "reality",
623
+ "romance",
624
+ "scienceFiction",
625
+ "soap",
626
+ "talk",
627
+ "thriller",
628
+ "war",
629
+ "western"
630
+ ]);
631
+ var Network = enumeration("Network", [
632
+ "netflix",
633
+ "hbo",
634
+ "disneyPlus",
635
+ "appleTv",
636
+ "primeVideo",
637
+ "hulu",
638
+ "peacock",
639
+ "paramountPlus",
640
+ "iqiyi",
641
+ "tencentVideo",
642
+ "youku",
643
+ "bilibili",
644
+ "mangoTv"
645
+ ]);
646
+ var Work = object("Work", {
647
+ kind: WorkKind,
648
+ ids: Ids,
649
+ title: string,
650
+ originalTitle: optional(string),
651
+ year: optional(integer),
652
+ image: optional(string),
653
+ summary: optional(string)
654
+ });
655
+ var PagedWork = paged(Work);
656
+ var MetadataSearchOptions = object("MetadataSearchOptions", { year: optional(integer), cursor: optional(string) });
657
+ var MetadataListOptions = object("MetadataListOptions", {
658
+ genre: optional(Genre),
659
+ network: optional(Network),
660
+ country: optional(string),
661
+ year: optional(integer),
662
+ cursor: optional(string)
663
+ });
664
+ var LoginMethod = object("LoginMethod", {
665
+ kind: enumeration("LoginMethodKind", ["web", "qrCode", "fields"]),
666
+ title: string,
667
+ note: optional(string),
668
+ url: optional(string),
669
+ loggedInCookie: optional(string),
670
+ cookies: optional(array(string)),
671
+ fields: optional(array(object("LoginField", {
672
+ name: string,
673
+ title: string,
674
+ secret: optional(boolean),
675
+ placeholder: optional(string)
676
+ })))
677
+ });
678
+ var LoginQRCode = object("LoginQRCode", {
679
+ content: string,
680
+ key: string,
681
+ interval: optional(number),
682
+ expiresIn: optional(number)
683
+ });
684
+ var LoginPoll = object("LoginPoll", {
685
+ state: enumeration("LoginPollState", ["waiting", "scanned", "confirmed", "expired"]),
686
+ message: optional(string)
687
+ });
688
+ var LoginAccount = object("LoginAccount", {
689
+ name: string,
690
+ avatar: optional(string)
691
+ });
692
+ var CryptoAlgorithm = enumeration("CryptoAlgorithm", [
693
+ "RSASSA-PKCS1-v1_5",
694
+ "RSA-PSS",
695
+ "RSA-OAEP",
696
+ "ECDSA",
697
+ "Ed25519",
698
+ "HMAC",
699
+ "AES-CTR",
700
+ "AES-CBC",
701
+ "AES-GCM",
702
+ "AES-KW",
703
+ "ECDH",
704
+ "X25519",
705
+ "HKDF",
706
+ "PBKDF2"
707
+ ]);
708
+ var CryptoHash = enumeration("CryptoHash", ["SHA-1", "SHA-256", "SHA-384", "SHA-512"]);
709
+ var CryptoNamedCurve = enumeration("CryptoNamedCurve", ["P-256", "P-384", "P-521"]);
710
+ var CryptoKeyUsage = enumeration("CryptoKeyUsage", ["encrypt", "decrypt", "sign", "verify", "deriveKey", "deriveBits", "wrapKey", "unwrapKey"]);
711
+ var CryptoKeyFormat = enumeration("CryptoKeyFormat", ["raw", "spki", "pkcs8", "jwk"]);
712
+ var CryptoKeyAlgorithm = object("CryptoKeyAlgorithm", {
713
+ name: CryptoAlgorithm,
714
+ modulusLength: optional(integer),
715
+ publicExponent: optional(bytes),
716
+ hash: optional(object("CryptoHashAlgorithm", { name: CryptoHash })),
717
+ namedCurve: optional(CryptoNamedCurve),
718
+ length: optional(integer)
719
+ });
720
+ var CryptoKeyMaterial = object("CryptoKeyMaterial", {
721
+ kty: string,
722
+ crv: optional(string),
723
+ x: optional(string),
724
+ y: optional(string),
725
+ n: optional(string),
726
+ e: optional(string),
727
+ d: optional(string),
728
+ p: optional(string),
729
+ q: optional(string),
730
+ dp: optional(string),
731
+ dq: optional(string),
732
+ qi: optional(string),
733
+ k: optional(string)
734
+ });
735
+ var CryptoKey = object("CryptoKey", {
736
+ type: enumeration("CryptoKeyType", ["secret", "public", "private"]),
737
+ extractable: boolean,
738
+ algorithm: CryptoKeyAlgorithm,
739
+ usages: array(CryptoKeyUsage),
740
+ material: CryptoKeyMaterial
741
+ });
742
+ var CryptoKeyPair = object("CryptoKeyPair", { publicKey: CryptoKey, privateKey: CryptoKey });
743
+ var SLOT_RETURNS = {
744
+ browse: {
745
+ lists: { schema: array(BrowseList) },
746
+ parameters: { schema: array(Parameter) },
747
+ options: { schema: array(Option) },
748
+ list: { schema: PagedEntry },
749
+ search: { schema: PagedEntry },
750
+ channel: { schema: ChannelPage },
751
+ collection: { schema: CollectionPage },
752
+ schedule: { schema: map(array(ScheduleEntry)) }
753
+ },
754
+ music: {
755
+ sections: { schema: array(MusicSection) },
756
+ parameters: { schema: array(Parameter) },
757
+ options: { schema: array(Option) },
758
+ list: { schema: PagedMusicEntry },
759
+ search: { schema: PagedMusicEntry },
760
+ artist: { schema: ArtistPage },
761
+ album: { schema: AlbumPage },
762
+ playlist: { schema: PlaylistPage },
763
+ lyrics: { schema: Lyrics, nullable: true }
764
+ },
765
+ play: { start: { schema: Playable } },
766
+ resources: { find: { schema: array(ResourceVersion) } },
767
+ subtitles: { list: { schema: array(SubtitleTrack) }, search: { schema: array(SubtitleTrack) }, fetch: { schema: Subtitle } },
768
+ danmaku: {
769
+ connect: { schema: LiveDanmakuConnection },
770
+ decode: { schema: DanmakuBatch },
771
+ segment: { schema: DanmakuSegment },
772
+ match: { schema: array(DanmakuMatch) },
773
+ comments: { schema: DanmakuSegment }
774
+ },
775
+ status: { check: { schema: array(ChannelStatus) }, images: { schema: array(ChannelImage) } },
776
+ login: {
777
+ methods: { schema: array(LoginMethod) },
778
+ qrCode: { schema: LoginQRCode },
779
+ poll: { schema: LoginPoll },
780
+ account: { schema: LoginAccount, nullable: true }
781
+ },
782
+ views: { panel: { schema: PanelPage }, action: { schema: ActionResult } },
783
+ parameters: { options: { schema: array(Option) } },
784
+ resolve: { "": { schema: Resolved, nullable: true } }
785
+ };
786
+
787
+ // host/json-depth.ts
788
+ function pluginJSONText(bytes2) {
789
+ if (bytes2[0] === 239 && bytes2[1] === 187 && bytes2[2] === 191) return void 0;
790
+ if (bytes2.includes(0)) return void 0;
791
+ try {
792
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes2);
793
+ } catch {
794
+ return void 0;
795
+ }
796
+ }
797
+ function nestedTooDeep(json, limit = VALUE_LIMITS.depth) {
798
+ let depth = 0;
799
+ let inString = false;
800
+ let escaped = false;
801
+ for (let i = 0; i < json.length; i += 1) {
802
+ const code = json.charCodeAt(i);
803
+ if (inString) {
804
+ if (escaped) escaped = false;
805
+ else if (code === 92) escaped = true;
806
+ else if (code === 34) inString = false;
807
+ continue;
808
+ }
809
+ if (code === 34) inString = true;
810
+ else if (code === 91 || code === 123) {
811
+ depth += 1;
812
+ if (depth > limit) return true;
813
+ } else if (code === 93 || code === 125) depth -= 1;
814
+ }
815
+ return false;
816
+ }
817
+
818
+ // host/crypto.ts
819
+ var RSA = ["RSASSA-PKCS1-v1_5", "RSA-PSS", "RSA-OAEP"];
820
+ var AES = ["AES-CTR", "AES-CBC", "AES-GCM"];
821
+ var SIGNING = ["RSASSA-PKCS1-v1_5", "RSA-PSS", "ECDSA", "Ed25519", "HMAC"];
822
+ var ENCRYPTION = ["RSA-OAEP", ...AES];
823
+ var AES_KEYS = [...AES, "AES-KW"];
824
+ var KDF = ["HKDF", "PBKDF2"];
825
+ var AGREEMENT = ["ECDH", "X25519"];
826
+ var WRAPPING = ["AES-KW", ...ENCRYPTION];
827
+ var SUPPORTED = {
828
+ generateKey: CryptoAlgorithm.values.filter((name) => !KDF.includes(name)),
829
+ importKey: CryptoAlgorithm.values,
830
+ exportKey: CryptoAlgorithm.values,
831
+ sign: SIGNING,
832
+ verify: SIGNING,
833
+ encrypt: ENCRYPTION,
834
+ decrypt: ENCRYPTION,
835
+ digest: [],
836
+ deriveBits: [...AGREEMENT, ...KDF],
837
+ deriveKey: [...AGREEMENT, ...KDF],
838
+ wrapKey: WRAPPING,
839
+ unwrapKey: WRAPPING
840
+ };
841
+ var USAGES = {
842
+ "RSASSA-PKCS1-v1_5": { public: ["verify"], private: ["sign"] },
843
+ "RSA-PSS": { public: ["verify"], private: ["sign"] },
844
+ "RSA-OAEP": { public: ["encrypt", "wrapKey"], private: ["decrypt", "unwrapKey"] },
845
+ ECDSA: { public: ["verify"], private: ["sign"] },
846
+ Ed25519: { public: ["verify"], private: ["sign"] },
847
+ HMAC: { secret: ["sign", "verify"] },
848
+ "AES-CTR": { secret: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] },
849
+ "AES-CBC": { secret: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] },
850
+ "AES-GCM": { secret: ["encrypt", "decrypt", "wrapKey", "unwrapKey"] },
851
+ "AES-KW": { secret: ["wrapKey", "unwrapKey"] },
852
+ ECDH: { public: [], private: ["deriveKey", "deriveBits"] },
853
+ X25519: { public: [], private: ["deriveKey", "deriveBits"] },
854
+ HKDF: { secret: ["deriveKey", "deriveBits"] },
855
+ PBKDF2: { secret: ["deriveKey", "deriveBits"] }
856
+ };
857
+ var ktyOf = (name) => RSA.includes(name) ? "RSA" : name === "ECDSA" || name === "ECDH" ? "EC" : name === "Ed25519" || name === "X25519" ? "OKP" : "oct";
858
+ var ELLIPTIC = ["ECDSA", "ECDH"];
859
+ var fixedCurve = (name) => name === "Ed25519" || name === "X25519" ? name : void 0;
860
+ var HASH_BYTES = { "SHA-1": 20, "SHA-256": 32, "SHA-384": 48, "SHA-512": 64 };
861
+ var HASH_BLOCK_BITS = { "SHA-1": 512, "SHA-256": 512, "SHA-384": 1024, "SHA-512": 1024 };
862
+ var COORDINATE_BYTES = { "P-256": 32, "P-384": 48, "P-521": 66 };
863
+ var RSA_MODULUS_LENGTHS = [1024, 2048, 3072, 4096];
864
+ var GCM_TAG_LENGTHS = [32, 64, 96, 104, 112, 120, 128];
865
+ var MAX_KEY_BYTES = 65536;
866
+ var MAX_HMAC_BYTES = 1024;
867
+ var MAX_KEY_FIELD = 87382;
868
+ var MAX_DERIVE_BYTES = 1024;
869
+ var MAX_PBKDF2_WORK = 2e6;
870
+ var MAX_WRAPPED_BYTES = MAX_KEY_BYTES;
871
+ var fieldsFit = (fields) => Object.values(fields).every((field) => typeof field !== "string" || field.length <= MAX_KEY_FIELD);
872
+ var subtle = () => globalThis.crypto.subtle;
873
+ var fail = (operation, message) => new TypeError(`krillplayer.crypto.subtle.${operation}: ${message}`);
874
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !ArrayBuffer.isView(value) && !(value instanceof ArrayBuffer);
875
+ function bytesOf(value) {
876
+ if (typeof value === "string") return new TextEncoder().encode(value);
877
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
878
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength));
879
+ return void 0;
880
+ }
881
+ function bytesArgument(operation, value, what) {
882
+ const bytes2 = bytesOf(value);
883
+ if (bytes2 === void 0) throw fail(operation, `${what} must be bytes or a string`);
884
+ return bytes2;
885
+ }
886
+ var letters = (first, count) => Array.from({ length: count }, (_, i) => String.fromCharCode(first.charCodeAt(0) + i)).join("");
887
+ var ALPHABET = `${letters("A", 26)}${letters("a", 26)}${letters("0", 10)}-_`;
888
+ function base64url(bytes2) {
889
+ let text = "";
890
+ for (let i = 0; i < bytes2.length; i += 3) {
891
+ const n = bytes2[i] << 16 | (bytes2[i + 1] ?? 0) << 8 | (bytes2[i + 2] ?? 0);
892
+ const count = Math.min(3, bytes2.length - i) + 1;
893
+ for (let j = 0; j < count; j += 1) text += ALPHABET[n >> 18 - 6 * j & 63];
894
+ }
895
+ return text;
896
+ }
897
+ function fromBase64url(text) {
898
+ if (typeof text !== "string" || text.length % 4 === 1) return void 0;
899
+ const values = [];
900
+ for (const character of text) {
901
+ const value = ALPHABET.indexOf(character);
902
+ if (value < 0) return void 0;
903
+ values.push(value);
904
+ }
905
+ const bytes2 = new Uint8Array(Math.floor(values.length * 6 / 8));
906
+ for (let i = 0, bit = 0; i < bytes2.length; i += 1, bit += 8) {
907
+ const at = Math.floor(bit / 6);
908
+ const shift = bit % 6;
909
+ const word = values[at] << 12 | (values[at + 1] ?? 0) << 6 | (values[at + 2] ?? 0);
910
+ bytes2[i] = word >> 10 - shift & 255;
911
+ }
912
+ return base64url(bytes2) === text ? bytes2 : void 0;
913
+ }
914
+ var PEM_LABELS = { spki: "PUBLIC KEY", pkcs8: "PRIVATE KEY" };
915
+ var isPEMSpace = (byte) => byte === 32 || byte === 9 || byte === 13 || byte === 10;
916
+ function fromPEM(operation, format, data) {
917
+ const expected = PEM_LABELS[format];
918
+ if (expected === void 0 || data.find((byte) => !isPEMSpace(byte)) !== 45) return data;
919
+ const invalid = () => fail(operation, "keyData is not valid PEM");
920
+ if (data.some((byte) => byte > 126 || byte < 32 && !isPEMSpace(byte))) throw invalid();
921
+ const text = new TextDecoder().decode(data).trim();
922
+ const begin = "-----BEGIN ";
923
+ const close = text.startsWith(begin) ? text.indexOf("-----", begin.length) : -1;
924
+ if (close < 0) throw invalid();
925
+ const label = text.slice(begin.length, close);
926
+ if (label === "" || /[^\x20-\x2c\x2e-\x7e]/.test(label)) throw invalid();
927
+ const end = `-----END ${label}-----`;
928
+ if (text.length < close + 5 + end.length || !text.endsWith(end)) throw invalid();
929
+ if (label !== expected) throw fail(operation, `the PEM label is "${label}", ${format} needs "${expected}"`);
930
+ const body = text.slice(close + 5, text.length - end.length).replace(/[ \t\r\n]/g, "");
931
+ if (body === "" || body.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(body)) throw invalid();
932
+ const decoded = fromBase64url(body.replace(/=+$/, "").replaceAll("+", "-").replaceAll("/", "_"));
933
+ if (decoded === void 0) throw invalid();
934
+ return decoded;
935
+ }
936
+ function algorithmOf(operation, algorithm, listing = operation) {
937
+ const params = typeof algorithm === "string" ? { name: algorithm } : isObject(algorithm) ? algorithm : void 0;
938
+ if (params === void 0 || typeof params.name !== "string") throw fail(operation, "algorithm needs a name");
939
+ const given = params.name;
940
+ const name = CryptoAlgorithm.values.find((value) => value.toLowerCase() === given.toLowerCase());
941
+ if (name === void 0 || !SUPPORTED[listing].includes(name)) throw fail(operation, `${given} is not a supported algorithm for ${operation}`);
942
+ return { name, params };
943
+ }
944
+ function hashOf(operation, value, owner) {
945
+ const given = typeof value === "string" ? value : isObject(value) && typeof value.name === "string" ? value.name : void 0;
946
+ if (given === void 0) throw fail(operation, `${owner} needs hash`);
947
+ const hash = CryptoHash.values.find((name) => name.toLowerCase() === given.toLowerCase());
948
+ if (hash === void 0) throw fail(operation, `${given} is not a supported hash (SHA-1, SHA-256, SHA-384, SHA-512)`);
949
+ return hash;
950
+ }
951
+ function curveOf(operation, value, owner) {
952
+ if (typeof value !== "string") throw fail(operation, `${owner} needs namedCurve`);
953
+ const curve = CryptoNamedCurve.values.find((name) => name === value);
954
+ if (curve === void 0) throw fail(operation, `${value} is not a supported curve (P-256, P-384, P-521)`);
955
+ return curve;
956
+ }
957
+ function integerOf(operation, params, field, owner) {
958
+ const value = params[field];
959
+ if (typeof value !== "number" || !Number.isInteger(value) || Math.abs(value) >= 1e15) throw fail(operation, `${owner} needs ${field}`);
960
+ return value;
961
+ }
962
+ function bytesParam(operation, params, field, owner) {
963
+ const bytes2 = bytesOf(params[field]);
964
+ if (bytes2 === void 0) throw fail(operation, `${owner} needs ${field}`);
965
+ return bytes2;
966
+ }
967
+ function optionalBytesParam(operation, params, field, owner) {
968
+ return params[field] === void 0 ? void 0 : bytesParam(operation, params, field, owner);
969
+ }
970
+ function extractableOf(operation, value) {
971
+ if (typeof value !== "boolean") throw fail(operation, "extractable must be a boolean");
972
+ return value;
973
+ }
974
+ function usagesOf(operation, value) {
975
+ if (!Array.isArray(value) || value.some((usage) => typeof usage !== "string")) throw fail(operation, "usages must be an array of usages");
976
+ for (const usage of value) {
977
+ if (!CryptoKeyUsage.values.includes(usage)) throw fail(operation, `${usage} is not a key usage`);
978
+ }
979
+ return CryptoKeyUsage.values.filter((usage) => value.includes(usage));
980
+ }
981
+ function formatOf(operation, value) {
982
+ const format = CryptoKeyFormat.values.find((name) => name === value);
983
+ if (format === void 0) throw fail(operation, `${typeof value === "string" ? value : "the format"} is not a key format (raw, spki, pkcs8, jwk)`);
984
+ return format;
985
+ }
986
+ async function keyOf(operation, value, what = "key") {
987
+ const bad = () => fail(operation, `${what} is not a key from krillplayer.crypto.subtle`);
988
+ if (!isObject(value) || !isObject(value.algorithm) || !isObject(value.material)) throw bad();
989
+ const { type, extractable, algorithm, usages, material } = value;
990
+ if (type !== "secret" && type !== "public" && type !== "private") throw bad();
991
+ if (typeof extractable !== "boolean" || !Array.isArray(usages) || usages.some((usage) => !CryptoKeyUsage.values.includes(usage))) throw bad();
992
+ const name = CryptoAlgorithm.values.find((known) => known === algorithm.name);
993
+ if (name === void 0 || typeof material.kty !== "string") throw bad();
994
+ if (!Object.values(material).every((field) => typeof field === "string") || !fieldsFit(material)) throw bad();
995
+ const hash = isObject(algorithm.hash) ? CryptoHash.values.find((known) => known === algorithm.hash.name) : void 0;
996
+ if ((RSA.includes(name) || name === "HMAC") && hash === void 0) throw bad();
997
+ const expected = USAGES[name][type];
998
+ if (expected === void 0 || usages.some((usage) => !expected.includes(usage))) throw bad();
999
+ if (material.kty !== ktyOf(name) || type === "private" !== (material.d !== void 0)) throw bad();
1000
+ if (ELLIPTIC.includes(name) && (!CryptoNamedCurve.values.includes(algorithm.namedCurve) || material.crv !== algorithm.namedCurve)) throw bad();
1001
+ if (fixedCurve(name) !== void 0 && material.crv !== fixedCurve(name)) throw bad();
1002
+ if (KDF.includes(name) && extractable) throw bad();
1003
+ if (!usableMaterial(name, type, material, algorithm.namedCurve)) throw bad();
1004
+ const derived = keyAlgorithm(name, material, { hash, curve: algorithm.namedCurve });
1005
+ if (!sameSize(algorithm.modulusLength, derived.modulusLength) || !sameSize(algorithm.length, derived.length)) throw bad();
1006
+ const key = makeKey(type, extractable, derived, usages, material);
1007
+ try {
1008
+ await webKey(key, USAGES[name][type][0]);
1009
+ if (type === "private" && (ELLIPTIC.includes(name) || fixedCurve(name) !== void 0)) await checkPair(key.material, name, key.algorithm.namedCurve);
1010
+ } catch {
1011
+ throw bad();
1012
+ }
1013
+ return key;
1014
+ }
1015
+ function usableMaterial(name, type, material, curve) {
1016
+ const size = (field) => fromBase64url(material[field])?.length;
1017
+ if (name === "HMAC") return (size("k") ?? 0) > 0 && size("k") <= MAX_HMAC_BYTES;
1018
+ if (AES_KEYS.includes(name)) return [16, 24, 32].includes(size("k") ?? 0);
1019
+ if (KDF.includes(name)) return size("k") !== void 0 && size("k") <= MAX_DERIVE_BYTES;
1020
+ if (RSA.includes(name)) {
1021
+ const modulus = fromBase64url(material.n);
1022
+ const parts = type === "private" ? PRIVATE_FIELDS : [];
1023
+ return modulus !== void 0 && bitLength(modulus) >= 512 && (size("e") ?? 0) > 0 && parts.every((field) => size(field) !== void 0);
1024
+ }
1025
+ const coordinate = ELLIPTIC.includes(name) ? COORDINATE_BYTES[curve] : 32;
1026
+ const fields = [...ELLIPTIC.includes(name) ? ["x", "y"] : ["x"], ...type === "private" ? ["d"] : []];
1027
+ return fields.every((field) => size(field) === coordinate);
1028
+ }
1029
+ var sameSize = (given, derived) => derived === void 0 ? given === void 0 : given === derived;
1030
+ function checkKey(operation, key, name, usage) {
1031
+ if (key.algorithm.name !== name) throw fail(operation, `the key is ${article(key.algorithm.name)} ${key.algorithm.name} key, not ${name}`);
1032
+ if (!key.usages.includes(usage)) throw fail(operation, `the key's usages do not include ${usage}`);
1033
+ }
1034
+ function requireType(operation, key, type) {
1035
+ if (key.type !== type) throw fail(operation, `${operation} needs a ${type} key`);
1036
+ }
1037
+ var hashOfKey = (key) => key.algorithm.hash.name;
1038
+ async function webKey(key, usage) {
1039
+ const usages = usage === void 0 ? [] : [usage];
1040
+ if (KDF.includes(key.algorithm.name)) return subtle().importKey("raw", fromBase64url(key.material.k), key.algorithm.name, false, usages);
1041
+ return subtle().importKey("jwk", { ...key.material, ext: true }, webAlgorithm(key.algorithm), true, usages);
1042
+ }
1043
+ function webAlgorithm(algorithm) {
1044
+ if (RSA.includes(algorithm.name) || algorithm.name === "HMAC") return { name: algorithm.name, hash: algorithm.hash.name };
1045
+ if (ELLIPTIC.includes(algorithm.name)) return { name: algorithm.name, namedCurve: algorithm.namedCurve };
1046
+ return { name: algorithm.name };
1047
+ }
1048
+ var bitLength = (bytes2) => {
1049
+ const first = bytes2.findIndex((byte) => byte !== 0);
1050
+ return first < 0 ? 0 : (bytes2.length - first - 1) * 8 + (32 - Math.clz32(bytes2[first]));
1051
+ };
1052
+ var stripZeros = (bytes2) => {
1053
+ const first = bytes2.findIndex((byte) => byte !== 0);
1054
+ return first < 0 ? new Uint8Array(0) : bytes2.slice(first);
1055
+ };
1056
+ function keyAlgorithm(name, material, extra) {
1057
+ if (RSA.includes(name)) {
1058
+ return { name, modulusLength: bitLength(fromBase64url(material.n)), publicExponent: stripZeros(fromBase64url(material.e)), hash: { name: extra.hash } };
1059
+ }
1060
+ if (ELLIPTIC.includes(name)) return { name, namedCurve: extra.curve };
1061
+ if (name === "HMAC") return { name, length: fromBase64url(material.k).length * 8, hash: { name: extra.hash } };
1062
+ if (AES_KEYS.includes(name)) return { name, length: fromBase64url(material.k).length * 8 };
1063
+ return { name };
1064
+ }
1065
+ var PRIVATE_FIELDS = ["d", "p", "q", "dp", "dq", "qi"];
1066
+ var MATERIAL_FIELDS = ["kty", "crv", "x", "y", "n", "e", "d", "p", "q", "dp", "dq", "qi", "k"];
1067
+ function materialOf(jwk) {
1068
+ return Object.fromEntries(MATERIAL_FIELDS.filter((field) => typeof jwk[field] === "string").map((field) => [field, jwk[field]]));
1069
+ }
1070
+ var publicMaterial = (material) => Object.fromEntries(Object.entries(material).filter(([field]) => !PRIVATE_FIELDS.includes(field)));
1071
+ function makeKey(type, extractable, algorithm, usages, material) {
1072
+ return { type, extractable, algorithm, usages, material };
1073
+ }
1074
+ function jwkAlg(name, hash, bits, curve) {
1075
+ const size = hash?.slice(4);
1076
+ switch (name) {
1077
+ case "RSASSA-PKCS1-v1_5":
1078
+ return `RS${size}`;
1079
+ case "RSA-PSS":
1080
+ return `PS${size}`;
1081
+ case "RSA-OAEP":
1082
+ return hash === "SHA-1" ? "RSA-OAEP" : `RSA-OAEP-${size}`;
1083
+ case "HMAC":
1084
+ return `HS${size}`;
1085
+ case "AES-CTR":
1086
+ case "AES-CBC":
1087
+ case "AES-GCM":
1088
+ case "AES-KW":
1089
+ return `A${bits}${name.slice(4)}`;
1090
+ case "Ed25519":
1091
+ return "Ed25519";
1092
+ case "ECDSA":
1093
+ return curve === void 0 ? void 0 : `ES${curve === "P-521" ? "512" : curve.slice(2)}`;
1094
+ case "ECDH":
1095
+ case "X25519":
1096
+ case "HKDF":
1097
+ case "PBKDF2":
1098
+ return void 0;
1099
+ }
1100
+ }
1101
+ async function generateKey(algorithm, extractableValue, usagesValue) {
1102
+ const operation = "generateKey";
1103
+ const { name, params } = algorithmOf(operation, algorithm);
1104
+ const extractable = extractableOf(operation, extractableValue);
1105
+ const usages = usagesOf(operation, usagesValue);
1106
+ const allowed = Object.values(USAGES[name]).flat();
1107
+ let hash;
1108
+ let curve;
1109
+ if (RSA.includes(name)) {
1110
+ const modulusLength = integerOf(operation, params, "modulusLength", name);
1111
+ const exponent = bytesParam(operation, params, "publicExponent", name);
1112
+ hash = hashOf(operation, params.hash, name);
1113
+ checkGeneratedUsages(operation, name, usages, allowed);
1114
+ if (!RSA_MODULUS_LENGTHS.includes(modulusLength)) throw fail(operation, `modulusLength must be 1024, 2048, 3072 or 4096, not ${modulusLength}`);
1115
+ if (stripZeros(exponent).join() !== "1,0,1") throw fail(operation, "publicExponent must be 65537 ([1, 0, 1])");
1116
+ } else if (ELLIPTIC.includes(name)) {
1117
+ curve = curveOf(operation, params.namedCurve, name);
1118
+ checkGeneratedUsages(operation, name, usages, allowed);
1119
+ } else if (name === "HMAC") {
1120
+ hash = hashOf(operation, params.hash, name);
1121
+ const length = params.length === void 0 ? HASH_BLOCK_BITS[hash] : integerOf(operation, params, "length", name);
1122
+ checkGeneratedUsages(operation, name, usages, allowed);
1123
+ if (length <= 0 || length % 8 !== 0) throw fail(operation, `HMAC length must be a positive multiple of 8, not ${length}`);
1124
+ if (length > MAX_HMAC_BYTES * 8) throw fail(operation, `an HMAC key can be at most ${MAX_HMAC_BYTES * 8} bits, not ${length}`);
1125
+ return secretKey(operation, name, extractable, usages, globalThis.crypto.getRandomValues(new Uint8Array(length / 8)), hash);
1126
+ } else if (AES_KEYS.includes(name)) {
1127
+ const length = integerOf(operation, params, "length", name);
1128
+ checkGeneratedUsages(operation, name, usages, allowed);
1129
+ if (![128, 192, 256].includes(length)) throw fail(operation, `an AES key must be 128, 192 or 256 bits, not ${length}`);
1130
+ return secretKey(operation, name, extractable, usages, globalThis.crypto.getRandomValues(new Uint8Array(length / 8)));
1131
+ } else {
1132
+ checkGeneratedUsages(operation, name, usages, allowed);
1133
+ }
1134
+ const privateUsages = usages.filter((usage) => USAGES[name].private.includes(usage));
1135
+ const publicUsages = usages.filter((usage) => USAGES[name].public.includes(usage));
1136
+ if (privateUsages.length === 0) throw fail(operation, "a private key needs at least one usage");
1137
+ const generated = await subtle().generateKey(
1138
+ RSA.includes(name) ? { name, modulusLength: integerOf(operation, params, "modulusLength", name), publicExponent: new Uint8Array([1, 0, 1]), hash } : ELLIPTIC.includes(name) ? { name, namedCurve: curve } : { name },
1139
+ true,
1140
+ [...USAGES[name].private, ...USAGES[name].public]
1141
+ );
1142
+ const material = materialOf(await subtle().exportKey("jwk", generated.privateKey));
1143
+ const keyAlg = keyAlgorithm(name, material, { hash, curve });
1144
+ return {
1145
+ publicKey: makeKey("public", true, keyAlg, publicUsages, publicMaterial(material)),
1146
+ privateKey: makeKey("private", extractable, keyAlg, privateUsages, material)
1147
+ };
1148
+ }
1149
+ function checkGeneratedUsages(operation, name, usages, allowed) {
1150
+ const wrong = usages.find((usage) => !allowed.includes(usage));
1151
+ if (wrong !== void 0) throw fail(operation, `${wrong} is not a usage of ${name} keys`);
1152
+ }
1153
+ function secretKey(operation, name, extractable, usages, bytes2, hash) {
1154
+ if (usages.length === 0) throw fail(operation, "a secret key needs at least one usage");
1155
+ const material = { kty: "oct", k: base64url(bytes2) };
1156
+ return makeKey("secret", extractable, keyAlgorithm(name, material, { hash }), usages, material);
1157
+ }
1158
+ var IMPORT_FORMATS = (name) => RSA.includes(name) ? ["spki", "pkcs8", "jwk"] : KDF.includes(name) ? ["raw"] : ELLIPTIC.includes(name) || fixedCurve(name) !== void 0 ? ["raw", "spki", "pkcs8", "jwk"] : ["raw", "jwk"];
1159
+ function importKey(formatValue, keyData, algorithm, extractableValue, usagesValue) {
1160
+ return importKeyAs("importKey", formatValue, keyData, algorithm, extractableValue, usagesValue);
1161
+ }
1162
+ async function importKeyAs(operation, formatValue, keyData, algorithm, extractableValue, usagesValue) {
1163
+ const format = formatOf(operation, formatValue);
1164
+ const jwk = format === "jwk" ? keyData : void 0;
1165
+ if (format === "jwk" && !isObject(jwk)) throw fail(operation, "jwk key data must be an object");
1166
+ if (format === "jwk" && !fieldsFit(jwk)) throw fail(operation, `the JWK has a field longer than ${MAX_KEY_FIELD} characters`);
1167
+ const given = format === "jwk" ? void 0 : bytesArgument(operation, keyData, "keyData");
1168
+ if (given !== void 0 && given.length > MAX_KEY_BYTES) throw fail(operation, `keyData can be at most ${MAX_KEY_BYTES} bytes, not ${given.length}`);
1169
+ const data = given === void 0 ? void 0 : fromPEM(operation, format, given);
1170
+ const { name, params } = algorithmOf(operation, algorithm, "importKey");
1171
+ const hash = RSA.includes(name) || name === "HMAC" ? hashOf(operation, params.hash, name) : void 0;
1172
+ const curve = ELLIPTIC.includes(name) ? curveOf(operation, params.namedCurve, name) : void 0;
1173
+ const hmacLength = name === "HMAC" && params.length !== void 0 ? integerOf(operation, params, "length", name) : void 0;
1174
+ const extractable = extractableOf(operation, extractableValue);
1175
+ const usages = usagesOf(operation, usagesValue);
1176
+ if (!IMPORT_FORMATS(name).includes(format)) throw fail(operation, `${name} keys cannot be imported as ${format}`);
1177
+ const symmetric = name === "HMAC" || AES_KEYS.includes(name) || KDF.includes(name);
1178
+ const type = symmetric ? "secret" : format === "pkcs8" || format === "jwk" && jwk.d !== void 0 ? "private" : "public";
1179
+ const wrong = usages.find((usage) => !USAGES[name][type].includes(usage));
1180
+ if (wrong !== void 0) throw fail(operation, `${wrong} is not a usage of a ${type} ${name} key`);
1181
+ if (KDF.includes(name) && extractable) throw fail(operation, `${name} keys cannot be extractable`);
1182
+ if (jwk !== void 0) checkJWK(operation, jwk, name, type, hash, curve, extractable, usages);
1183
+ const invalid = () => fail(operation, `the ${format} data is not a valid ${name} key`);
1184
+ let material;
1185
+ if (symmetric) {
1186
+ const bytes2 = data ?? fromBase64url(jwk.k);
1187
+ if (bytes2 === void 0) throw invalid();
1188
+ if (AES_KEYS.includes(name) && ![16, 24, 32].includes(bytes2.length)) throw fail(operation, `an AES key must be 128, 192 or 256 bits, not ${bytes2.length * 8}`);
1189
+ if (name === "HMAC" && bytes2.length === 0) throw invalid();
1190
+ if (name === "HMAC" && bytes2.length > MAX_HMAC_BYTES) throw fail(operation, `an HMAC key can be at most ${MAX_HMAC_BYTES * 8} bits, not ${bytes2.length * 8}`);
1191
+ if (KDF.includes(name) && bytes2.length > MAX_DERIVE_BYTES) {
1192
+ throw fail(operation, `${name} key material can be at most ${MAX_DERIVE_BYTES * 8} bits, not ${bytes2.length * 8}`);
1193
+ }
1194
+ if (hmacLength !== void 0 && hmacLength !== bytes2.length * 8) {
1195
+ throw fail(operation, `HMAC length ${hmacLength} does not match the ${bytes2.length * 8}-bit key data`);
1196
+ }
1197
+ material = { kty: "oct", k: base64url(bytes2) };
1198
+ } else {
1199
+ if (format === "raw" && ELLIPTIC.includes(name) && (data[0] !== 4 || data.length !== 1 + 2 * COORDINATE_BYTES[curve])) throw invalid();
1200
+ if (format === "raw" && fixedCurve(name) !== void 0 && data.length !== 32) throw invalid();
1201
+ const imported = await webImport(format, data ?? materialOf(jwk), name, hash, curve, type).catch(() => {
1202
+ throw invalid();
1203
+ });
1204
+ material = materialOf(await subtle().exportKey("jwk", imported));
1205
+ if (format === "jwk" && type === "private" && !RSA.includes(name)) await checkPair(material, name, curve).catch(() => {
1206
+ throw invalid();
1207
+ });
1208
+ }
1209
+ if (usages.length === 0 && type !== "public") throw fail(operation, `a ${type} key needs at least one usage`);
1210
+ return makeKey(type, extractable, keyAlgorithm(name, material, { hash, curve }), usages, material);
1211
+ }
1212
+ function webImport(format, keyData, name, hash, curve, type) {
1213
+ const algorithm = RSA.includes(name) ? { name, hash } : ELLIPTIC.includes(name) ? { name, namedCurve: curve } : { name };
1214
+ const usages = [...USAGES[name][type]];
1215
+ return format === "jwk" ? subtle().importKey("jwk", { ...keyData, ext: true }, algorithm, true, usages) : subtle().importKey(format, keyData, algorithm, true, usages);
1216
+ }
1217
+ async function checkPair(material, keyName, curve) {
1218
+ if (keyName === "X25519") {
1219
+ const pkcs8 = new Uint8Array([...X25519_PKCS8_PREFIX, ...fromBase64url(material.d)]);
1220
+ const imported = await subtle().importKey("pkcs8", pkcs8, { name: keyName }, true, ["deriveBits"]);
1221
+ if ((await subtle().exportKey("jwk", imported)).x !== material.x) throw new Error("not a pair");
1222
+ return;
1223
+ }
1224
+ const name = keyName === "ECDH" ? "ECDSA" : keyName;
1225
+ const algorithm = name === "ECDSA" ? { name, namedCurve: curve } : { name };
1226
+ const signer = await subtle().importKey("jwk", { ...material, ext: true }, algorithm, false, ["sign"]);
1227
+ const verifier = await subtle().importKey("jwk", { ...publicMaterial(material), ext: true }, algorithm, false, ["verify"]);
1228
+ const params = name === "ECDSA" ? { name, hash: "SHA-256" } : { name };
1229
+ const probe = new Uint8Array([1]);
1230
+ const signature = new Uint8Array(await subtle().sign(params, signer, probe));
1231
+ if (!await subtle().verify(params, verifier, signature, probe)) throw new Error("not a pair");
1232
+ }
1233
+ var X25519_PKCS8_PREFIX = [48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 110, 4, 34, 4, 32];
1234
+ function checkJWK(operation, jwk, name, type, hash, curve, extractable, usages) {
1235
+ const kty = ktyOf(name);
1236
+ if (jwk.kty !== kty) throw fail(operation, `the JWK kty must be ${kty}`);
1237
+ const crv = ELLIPTIC.includes(name) ? curve : fixedCurve(name);
1238
+ if (crv !== void 0 && jwk.crv !== crv) throw fail(operation, `the JWK crv must be ${crv}`);
1239
+ if (jwk.alg !== void 0 && !AGREEMENT.includes(name)) {
1240
+ const bits = AES_KEYS.includes(name) ? (fromBase64url(jwk.k)?.length ?? 0) * 8 : void 0;
1241
+ const expected = jwkAlg(name, hash, bits, curve);
1242
+ if (jwk.alg !== expected && !(name === "Ed25519" && jwk.alg === "EdDSA")) throw fail(operation, `the JWK alg ${String(jwk.alg)} does not match ${expected}`);
1243
+ }
1244
+ if (jwk.use !== void 0 && usages.length > 0) {
1245
+ const use = ENCRYPTION.includes(name) || name === "AES-KW" || AGREEMENT.includes(name) ? "enc" : "sig";
1246
+ if (jwk.use !== use) throw fail(operation, `the JWK use must be ${use}`);
1247
+ }
1248
+ if (jwk.key_ops !== void 0) {
1249
+ if (!Array.isArray(jwk.key_ops)) throw fail(operation, `the jwk data is not a valid ${name} key`);
1250
+ const missing = usages.find((usage) => !jwk.key_ops.includes(usage));
1251
+ if (missing !== void 0) throw fail(operation, `the JWK key_ops do not include ${missing}`);
1252
+ }
1253
+ if (jwk.ext === false && extractable) throw fail(operation, "the JWK is marked not extractable");
1254
+ if (type === "private" && RSA.includes(name) && PRIVATE_FIELDS.some((field) => jwk[field] === void 0)) {
1255
+ throw fail(operation, "the JWK has d but not all of p, q, dp, dq, qi");
1256
+ }
1257
+ }
1258
+ async function exportKey(formatValue, keyValue) {
1259
+ const operation = "exportKey";
1260
+ const format = formatOf(operation, formatValue);
1261
+ return exported(operation, format, await keyOf(operation, keyValue));
1262
+ }
1263
+ async function exported(operation, format, key) {
1264
+ if (!key.extractable) throw fail(operation, "the key is not extractable");
1265
+ const name = key.algorithm.name;
1266
+ const formats = key.type === "secret" ? ["raw", "jwk"] : key.type === "private" ? ["pkcs8", "jwk"] : RSA.includes(name) ? ["spki", "jwk"] : ["raw", "spki", "jwk"];
1267
+ if (!formats.includes(format)) throw fail(operation, `a ${key.type} ${name} key cannot be exported as ${format}`);
1268
+ if (format === "jwk") {
1269
+ const bits = key.algorithm.length;
1270
+ const alg = jwkAlg(name, key.algorithm.hash?.name, bits, void 0);
1271
+ return { ...key.material, ...alg === void 0 ? {} : { alg }, ext: key.extractable, key_ops: [...key.usages] };
1272
+ }
1273
+ if (key.type === "secret") return fromBase64url(key.material.k);
1274
+ const web = await webImport("jwk", key.material, name, key.algorithm.hash?.name, key.algorithm.namedCurve, key.type);
1275
+ return new Uint8Array(await subtle().exportKey(format, web));
1276
+ }
1277
+ function signingParams(operation, name, params) {
1278
+ if (name === "RSA-PSS") return { saltLength: integerOf(operation, params, "saltLength", name) };
1279
+ if (name === "ECDSA") return { hash: hashOf(operation, params.hash, name) };
1280
+ return {};
1281
+ }
1282
+ function signingKey(operation, key, name, saltLength) {
1283
+ checkKey(operation, key, name, operation);
1284
+ requireType(operation, key, name === "HMAC" ? "secret" : operation === "sign" ? "private" : "public");
1285
+ if (name === "RSA-PSS" && saltLength !== HASH_BYTES[hashOfKey(key)]) {
1286
+ throw fail(operation, `RSA-PSS saltLength must be ${HASH_BYTES[hashOfKey(key)]} for ${hashOfKey(key)}, not ${saltLength}`);
1287
+ }
1288
+ }
1289
+ function webSigning(name, extra) {
1290
+ return name === "RSA-PSS" ? { name, saltLength: extra.saltLength } : name === "ECDSA" ? { name, hash: extra.hash } : { name };
1291
+ }
1292
+ async function sign(algorithm, keyValue, dataValue) {
1293
+ const operation = "sign";
1294
+ const { name, params } = algorithmOf(operation, algorithm);
1295
+ const extra = signingParams(operation, name, params);
1296
+ const key = await keyOf(operation, keyValue);
1297
+ const data = bytesArgument(operation, dataValue, "data");
1298
+ signingKey(operation, key, name, extra.saltLength);
1299
+ return new Uint8Array(await subtle().sign(webSigning(name, extra), await webKey(key, "sign"), data));
1300
+ }
1301
+ async function verify(algorithm, keyValue, signatureValue, dataValue) {
1302
+ const operation = "verify";
1303
+ const { name, params } = algorithmOf(operation, algorithm);
1304
+ const extra = signingParams(operation, name, params);
1305
+ const key = await keyOf(operation, keyValue);
1306
+ const signature = bytesArgument(operation, signatureValue, "signature");
1307
+ const data = bytesArgument(operation, dataValue, "data");
1308
+ signingKey(operation, key, name, extra.saltLength);
1309
+ return subtle().verify(webSigning(name, extra), await webKey(key, "verify"), signature, data);
1310
+ }
1311
+ function cipherParams(operation, name, params) {
1312
+ switch (name) {
1313
+ case "RSA-OAEP":
1314
+ return { label: optionalBytesParam(operation, params, "label", name) };
1315
+ case "AES-CBC":
1316
+ return { iv: bytesParam(operation, params, "iv", name) };
1317
+ case "AES-CTR":
1318
+ return { counter: bytesParam(operation, params, "counter", name), length: integerOf(operation, params, "length", name) };
1319
+ default:
1320
+ return {
1321
+ iv: bytesParam(operation, params, "iv", name),
1322
+ additionalData: optionalBytesParam(operation, params, "additionalData", name),
1323
+ tagLength: params.tagLength === void 0 ? 128 : integerOf(operation, params, "tagLength", name)
1324
+ };
1325
+ }
1326
+ }
1327
+ function checkCipher(operation, name, cipher, data, key) {
1328
+ if (name === "RSA-OAEP") {
1329
+ if (cipher.label !== void 0 && cipher.label.length > 0) throw fail(operation, "RSA-OAEP does not support a label");
1330
+ const max = Math.ceil(bitLength(fromBase64url(key.material.n)) / 8) - 2 * HASH_BYTES[hashOfKey(key)] - 2;
1331
+ if ((operation === "encrypt" || operation === "wrapKey") && data.length > max) throw fail(operation, `the data is longer than ${max} bytes, the most this RSA-OAEP key can encrypt`);
1332
+ } else if (name === "AES-CBC") {
1333
+ if (cipher.iv.length !== 16) throw fail(operation, `AES-CBC iv must be 16 bytes, not ${cipher.iv.length}`);
1334
+ } else if (name === "AES-CTR") {
1335
+ if (cipher.counter.length !== 16) throw fail(operation, `AES-CTR counter must be 16 bytes, not ${cipher.counter.length}`);
1336
+ if (cipher.length < 1 || cipher.length > 128) throw fail(operation, `AES-CTR length must be from 1 to 128, not ${cipher.length}`);
1337
+ const blocks = Math.ceil(data.length / 16);
1338
+ if (cipher.length < 64 && blocks > 2 ** cipher.length) {
1339
+ throw fail(operation, `AES-CTR counter would wrap around: the data needs more than 2^${cipher.length} blocks`);
1340
+ }
1341
+ } else {
1342
+ if (cipher.iv.length !== 12) throw fail(operation, `AES-GCM iv must be 12 bytes, not ${cipher.iv.length}`);
1343
+ if (!GCM_TAG_LENGTHS.includes(cipher.tagLength)) throw fail(operation, `AES-GCM tagLength must be 32, 64, 96, 104, 112, 120 or 128, not ${cipher.tagLength}`);
1344
+ }
1345
+ }
1346
+ function webCipher(name, cipher) {
1347
+ switch (name) {
1348
+ case "RSA-OAEP":
1349
+ return { name };
1350
+ case "AES-CBC":
1351
+ return { name, iv: cipher.iv };
1352
+ case "AES-CTR":
1353
+ return { name, counter: cipher.counter, length: cipher.length };
1354
+ default:
1355
+ return { name, iv: cipher.iv, tagLength: cipher.tagLength, ...cipher.additionalData === void 0 ? {} : { additionalData: cipher.additionalData } };
1356
+ }
1357
+ }
1358
+ async function crypt(operation, algorithm, keyValue, dataValue) {
1359
+ const { name, params } = algorithmOf(operation, algorithm);
1360
+ const cipher = cipherParams(operation, name, params);
1361
+ const key = await keyOf(operation, keyValue);
1362
+ const data = bytesArgument(operation, dataValue, "data");
1363
+ checkKey(operation, key, name, operation);
1364
+ requireType(operation, key, name === "RSA-OAEP" ? operation === "encrypt" ? "public" : "private" : "secret");
1365
+ checkCipher(operation, name, cipher, data, key);
1366
+ const web = await webKey(key, operation);
1367
+ try {
1368
+ return new Uint8Array(await (operation === "encrypt" ? subtle().encrypt(webCipher(name, cipher), web, data) : subtle().decrypt(webCipher(name, cipher), web, data)));
1369
+ } catch (error) {
1370
+ if (operation === "encrypt") throw error;
1371
+ throw decryptionFailed(operation, name);
1372
+ }
1373
+ }
1374
+ var decryptionFailed = (operation, name) => fail(operation, name === "AES-GCM" ? "AES-GCM tag check failed" : name === "AES-CBC" ? "AES-CBC decryption failed: the data or its padding is wrong" : name === "AES-KW" ? "AES-KW integrity check failed" : `${name} decryption failed`);
1375
+ async function digest(algorithm, dataValue) {
1376
+ const operation = "digest";
1377
+ const given = typeof algorithm === "string" ? algorithm : isObject(algorithm) && typeof algorithm.name === "string" ? algorithm.name : void 0;
1378
+ if (given === void 0) throw fail(operation, "algorithm needs a name");
1379
+ const hash = hashOf(operation, given, "digest");
1380
+ return new Uint8Array(await subtle().digest(hash, bytesArgument(operation, dataValue, "data")));
1381
+ }
1382
+ async function derivationOf(operation, algorithm) {
1383
+ const { name, params } = algorithmOf(operation, algorithm);
1384
+ if (AGREEMENT.includes(name)) {
1385
+ if (params.public === void 0) throw fail(operation, `${name} needs public`);
1386
+ return { name, publicKey: await keyOf(operation, params.public, "public") };
1387
+ }
1388
+ const hash = hashOf(operation, params.hash, name);
1389
+ const salt = boundedBytes(operation, params, "salt", name);
1390
+ if (name === "HKDF") return { name, hash, salt, info: boundedBytes(operation, params, "info", name) };
1391
+ return { name, hash, salt, iterations: integerOf(operation, params, "iterations", name) };
1392
+ }
1393
+ function boundedBytes(operation, params, field, owner) {
1394
+ const bytes2 = bytesParam(operation, params, field, owner);
1395
+ if (bytes2.length > MAX_DERIVE_BYTES) throw fail(operation, `${owner} ${field} can be at most 1024 bytes, not ${bytes2.length}`);
1396
+ return bytes2;
1397
+ }
1398
+ function lengthOf(operation, value) {
1399
+ if (value === null || value === void 0) return null;
1400
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value >= 1e15) throw fail(operation, "length must be a whole number of bits or null");
1401
+ return value;
1402
+ }
1403
+ var article = (name) => /^[AEIOX]/.test(name) ? "an" : "a";
1404
+ async function derive(operation, derivation, key, length, usage) {
1405
+ const { name } = derivation;
1406
+ checkKey(operation, key, name, usage);
1407
+ if (AGREEMENT.includes(name)) return agree(operation, derivation, key, length);
1408
+ if (length === null) throw fail(operation, `${name} needs length`);
1409
+ if (length % 8 !== 0) throw fail(operation, `${name} length must be a multiple of 8, not ${length}`);
1410
+ if (length > MAX_DERIVE_BYTES * 8) throw fail(operation, `${name} can derive at most ${MAX_DERIVE_BYTES * 8} bits, not ${length}`);
1411
+ const iterations = derivation.iterations ?? 0;
1412
+ if (name === "PBKDF2") {
1413
+ if (iterations < 1) throw fail(operation, `PBKDF2 iterations must be at least 1, not ${iterations}`);
1414
+ const work = iterations * Math.ceil(length / (HASH_BYTES[derivation.hash] * 8));
1415
+ if (work > MAX_PBKDF2_WORK) {
1416
+ throw fail(operation, `PBKDF2 can run at most ${MAX_PBKDF2_WORK} iterations in total (iterations times output blocks), not ${work}`);
1417
+ }
1418
+ }
1419
+ if (length === 0) return new Uint8Array(0);
1420
+ const params = name === "HKDF" ? { name, hash: derivation.hash, salt: derivation.salt, info: derivation.info } : { name, hash: derivation.hash, salt: derivation.salt, iterations };
1421
+ return new Uint8Array(await subtle().deriveBits(params, await webKey(key, "deriveBits"), length));
1422
+ }
1423
+ async function agree(operation, derivation, key, length) {
1424
+ const { name } = derivation;
1425
+ const other = derivation.publicKey;
1426
+ requireType(operation, key, "private");
1427
+ if (other.type !== "public") throw fail(operation, "public must be a public key");
1428
+ if (other.algorithm.name !== name) throw fail(operation, `the public key is ${article(other.algorithm.name)} ${other.algorithm.name} key, not ${name}`);
1429
+ const curve = key.algorithm.namedCurve;
1430
+ if (curve !== void 0 && other.algorithm.namedCurve !== curve) throw fail(operation, `the public key is on ${other.algorithm.namedCurve}, not ${curve}`);
1431
+ const full = curve === void 0 ? 256 : COORDINATE_BYTES[curve] * 8;
1432
+ if (length !== null && length > full) {
1433
+ throw fail(operation, curve === void 0 ? `${name} can derive at most ${full} bits, not ${length}` : `${name} can derive at most ${full} bits on ${curve}, not ${length}`);
1434
+ }
1435
+ const smallOrder = () => fail(operation, "the X25519 shared secret is all zero: the public key is a small-order point");
1436
+ let secret;
1437
+ try {
1438
+ secret = new Uint8Array(await subtle().deriveBits({ name, public: await webKey(other, void 0) }, await webKey(key, "deriveBits"), null));
1439
+ } catch {
1440
+ throw name === "X25519" ? smallOrder() : fail(operation, `${name} could not derive bits with this key`);
1441
+ }
1442
+ if (name === "X25519" && secret.every((byte) => byte === 0)) throw smallOrder();
1443
+ if (length === null) return secret;
1444
+ const bits = secret.slice(0, Math.ceil(length / 8));
1445
+ if (length % 8 !== 0) bits[bits.length - 1] &= 255 << 8 - length % 8 & 255;
1446
+ return bits;
1447
+ }
1448
+ async function deriveBits(algorithm, baseKey, lengthValue) {
1449
+ const operation = "deriveBits";
1450
+ const derivation = await derivationOf(operation, algorithm);
1451
+ const key = await keyOf(operation, baseKey);
1452
+ return derive(operation, derivation, key, lengthOf(operation, lengthValue), "deriveBits");
1453
+ }
1454
+ function derivedLength(operation, name, params) {
1455
+ if (AES_KEYS.includes(name)) {
1456
+ const length = integerOf(operation, params, "length", name);
1457
+ if (![128, 192, 256].includes(length)) throw fail(operation, `an AES key must be 128, 192 or 256 bits, not ${length}`);
1458
+ return length;
1459
+ }
1460
+ if (name === "HMAC") {
1461
+ const hash = hashOf(operation, params.hash, name);
1462
+ const length = params.length === void 0 ? HASH_BLOCK_BITS[hash] : integerOf(operation, params, "length", name);
1463
+ if (length <= 0 || length % 8 !== 0) throw fail(operation, `HMAC length must be a positive multiple of 8, not ${length}`);
1464
+ if (length > MAX_HMAC_BYTES * 8) throw fail(operation, `an HMAC key can be at most ${MAX_HMAC_BYTES * 8} bits, not ${length}`);
1465
+ return length;
1466
+ }
1467
+ if (KDF.includes(name)) return null;
1468
+ throw fail(operation, `${name} keys cannot be derived`);
1469
+ }
1470
+ async function deriveKey(algorithm, baseKey, derivedKeyType, extractableValue, usagesValue) {
1471
+ const operation = "deriveKey";
1472
+ const derivation = await derivationOf(operation, algorithm);
1473
+ const key = await keyOf(operation, baseKey);
1474
+ const { name, params } = algorithmOf(operation, derivedKeyType, "importKey");
1475
+ const length = derivedLength(operation, name, params);
1476
+ extractableOf(operation, extractableValue);
1477
+ usagesOf(operation, usagesValue);
1478
+ const bits = await derive(operation, derivation, key, length, "deriveKey");
1479
+ return importKeyAs(operation, "raw", bits, derivedKeyType, extractableValue, usagesValue);
1480
+ }
1481
+ function jwkBytes(jwk, pad) {
1482
+ let text = JSON.stringify(Object.fromEntries(Object.keys(jwk).sort().map((field) => [field, jwk[field]])));
1483
+ if (pad) text += " ".repeat((8 - text.length % 8) % 8);
1484
+ return new TextEncoder().encode(text);
1485
+ }
1486
+ function wrapping(operation, algorithm) {
1487
+ const { name, params } = algorithmOf(operation, algorithm);
1488
+ return { name, cipher: name === "AES-KW" ? {} : cipherParams(operation, name, params) };
1489
+ }
1490
+ function checkKeyWrap(operation, data) {
1491
+ const least = operation === "wrapKey" ? 16 : 24;
1492
+ if (data.length % 8 !== 0 || data.length < least) {
1493
+ throw fail(operation, `AES-KW can only ${operation === "wrapKey" ? "wrap" : "unwrap"} a multiple of 8 bytes, at least ${least}, not ${data.length}`);
1494
+ }
1495
+ }
1496
+ var HMAC_CARRIER = { name: "HMAC", hash: "SHA-256" };
1497
+ async function wrapKey(formatValue, keyValue, wrappingKeyValue, algorithm) {
1498
+ const operation = "wrapKey";
1499
+ const format = formatOf(operation, formatValue);
1500
+ const { name, cipher } = wrapping(operation, algorithm);
1501
+ const key = await keyOf(operation, keyValue);
1502
+ const wrappingKey = await keyOf(operation, wrappingKeyValue);
1503
+ checkKey(operation, wrappingKey, name, "wrapKey");
1504
+ requireType(operation, wrappingKey, name === "RSA-OAEP" ? "public" : "secret");
1505
+ const output = await exported(operation, format, key);
1506
+ const data = output instanceof Uint8Array ? output : jwkBytes(output, name === "AES-KW");
1507
+ if (name === "AES-KW") {
1508
+ checkKeyWrap(operation, data);
1509
+ } else {
1510
+ checkCipher(operation, name, cipher, data, wrappingKey);
1511
+ }
1512
+ try {
1513
+ if (name !== "AES-KW") return new Uint8Array(await subtle().encrypt(webCipher(name, cipher), await webKey(wrappingKey, "encrypt"), data));
1514
+ const carrier = await subtle().importKey("raw", data, HMAC_CARRIER, true, ["sign"]);
1515
+ return new Uint8Array(await subtle().wrapKey("raw", carrier, await webKey(wrappingKey, "wrapKey"), { name }));
1516
+ } catch {
1517
+ throw fail(operation, `${name} could not wrap with this key`);
1518
+ }
1519
+ }
1520
+ function jwkOf(operation, data) {
1521
+ const text = pluginJSONText(data);
1522
+ if (text === void 0) throw fail(operation, "the unwrapped data is not a valid JWK");
1523
+ if (nestedTooDeep(text)) throw fail(operation, `the unwrapped JWK is nested deeper than ${VALUE_LIMITS.depth} levels`);
1524
+ try {
1525
+ const value = JSON.parse(text);
1526
+ if (isObject(value)) return value;
1527
+ } catch {
1528
+ }
1529
+ throw fail(operation, "the unwrapped data is not a valid JWK");
1530
+ }
1531
+ async function unwrapKey(formatValue, wrappedValue, unwrappingKeyValue, algorithm, keyAlgorithm2, extractableValue, usagesValue) {
1532
+ const operation = "unwrapKey";
1533
+ const format = formatOf(operation, formatValue);
1534
+ const wrapped2 = bytesArgument(operation, wrappedValue, "wrappedKey");
1535
+ if (wrapped2.length > MAX_WRAPPED_BYTES) throw fail(operation, `wrappedKey can be at most ${MAX_WRAPPED_BYTES} bytes, not ${wrapped2.length}`);
1536
+ const { name, cipher } = wrapping(operation, algorithm);
1537
+ const unwrappingKey = await keyOf(operation, unwrappingKeyValue);
1538
+ algorithmOf(operation, keyAlgorithm2, "importKey");
1539
+ extractableOf(operation, extractableValue);
1540
+ usagesOf(operation, usagesValue);
1541
+ checkKey(operation, unwrappingKey, name, "unwrapKey");
1542
+ requireType(operation, unwrappingKey, name === "RSA-OAEP" ? "private" : "secret");
1543
+ if (name === "AES-KW") checkKeyWrap(operation, wrapped2);
1544
+ else checkCipher(operation, name, cipher, wrapped2, unwrappingKey);
1545
+ let data;
1546
+ try {
1547
+ if (name === "AES-KW") {
1548
+ const carrier = await subtle().unwrapKey("raw", wrapped2, await webKey(unwrappingKey, "unwrapKey"), { name }, HMAC_CARRIER, true, ["sign"]);
1549
+ data = new Uint8Array(await subtle().exportKey("raw", carrier));
1550
+ } else {
1551
+ data = new Uint8Array(await subtle().decrypt(webCipher(name, cipher), await webKey(unwrappingKey, "decrypt"), wrapped2));
1552
+ }
1553
+ } catch {
1554
+ throw decryptionFailed(operation, name);
1555
+ }
1556
+ return importKeyAs(operation, format, format === "jwk" ? jwkOf(operation, data) : data, keyAlgorithm2, extractableValue, usagesValue);
1557
+ }
1558
+ function createSubtle() {
1559
+ return {
1560
+ generateKey,
1561
+ importKey,
1562
+ exportKey,
1563
+ sign,
1564
+ verify,
1565
+ encrypt: (algorithm, key, data) => crypt("encrypt", algorithm, key, data),
1566
+ decrypt: (algorithm, key, data) => crypt("decrypt", algorithm, key, data),
1567
+ digest,
1568
+ deriveBits,
1569
+ deriveKey,
1570
+ wrapKey,
1571
+ unwrapKey
1572
+ };
1573
+ }
1574
+ var DIGESTS = /* @__PURE__ */ new Map([["sha-1", "SHA-1"], ["sha-256", "SHA-256"], ["sha-384", "SHA-384"], ["sha-512", "SHA-512"]]);
1575
+ async function plainDigest(algorithm, data) {
1576
+ const name = DIGESTS.get(algorithm.toLowerCase());
1577
+ if (name === void 0) throw new TypeError(`unsupported digest ${algorithm}`);
1578
+ return new Uint8Array(await subtle().digest(name, typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data)));
1579
+ }
1580
+ function createCrypto() {
1581
+ return {
1582
+ randomBytes: (length) => globalThis.crypto.getRandomValues(new Uint8Array(length)),
1583
+ digest: plainDigest,
1584
+ subtle: createSubtle()
1585
+ };
1586
+ }
1587
+ export {
1588
+ createCrypto
1589
+ };