@blockcast/mmt-container 0.4.0 → 0.4.1-main.47aa22331187

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 (210) hide show
  1. package/README.md +36 -20
  2. package/dist/align.d.ts +24 -18
  3. package/dist/align.d.ts.map +1 -1
  4. package/dist/align.js +23 -4
  5. package/dist/align.js.map +2 -2
  6. package/dist/browser-runtime.js +1839 -692
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +76 -39
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +321 -205
  11. package/dist/carp-catalog.js.map +3 -3
  12. package/dist/catalog-fec-params.d.ts +12 -4
  13. package/dist/catalog-fec-params.d.ts.map +1 -1
  14. package/dist/catalog-fec-params.js +40 -17
  15. package/dist/catalog-fec-params.js.map +3 -3
  16. package/dist/catalog-network-source.d.ts +28 -7
  17. package/dist/catalog-network-source.d.ts.map +1 -1
  18. package/dist/catalog-network-source.js +21 -1
  19. package/dist/catalog-network-source.js.map +2 -2
  20. package/dist/catalog-validator.d.ts +4 -3
  21. package/dist/catalog-validator.d.ts.map +1 -1
  22. package/dist/catalog-validator.js +0 -29
  23. package/dist/catalog-validator.js.map +3 -3
  24. package/dist/cmcd-producer.d.ts +8 -0
  25. package/dist/cmcd-producer.d.ts.map +1 -1
  26. package/dist/cmcd-producer.js +14 -0
  27. package/dist/cmcd-producer.js.map +2 -2
  28. package/dist/delivery-catalog.js +98 -234
  29. package/dist/delivery-catalog.js.map +4 -4
  30. package/dist/fec-manager.d.ts +121 -1
  31. package/dist/fec-manager.d.ts.map +1 -1
  32. package/dist/fec-manager.js +421 -66
  33. package/dist/fec-manager.js.map +3 -3
  34. package/dist/fec-state.d.ts +2 -1
  35. package/dist/fec-state.d.ts.map +1 -1
  36. package/dist/fec-state.js +18 -3
  37. package/dist/fec-state.js.map +3 -3
  38. package/dist/fec-worker-setup.d.ts +10 -0
  39. package/dist/fec-worker-setup.d.ts.map +1 -1
  40. package/dist/fec-worker-setup.js +15 -4
  41. package/dist/fec-worker-setup.js.map +2 -2
  42. package/dist/index.d.ts +5 -5
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +8 -8
  45. package/dist/index.js.map +2 -2
  46. package/dist/iso-block-locator.d.ts +39 -1
  47. package/dist/iso-block-locator.d.ts.map +1 -1
  48. package/dist/iso-block-locator.js +109 -17
  49. package/dist/iso-block-locator.js.map +3 -3
  50. package/dist/manifest-auth-plan.d.ts +26 -25
  51. package/dist/manifest-auth-plan.d.ts.map +1 -1
  52. package/dist/manifest-auth-plan.js +331 -1171
  53. package/dist/manifest-auth-plan.js.map +4 -4
  54. package/dist/mfu-reassembler.js +21 -13
  55. package/dist/mfu-reassembler.js.map +2 -2
  56. package/dist/mmtp-container-parser.d.ts.map +1 -1
  57. package/dist/mmtp-container-parser.js +93 -22
  58. package/dist/mmtp-container-parser.js.map +2 -2
  59. package/dist/mmtp-container-parser.no-modules.js +1137 -317
  60. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  61. package/dist/mmtp-decode-pipeline.js +93 -22
  62. package/dist/mmtp-decode-pipeline.js.map +2 -2
  63. package/dist/mmtp-fec-session.d.ts +159 -0
  64. package/dist/mmtp-fec-session.d.ts.map +1 -0
  65. package/dist/mmtp-fec-session.js +531 -0
  66. package/dist/mmtp-fec-session.js.map +7 -0
  67. package/dist/mmtp-router.d.ts +39 -6
  68. package/dist/mmtp-router.d.ts.map +1 -1
  69. package/dist/mmtp-router.js +184 -27
  70. package/dist/mmtp-router.js.map +2 -2
  71. package/dist/multicast-auth-catalog.d.ts +86 -92
  72. package/dist/multicast-auth-catalog.d.ts.map +1 -1
  73. package/dist/multicast-auth-catalog.js +347 -132
  74. package/dist/multicast-auth-catalog.js.map +4 -4
  75. package/dist/multicast-input.d.ts +31 -8
  76. package/dist/multicast-input.d.ts.map +1 -1
  77. package/dist/multicast-input.js +299 -35
  78. package/dist/multicast-input.js.map +3 -3
  79. package/dist/multicast-manager.d.ts +94 -5
  80. package/dist/multicast-manager.d.ts.map +1 -1
  81. package/dist/multicast-manager.js +877 -357
  82. package/dist/multicast-manager.js.map +4 -4
  83. package/dist/multicast-transport.d.ts +12 -2
  84. package/dist/multicast-transport.d.ts.map +1 -1
  85. package/dist/multicast-transport.js +108 -238
  86. package/dist/multicast-transport.js.map +4 -4
  87. package/dist/multicast-unwrap.js +21 -13
  88. package/dist/multicast-unwrap.js.map +2 -2
  89. package/dist/no-modules.d.ts +4 -1
  90. package/dist/no-modules.d.ts.map +1 -1
  91. package/dist/no-modules.js +1086 -301
  92. package/dist/no-modules.js.map +4 -4
  93. package/dist/phase14-catalog-override.d.ts +1 -1
  94. package/dist/phase14-catalog-override.d.ts.map +1 -1
  95. package/dist/phase14-catalog-override.js +2 -2
  96. package/dist/phase14-catalog-override.js.map +2 -2
  97. package/dist/repair-fetch.d.ts +81 -6
  98. package/dist/repair-fetch.d.ts.map +1 -1
  99. package/dist/repair-fetch.js +156 -31
  100. package/dist/repair-fetch.js.map +3 -3
  101. package/dist/repair-layers.d.ts +2 -0
  102. package/dist/repair-layers.d.ts.map +1 -1
  103. package/dist/repair-layers.js +19 -2
  104. package/dist/repair-layers.js.map +2 -2
  105. package/dist/sample-combiner.d.ts +7 -1
  106. package/dist/sample-combiner.d.ts.map +1 -1
  107. package/dist/sample-combiner.js +14 -2
  108. package/dist/sample-combiner.js.map +2 -2
  109. package/dist/signaling.d.ts +2 -2
  110. package/dist/signaling.d.ts.map +1 -1
  111. package/dist/signaling.js +3 -3
  112. package/dist/signaling.js.map +2 -2
  113. package/dist/source-auth.js +2710 -7
  114. package/dist/source-auth.js.map +4 -4
  115. package/dist/switching-set-alignment.d.ts +1 -1
  116. package/dist/switching-set-alignment.js.map +1 -1
  117. package/dist/timestamp-codec.js +21 -13
  118. package/dist/timestamp-codec.js.map +2 -2
  119. package/dist/wasm-mfu-reassembler.js.map +1 -1
  120. package/dist/wasm-mmtp-container-parser.js +93 -22
  121. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  122. package/package.json +6 -9
  123. package/schemas/catalog.schema.json +133 -38
  124. package/src/align.ts +52 -21
  125. package/src/carp-catalog.ts +188 -68
  126. package/src/catalog-fec-params.ts +28 -3
  127. package/src/catalog-network-source.ts +49 -7
  128. package/src/catalog-validator.ts +4 -11
  129. package/src/cmcd-producer.ts +17 -0
  130. package/src/fec-manager.ts +452 -63
  131. package/src/fec-state.ts +11 -4
  132. package/src/fec-worker-setup.ts +30 -2
  133. package/src/index.ts +27 -10
  134. package/src/iso-block-locator.ts +110 -7
  135. package/src/manifest-auth-plan.ts +39 -91
  136. package/src/mmtp-container-parser.ts +75 -7
  137. package/src/mmtp-fec-session.ts +533 -0
  138. package/src/mmtp-router.ts +166 -7
  139. package/src/multicast-auth-catalog.ts +131 -238
  140. package/src/multicast-input.ts +148 -124
  141. package/src/multicast-manager.ts +267 -21
  142. package/src/multicast-transport.ts +17 -3
  143. package/src/no-modules.ts +7 -1
  144. package/src/phase14-catalog-override.ts +3 -3
  145. package/src/repair-fetch.ts +283 -39
  146. package/src/repair-layers.ts +22 -2
  147. package/src/sample-combiner.ts +15 -2
  148. package/src/signaling.ts +2 -2
  149. package/src/switching-set-alignment.ts +1 -1
  150. package/test-vectors/align.json +108 -32
  151. package/test-vectors/bc-provenance-v2.json +1526 -0
  152. package/test-vectors/catalog/README.md +71 -4
  153. package/test-vectors/catalog/negative/fec-block-profile-missing.json +1 -1
  154. package/test-vectors/catalog/negative/fec-block-profile-retired.json +1 -1
  155. package/test-vectors/catalog/negative/fec-block-profile-unknown.json +1 -1
  156. package/test-vectors/catalog/negative/fec-iso-symbol-size-below-floor.json +28 -0
  157. package/test-vectors/catalog/negative/fec-reed-solomon-iso-symbol-size-13.json +28 -0
  158. package/test-vectors/catalog/negative/fec-reed-solomon-k-plus-p-over-255.json +39 -0
  159. package/test-vectors/catalog/negative/fec-reed-solomon-overlay-over-255.json +40 -0
  160. package/test-vectors/catalog/negative/fec-repair-overlay-source-symbols-zero.json +43 -0
  161. package/test-vectors/catalog/negative/fec-repair-symbols-zero.json +28 -0
  162. package/test-vectors/catalog/negative/fec-source-symbols-zero.json +28 -0
  163. package/test-vectors/catalog/negative/fec-symbol-size-zero.json +28 -0
  164. package/test-vectors/catalog/negative/init-data-inline-without-data.json +22 -0
  165. package/test-vectors/catalog/negative/mmtp-mode-mpu.json +15 -0
  166. package/test-vectors/catalog/negative/multicast-amt-dns-without-relay.json +37 -0
  167. package/test-vectors/catalog/negative/multicast-amt-driad-with-relay.json +38 -0
  168. package/test-vectors/catalog/negative/multicast-auth-asm-missing-sender-address.json +77 -0
  169. package/test-vectors/catalog/negative/multicast-auth-duplicate-first-epoch.json +56 -0
  170. package/test-vectors/catalog/negative/multicast-auth-duplicate-kid.json +56 -0
  171. package/test-vectors/catalog/negative/multicast-auth-endpoint-auth-without-object-auth.json +38 -0
  172. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-auth.json +49 -0
  173. package/test-vectors/catalog/negative/multicast-auth-endpoint-missing-bandwidth.json +55 -0
  174. package/test-vectors/catalog/negative/multicast-auth-manifest-port-equals-port.json +56 -0
  175. package/test-vectors/catalog/negative/multicast-auth-manifest-timer-out-of-range.json +56 -0
  176. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-above-max.json +56 -0
  177. package/test-vectors/catalog/negative/multicast-auth-max-auth-delay-below-min.json +56 -0
  178. package/test-vectors/catalog/negative/multicast-auth-root-dotted-key.json +55 -0
  179. package/test-vectors/catalog/negative/multicast-auth-sender-address-on-ssm.json +57 -0
  180. package/test-vectors/catalog/negative/multicast-auth-version-1.json +56 -0
  181. package/test-vectors/catalog/negative/multicast-auth-version-3.json +56 -0
  182. package/test-vectors/catalog/negative/multicast-auth-version-missing.json +55 -0
  183. package/test-vectors/catalog/negative/multicast-endpoint-foreign-namespace-track.json +44 -0
  184. package/test-vectors/catalog/negative/multicast-endpoint-protocol-amt.json +38 -0
  185. package/test-vectors/catalog/negative/multicast-endpoint-protocol-atsc3.json +38 -0
  186. package/test-vectors/catalog/negative/presentation-anchor-unsafe.json +16 -0
  187. package/test-vectors/catalog/positive/fec-algorithm-unimplemented.json +29 -0
  188. package/test-vectors/catalog/positive/fec-iso-ssbg1.json +1 -1
  189. package/test-vectors/catalog/positive/fec-multicast.json +1 -1
  190. package/test-vectors/catalog/positive/fec-reed-solomon-layered.json +50 -0
  191. package/test-vectors/catalog/positive/mmt01-12-1-init-ref-anchor.json +29 -0
  192. package/test-vectors/catalog/positive/multicast-amt-discovery-omitted.json +37 -0
  193. package/test-vectors/catalog/positive/multicast-amt-dns-relay.json +38 -0
  194. package/test-vectors/catalog/positive/multicast-amt-manual-relay.json +3 -3
  195. package/test-vectors/catalog/{negative/multicast-endpoint-missing-protocol-and-source.json → positive/multicast-asm-unprotected.json} +10 -5
  196. package/test-vectors/catalog/positive/multicast-auth-asm-sender.json +78 -0
  197. package/test-vectors/catalog/positive/multicast-auth-rotation.json +39 -38
  198. package/test-vectors/catalog/positive/multicast-draft01-4-1-example.json +81 -0
  199. package/test-vectors/catalog/positive/multicast-draft01-7-2-6-example.json +70 -0
  200. package/test-vectors/catalog/positive/presentation-anchor-negative.json +27 -0
  201. package/test-vectors/catalog/section-codes.json +31 -1
  202. package/test-vectors/catalog-multicast-auth-v1.json +38 -20
  203. package/test-vectors/catalog-validation.json +101 -5
  204. package/test-vectors/catalog-validator-public-api.mjs +14 -9
  205. package/test-vectors/generate-bc-provenance-v2.mjs +252 -0
  206. package/dist/fec-codec.d.ts +0 -32
  207. package/dist/fec-codec.d.ts.map +0 -1
  208. package/dist/fec-codec.js +0 -47
  209. package/dist/fec-codec.js.map +0 -7
  210. package/src/fec-codec.ts +0 -61
@@ -1,1017 +1,301 @@
1
- // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/utils.js
2
- function isBytes(a) {
3
- return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
4
- }
5
- function anumber(n) {
6
- if (!Number.isSafeInteger(n) || n < 0)
7
- throw new Error("positive integer expected, got " + n);
8
- }
9
- function abytes(b, ...lengths) {
10
- if (!isBytes(b))
11
- throw new Error("Uint8Array expected");
12
- if (lengths.length > 0 && !lengths.includes(b.length))
13
- throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
14
- }
15
- function aexists(instance, checkFinished = true) {
16
- if (instance.destroyed)
17
- throw new Error("Hash instance has been destroyed");
18
- if (checkFinished && instance.finished)
19
- throw new Error("Hash#digest() has already been called");
20
- }
21
- function aoutput(out, instance) {
22
- abytes(out);
23
- const min = instance.outputLen;
24
- if (out.length < min) {
25
- throw new Error("digestInto() expects output buffer of length at least " + min);
26
- }
27
- }
28
- function u8(arr) {
29
- return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
30
- }
31
- function u32(arr) {
32
- return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
33
- }
34
- function clean(...arrays) {
35
- for (let i = 0; i < arrays.length; i++) {
36
- arrays[i].fill(0);
37
- }
38
- }
39
- function rotr(word, shift) {
40
- return word << 32 - shift | word >>> shift;
41
- }
42
- var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
43
- function byteSwap(word) {
44
- return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
45
- }
46
- var swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n);
47
- function byteSwap32(arr) {
48
- for (let i = 0; i < arr.length; i++) {
49
- arr[i] = byteSwap(arr[i]);
50
- }
51
- return arr;
52
- }
53
- var swap32IfBE = isLE ? (u) => u : byteSwap32;
54
- function utf8ToBytes(str) {
55
- if (typeof str !== "string")
56
- throw new Error("string expected");
57
- return new Uint8Array(new TextEncoder().encode(str));
58
- }
59
- function toBytes(data) {
60
- if (typeof data === "string")
61
- data = utf8ToBytes(data);
62
- abytes(data);
63
- return data;
64
- }
65
- var Hash = class {
66
- };
67
- function createXOFer(hashCons) {
68
- const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
69
- const tmp = hashCons({});
70
- hashC.outputLen = tmp.outputLen;
71
- hashC.blockLen = tmp.blockLen;
72
- hashC.create = (opts) => hashCons(opts);
73
- return hashC;
74
- }
1
+ // ../mmt-base/dist/mmtp.js
2
+ var MPU_HEADER_SIZE = 8;
3
+ var MPU_LENGTH_FIELD_SIZE = 2;
4
+ var MPU_HEADER_REMAINDER_SIZE = MPU_HEADER_SIZE - MPU_LENGTH_FIELD_SIZE;
75
5
 
76
- // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/_md.js
77
- var SHA256_IV = /* @__PURE__ */ Uint32Array.from([
78
- 1779033703,
79
- 3144134277,
80
- 1013904242,
81
- 2773480762,
82
- 1359893119,
83
- 2600822924,
84
- 528734635,
85
- 1541459225
6
+ // ../mmt-base/dist/ntp-short.js
7
+ var NTP_SHORT_BITS = 32;
8
+ var NTP_SHORT_MODULUS = 2 ** NTP_SHORT_BITS;
9
+ var NTP_SHORT_HALF_RANGE = 2 ** (NTP_SHORT_BITS - 1);
10
+
11
+ // ../mmt-base/dist/fec-block-profile.js
12
+ var FEC_BLOCK_PROFILES = Object.freeze([
13
+ "iso-ssbg1-v1"
86
14
  ]);
87
15
 
88
- // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/_u64.js
89
- var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
90
- var _32n = /* @__PURE__ */ BigInt(32);
91
- function fromBig(n, le = false) {
92
- if (le)
93
- return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
94
- return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
95
- }
16
+ // ../mmt-base/dist/catalog-fec-source.js
17
+ var ALL_ROLES = Object.freeze(["video", "audio"]);
96
18
 
97
- // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/_blake.js
98
- function G1s(a, b, c, d, x) {
99
- a = a + b + x | 0;
100
- d = rotr(d ^ a, 16);
101
- c = c + d | 0;
102
- b = rotr(b ^ c, 12);
103
- return { a, b, c, d };
19
+ // ../mmt-base/dist/multicast-catalog.js
20
+ var ED25519_PUBLIC_KEY_BASE64URL = /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;
21
+ var UINT32_MAX = 4294967295;
22
+ var AUTH_MEMBERS = /* @__PURE__ */ new Set(["scheme", "version", "sig", "keys", "minEpoch"]);
23
+ var KEY_MEMBERS = /* @__PURE__ */ new Set(["kid", "publicKey", "firstEpoch"]);
24
+ var ENDPOINT_AUTH_MEMBERS = /* @__PURE__ */ new Set([
25
+ "manifestPort",
26
+ "streamId",
27
+ "senderAddress",
28
+ "maxAuthDelayMs",
29
+ "manifestTimerMs",
30
+ "manifestTrack"
31
+ ]);
32
+ function isObject(value) {
33
+ return typeof value === "object" && value !== null && !Array.isArray(value);
104
34
  }
105
- function G2s(a, b, c, d, x) {
106
- a = a + b + x | 0;
107
- d = rotr(d ^ a, 8);
108
- c = c + d | 0;
109
- b = rotr(b ^ c, 7);
110
- return { a, b, c, d };
35
+ function isNonEmptyString(value) {
36
+ return typeof value === "string" && value.trim().length > 0;
111
37
  }
112
-
113
- // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/blake2.js
114
- var BLAKE2 = class extends Hash {
115
- constructor(blockLen, outputLen) {
116
- super();
117
- this.finished = false;
118
- this.destroyed = false;
119
- this.length = 0;
120
- this.pos = 0;
121
- anumber(blockLen);
122
- anumber(outputLen);
123
- this.blockLen = blockLen;
124
- this.outputLen = outputLen;
125
- this.buffer = new Uint8Array(blockLen);
126
- this.buffer32 = u32(this.buffer);
127
- }
128
- update(data) {
129
- aexists(this);
130
- data = toBytes(data);
131
- abytes(data);
132
- const { blockLen, buffer, buffer32 } = this;
133
- const len = data.length;
134
- const offset = data.byteOffset;
135
- const buf = data.buffer;
136
- for (let pos = 0; pos < len; ) {
137
- if (this.pos === blockLen) {
138
- swap32IfBE(buffer32);
139
- this.compress(buffer32, 0, false);
140
- swap32IfBE(buffer32);
141
- this.pos = 0;
142
- }
143
- const take = Math.min(blockLen - this.pos, len - pos);
144
- const dataOffset = offset + pos;
145
- if (take === blockLen && !(dataOffset % 4) && pos + take < len) {
146
- const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4));
147
- swap32IfBE(data32);
148
- for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {
149
- this.length += blockLen;
150
- this.compress(data32, pos32, false);
151
- }
152
- swap32IfBE(data32);
153
- continue;
154
- }
155
- buffer.set(data.subarray(pos, pos + take), this.pos);
156
- this.pos += take;
157
- this.length += take;
158
- pos += take;
159
- }
160
- return this;
161
- }
162
- digestInto(out) {
163
- aexists(this);
164
- aoutput(out, this);
165
- const { pos, buffer32 } = this;
166
- this.finished = true;
167
- clean(this.buffer.subarray(pos));
168
- swap32IfBE(buffer32);
169
- this.compress(buffer32, 0, true);
170
- swap32IfBE(buffer32);
171
- const out32 = u32(out);
172
- this.get().forEach((v, i) => out32[i] = swap8IfBE(v));
173
- }
174
- digest() {
175
- const { buffer, outputLen } = this;
176
- this.digestInto(buffer);
177
- const res = buffer.slice(0, outputLen);
178
- this.destroy();
179
- return res;
180
- }
181
- _cloneInto(to) {
182
- const { buffer, length, finished, destroyed, outputLen, pos } = this;
183
- to || (to = new this.constructor({ dkLen: outputLen }));
184
- to.set(...this.get());
185
- to.buffer.set(buffer);
186
- to.destroyed = destroyed;
187
- to.finished = finished;
188
- to.length = length;
189
- to.pos = pos;
190
- to.outputLen = outputLen;
191
- return to;
192
- }
193
- clone() {
194
- return this._cloneInto();
195
- }
196
- };
197
- function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
198
- let j = 0;
199
- for (let i = 0; i < rounds; i++) {
200
- ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]]));
201
- ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]]));
202
- ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]]));
203
- ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]]));
204
- ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]]));
205
- ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]]));
206
- ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]]));
207
- ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]]));
208
- ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]]));
209
- ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]]));
210
- ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]]));
211
- ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]]));
212
- ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]]));
213
- ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]]));
214
- ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]]));
215
- ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]]));
216
- }
217
- return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };
38
+ function isIntegerIn(value, min, max) {
39
+ return Number.isSafeInteger(value) && value >= min && value <= max;
218
40
  }
219
-
220
- // ../mmt-manifest-verify/node_modules/@noble/hashes/esm/blake3.js
221
- var B3_Flags = {
222
- CHUNK_START: 1,
223
- CHUNK_END: 2,
224
- PARENT: 4,
225
- ROOT: 8,
226
- KEYED_HASH: 16,
227
- DERIVE_KEY_CONTEXT: 32,
228
- DERIVE_KEY_MATERIAL: 64
229
- };
230
- var B3_IV = SHA256_IV.slice();
231
- var B3_SIGMA = /* @__PURE__ */ (() => {
232
- const Id = Array.from({ length: 16 }, (_, i) => i);
233
- const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);
234
- const res = [];
235
- for (let i = 0, v = Id; i < 7; i++, v = permute(v))
236
- res.push(...v);
237
- return Uint8Array.from(res);
238
- })();
239
- var BLAKE3 = class _BLAKE3 extends BLAKE2 {
240
- constructor(opts = {}, flags = 0) {
241
- super(64, opts.dkLen === void 0 ? 32 : opts.dkLen);
242
- this.chunkPos = 0;
243
- this.chunksDone = 0;
244
- this.flags = 0 | 0;
245
- this.stack = [];
246
- this.posOut = 0;
247
- this.bufferOut32 = new Uint32Array(16);
248
- this.chunkOut = 0;
249
- this.enableXOF = true;
250
- const { key, context } = opts;
251
- const hasContext = context !== void 0;
252
- if (key !== void 0) {
253
- if (hasContext)
254
- throw new Error('Only "key" or "context" can be specified at same time');
255
- const k = toBytes(key).slice();
256
- abytes(k, 32);
257
- this.IV = u32(k);
258
- swap32IfBE(this.IV);
259
- this.flags = flags | B3_Flags.KEYED_HASH;
260
- } else if (hasContext) {
261
- const ctx = toBytes(context);
262
- const contextKey = new _BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT).update(ctx).digest();
263
- this.IV = u32(contextKey);
264
- swap32IfBE(this.IV);
265
- this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL;
266
- } else {
267
- this.IV = B3_IV.slice();
268
- this.flags = flags;
269
- }
270
- this.state = this.IV.slice();
271
- this.bufferOut = u8(this.bufferOut32);
272
- }
273
- // Unused
274
- get() {
41
+ function multicastEndpointSource(endpoint) {
42
+ if (!isObject(endpoint))
43
+ return void 0;
44
+ const sourceAddress = endpoint["sourceAddress"];
45
+ if (sourceAddress !== void 0 && !isNonEmptyString(sourceAddress))
46
+ return void 0;
47
+ const mode = sourceAddress === void 0 ? "asm" : "ssm";
48
+ const protocol = endpoint["protocol"];
49
+ if (protocol !== void 0 && protocol !== mode)
50
+ return void 0;
51
+ const auth = endpoint["auth"];
52
+ const senderAddress = isObject(auth) ? auth["senderAddress"] : void 0;
53
+ if (mode === "ssm")
54
+ return senderAddress === void 0 ? { mode, source: sourceAddress } : void 0;
55
+ if (auth === void 0)
56
+ return { mode };
57
+ return isNonEmptyString(senderAddress) ? { mode, source: senderAddress } : void 0;
58
+ }
59
+ function authIssues(auth) {
60
+ const base = "$.multicast.auth";
61
+ const issue = (path, message) => [
62
+ { code: "multicast_auth", path: `${base}${path}`, message }
63
+ ];
64
+ if (!isObject(auth))
65
+ return issue("", "auth must be an object");
66
+ const unknown = Object.keys(auth).filter((key) => !AUTH_MEMBERS.has(key));
67
+ if (unknown.length > 0) {
68
+ return issue("", `auth has unknown member(s) ${unknown.join(", ")}; draft -01 7.2.6 defines scheme, version, sig, keys and minEpoch`);
69
+ }
70
+ if (auth["scheme"] !== "bc-provenance")
71
+ return issue(".scheme", 'scheme must be "bc-provenance"');
72
+ if (auth["version"] !== 2)
73
+ return issue(".version", "version must be 2 (bc-provenance version 2, draft -01 7.2)");
74
+ if (auth["sig"] !== "ed25519")
75
+ return issue(".sig", 'sig must be "ed25519"');
76
+ const keys = auth["keys"];
77
+ if (!Array.isArray(keys) || keys.length < 1 || keys.length > 4) {
78
+ return issue(".keys", "keys must be an array of one to four {kid, publicKey, firstEpoch} objects");
79
+ }
80
+ const kids = /* @__PURE__ */ new Set();
81
+ const firstEpochs = /* @__PURE__ */ new Set();
82
+ for (let index = 0; index < keys.length; index++) {
83
+ const key = keys[index];
84
+ const at = `.keys[${index}]`;
85
+ if (!isObject(key) || Object.keys(key).some((member) => !KEY_MEMBERS.has(member))) {
86
+ return issue(at, "a key is exactly {kid, publicKey, firstEpoch}");
87
+ }
88
+ if (!isIntegerIn(key["kid"], 0, UINT32_MAX))
89
+ return issue(`${at}.kid`, "kid must be an unsigned 32-bit integer");
90
+ if (typeof key["publicKey"] !== "string" || !ED25519_PUBLIC_KEY_BASE64URL.test(key["publicKey"])) {
91
+ return issue(`${at}.publicKey`, "publicKey must be a 32-octet Ed25519 key in canonical unpadded base64url");
92
+ }
93
+ if (!isIntegerIn(key["firstEpoch"], 0, UINT32_MAX)) {
94
+ return issue(`${at}.firstEpoch`, "firstEpoch must be an unsigned 32-bit integer");
95
+ }
96
+ if (kids.has(key["kid"]))
97
+ return issue(`${at}.kid`, `kid ${key["kid"]} is repeated; the catalog holds no key set`);
98
+ if (firstEpochs.has(key["firstEpoch"])) {
99
+ return issue(`${at}.firstEpoch`, `firstEpoch ${key["firstEpoch"]} is repeated; the catalog holds no key set`);
100
+ }
101
+ kids.add(key["kid"]);
102
+ firstEpochs.add(key["firstEpoch"]);
103
+ }
104
+ if (!isIntegerIn(auth["minEpoch"], 0, UINT32_MAX)) {
105
+ return issue(".minEpoch", "minEpoch must be an unsigned 32-bit integer");
106
+ }
107
+ return [];
108
+ }
109
+ function endpointAuthIssue(endpoint, mode, at) {
110
+ const auth = endpoint["auth"];
111
+ if (!isObject(auth))
112
+ return { path: `${at}.auth`, message: "auth must be an object" };
113
+ const unknown = Object.keys(auth).filter((key) => !ENDPOINT_AUTH_MEMBERS.has(key));
114
+ if (unknown.length > 0)
115
+ return { path: `${at}.auth`, message: `auth has unknown member(s) ${unknown.join(", ")}` };
116
+ if (!isIntegerIn(auth["manifestPort"], 1, 65535)) {
117
+ return { path: `${at}.auth.manifestPort`, message: "manifestPort must be an integer from 1 to 65535" };
118
+ }
119
+ if (!isIntegerIn(auth["streamId"], 0, UINT32_MAX)) {
120
+ return { path: `${at}.auth.streamId`, message: "streamId must be an unsigned 32-bit integer" };
121
+ }
122
+ if (mode === "ssm" && auth["senderAddress"] !== void 0) {
123
+ return { path: `${at}.auth.senderAddress`, message: "senderAddress must not appear on an SSM endpoint; S is sourceAddress" };
124
+ }
125
+ if (mode === "asm" && !isNonEmptyString(auth["senderAddress"])) {
126
+ return { path: `${at}.auth.senderAddress`, message: "a protected ASM endpoint requires senderAddress" };
127
+ }
128
+ if (auth["maxAuthDelayMs"] !== void 0 && !isIntegerIn(auth["maxAuthDelayMs"], 50, 1e3)) {
129
+ return { path: `${at}.auth.maxAuthDelayMs`, message: "maxAuthDelayMs must be an integer from 50 to 1000" };
130
+ }
131
+ if (auth["manifestTimerMs"] !== void 0 && !isIntegerIn(auth["manifestTimerMs"], 1, Number.MAX_SAFE_INTEGER)) {
132
+ return { path: `${at}.auth.manifestTimerMs`, message: "manifestTimerMs must be an integer of at least 1" };
133
+ }
134
+ if (auth["manifestTrack"] !== void 0 && !isNonEmptyString(auth["manifestTrack"])) {
135
+ return { path: `${at}.auth.manifestTrack`, message: "manifestTrack must be a non-empty string" };
136
+ }
137
+ if (!isIntegerIn(endpoint["bandwidth"], 1, Number.MAX_SAFE_INTEGER)) {
138
+ return { path: `${at}.bandwidth`, message: "a protected endpoint requires bandwidth, which bounds the receiver's hold queues" };
139
+ }
140
+ return void 0;
141
+ }
142
+ var CATALOG_NAMESPACE = /* @__PURE__ */ Symbol.for("@blockcast/mmt-base/catalogNamespace");
143
+ function multicastCatalogIssues(catalog, options = {}) {
144
+ if (!isObject(catalog))
275
145
  return [];
146
+ const issues = [];
147
+ if ("multicast.auth" in catalog) {
148
+ issues.push({
149
+ code: "multicast_auth",
150
+ path: '$["multicast.auth"]',
151
+ message: 'the root "multicast.auth" key is retired; declare auth as multicast.auth (draft -01 7.2.6)'
152
+ });
276
153
  }
277
- set() {
278
- }
279
- b2Compress(counter, flags, buf, bufPos = 0) {
280
- const { state: s, pos } = this;
281
- const { h, l } = fromBig(BigInt(counter), true);
282
- const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(B3_SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], h, l, pos, flags);
283
- s[0] = v0 ^ v8;
284
- s[1] = v1 ^ v9;
285
- s[2] = v2 ^ v10;
286
- s[3] = v3 ^ v11;
287
- s[4] = v4 ^ v12;
288
- s[5] = v5 ^ v13;
289
- s[6] = v6 ^ v14;
290
- s[7] = v7 ^ v15;
291
- }
292
- compress(buf, bufPos = 0, isLast = false) {
293
- let flags = this.flags;
294
- if (!this.chunkPos)
295
- flags |= B3_Flags.CHUNK_START;
296
- if (this.chunkPos === 15 || isLast)
297
- flags |= B3_Flags.CHUNK_END;
298
- if (!isLast)
299
- this.pos = this.blockLen;
300
- this.b2Compress(this.chunksDone, flags, buf, bufPos);
301
- this.chunkPos += 1;
302
- if (this.chunkPos === 16 || isLast) {
303
- let chunk = this.state;
304
- this.state = this.IV.slice();
305
- for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) {
306
- if (!(last = this.stack.pop()))
307
- break;
308
- this.buffer32.set(last, 0);
309
- this.buffer32.set(chunk, 8);
310
- this.pos = this.blockLen;
311
- this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0);
312
- chunk = this.state;
313
- this.state = this.IV.slice();
154
+ const multicast = catalog["multicast"];
155
+ if (!isObject(multicast))
156
+ return issues;
157
+ const protectedCatalog = multicast["auth"] !== void 0;
158
+ if (protectedCatalog)
159
+ issues.push(...authIssues(multicast["auth"]));
160
+ const endpoints = multicast["endpoints"];
161
+ if (!Array.isArray(endpoints))
162
+ return issues;
163
+ const tracks = Array.isArray(catalog["tracks"]) ? catalog["tracks"] : [];
164
+ const namespaceOf = /* @__PURE__ */ new Map();
165
+ for (const track of tracks) {
166
+ if (isObject(track) && typeof track["name"] === "string")
167
+ namespaceOf.set(track["name"], track["namespace"]);
168
+ }
169
+ const tagged = catalog[CATALOG_NAMESPACE];
170
+ let referenceNamespace = options.catalogNamespace ?? (typeof tagged === "string" ? tagged : void 0);
171
+ const sources = [];
172
+ for (let index = 0; index < endpoints.length; index++) {
173
+ const endpoint = endpoints[index];
174
+ const at = `$.multicast.endpoints[${index}]`;
175
+ const fail = (code, path, message) => {
176
+ issues.push({ code, path, message, endpointIndex: index });
177
+ };
178
+ sources.push(void 0);
179
+ if (!isObject(endpoint)) {
180
+ fail("multicast_endpoint", at, "endpoint must be an object");
181
+ continue;
182
+ }
183
+ const protocol = endpoint["protocol"];
184
+ if (protocol !== void 0 && protocol !== "ssm" && protocol !== "asm") {
185
+ fail("multicast_endpoint", `${at}.protocol`, `protocol must be "ssm" or "asm"; a bearer such as ${JSON.stringify(protocol)} is a networkSource entry (draft -01 4.2)`);
186
+ continue;
187
+ }
188
+ const hasAuth = endpoint["auth"] !== void 0;
189
+ if (protectedCatalog !== hasAuth) {
190
+ fail("multicast_endpoint_auth", `${at}.auth`, protectedCatalog ? "every endpoint requires auth when multicast carries auth; a receiver ignores this endpoint" : "auth names no key without multicast.auth; a receiver ignores this endpoint");
191
+ continue;
192
+ }
193
+ const sourceAddress = endpoint["sourceAddress"];
194
+ if (sourceAddress !== void 0 && !isNonEmptyString(sourceAddress)) {
195
+ fail("multicast_endpoint", `${at}.sourceAddress`, "sourceAddress must be a non-empty string");
196
+ continue;
197
+ }
198
+ const mode = sourceAddress === void 0 ? "asm" : "ssm";
199
+ if (protocol !== void 0 && protocol !== mode) {
200
+ fail("multicast_endpoint", `${at}.protocol`, `protocol ${JSON.stringify(protocol)} disagrees with sourceAddress, which selects ${mode}`);
201
+ continue;
202
+ }
203
+ if (!isIntegerIn(endpoint["port"], 1, 65535)) {
204
+ fail("multicast_endpoint", `${at}.port`, "port must be an integer from 1 to 65535");
205
+ continue;
206
+ }
207
+ if (hasAuth) {
208
+ const authIssue = endpointAuthIssue(endpoint, mode, at);
209
+ if (authIssue) {
210
+ fail("multicast_endpoint_auth", authIssue.path, authIssue.message);
211
+ continue;
314
212
  }
315
- this.chunksDone++;
316
- this.chunkPos = 0;
317
- this.stack.push(chunk);
318
213
  }
319
- this.pos = 0;
320
- }
321
- _cloneInto(to) {
322
- to = super._cloneInto(to);
323
- const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;
324
- to.state.set(state.slice());
325
- to.stack = stack.map((i) => Uint32Array.from(i));
326
- to.IV.set(IV);
327
- to.flags = flags;
328
- to.chunkPos = chunkPos;
329
- to.chunksDone = chunksDone;
330
- to.posOut = posOut;
331
- to.chunkOut = chunkOut;
332
- to.enableXOF = this.enableXOF;
333
- to.bufferOut32.set(this.bufferOut32);
334
- return to;
335
- }
336
- destroy() {
337
- this.destroyed = true;
338
- clean(this.state, this.buffer32, this.IV, this.bufferOut32);
339
- clean(...this.stack);
340
- }
341
- // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)
342
- b2CompressOut() {
343
- const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this;
344
- const { h, l } = fromBig(BigInt(this.chunkOut++));
345
- swap32IfBE(buffer32);
346
- const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(B3_SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], l, h, pos, flags);
347
- out32[0] = v0 ^ v8;
348
- out32[1] = v1 ^ v9;
349
- out32[2] = v2 ^ v10;
350
- out32[3] = v3 ^ v11;
351
- out32[4] = v4 ^ v12;
352
- out32[5] = v5 ^ v13;
353
- out32[6] = v6 ^ v14;
354
- out32[7] = v7 ^ v15;
355
- out32[8] = s[0] ^ v8;
356
- out32[9] = s[1] ^ v9;
357
- out32[10] = s[2] ^ v10;
358
- out32[11] = s[3] ^ v11;
359
- out32[12] = s[4] ^ v12;
360
- out32[13] = s[5] ^ v13;
361
- out32[14] = s[6] ^ v14;
362
- out32[15] = s[7] ^ v15;
363
- swap32IfBE(buffer32);
364
- swap32IfBE(out32);
365
- this.posOut = 0;
366
- }
367
- finish() {
368
- if (this.finished)
369
- return;
370
- this.finished = true;
371
- clean(this.buffer.subarray(this.pos));
372
- let flags = this.flags | B3_Flags.ROOT;
373
- if (this.stack.length) {
374
- flags |= B3_Flags.PARENT;
375
- swap32IfBE(this.buffer32);
376
- this.compress(this.buffer32, 0, true);
377
- swap32IfBE(this.buffer32);
378
- this.chunksDone = 0;
379
- this.pos = this.blockLen;
380
- } else {
381
- flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END;
214
+ sources[index] = multicastEndpointSource(endpoint);
215
+ const refs = Array.isArray(endpoint["tracks"]) ? endpoint["tracks"] : [];
216
+ for (let refIndex = 0; refIndex < refs.length; refIndex++) {
217
+ const ref = refs[refIndex];
218
+ const name = isObject(ref) ? ref["name"] : ref;
219
+ if (typeof name !== "string")
220
+ continue;
221
+ const namespace = namespaceOf.get(name);
222
+ if (typeof namespace !== "string")
223
+ continue;
224
+ referenceNamespace ??= namespace;
225
+ if (namespace !== referenceNamespace) {
226
+ fail("multicast_track", `${at}.tracks[${refIndex}].name`, `track ${JSON.stringify(name)} declares namespace ${JSON.stringify(namespace)}, not the catalog track's ${JSON.stringify(referenceNamespace)}`);
227
+ }
382
228
  }
383
- this.flags = flags;
384
- this.b2CompressOut();
385
229
  }
386
- writeInto(out) {
387
- aexists(this, false);
388
- abytes(out);
389
- this.finish();
390
- const { blockLen, bufferOut } = this;
391
- for (let pos = 0, len = out.length; pos < len; ) {
392
- if (this.posOut >= blockLen)
393
- this.b2CompressOut();
394
- const take = Math.min(blockLen - this.posOut, len - pos);
395
- out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
396
- this.posOut += take;
397
- pos += take;
230
+ const tupleOf = (index) => {
231
+ const endpoint = endpoints[index];
232
+ const auth = endpoint["auth"];
233
+ return {
234
+ sg: JSON.stringify([sources[index].source ?? null, endpoint["groupAddress"]]),
235
+ port: endpoint["port"],
236
+ manifestPort: isObject(auth) ? auth["manifestPort"] : void 0
237
+ };
238
+ };
239
+ for (let index = 0; index < endpoints.length; index++) {
240
+ if (!sources[index])
241
+ continue;
242
+ const own = tupleOf(index);
243
+ const at = `$.multicast.endpoints[${index}]`;
244
+ if (own.manifestPort !== void 0 && own.manifestPort === own.port) {
245
+ issues.push({ code: "multicast_endpoint_auth", path: `${at}.auth.manifestPort`, message: "manifestPort must differ from the endpoint's own port", endpointIndex: index });
246
+ continue;
247
+ }
248
+ for (let other = 0; other < endpoints.length; other++) {
249
+ if (other === index || !sources[other])
250
+ continue;
251
+ const peer = tupleOf(other);
252
+ if (peer.sg !== own.sg)
253
+ continue;
254
+ if (peer.port === own.port) {
255
+ issues.push({ code: "multicast_endpoint", path: `${at}.port`, message: `(S, G, port) is shared with endpoint ${other}; one endpoint object per multicast tuple`, endpointIndex: index });
256
+ break;
257
+ }
258
+ if (own.manifestPort !== void 0 && (own.manifestPort === peer.port || own.manifestPort === peer.manifestPort)) {
259
+ issues.push({ code: "multicast_endpoint_auth", path: `${at}.auth.manifestPort`, message: `manifestPort is a port or manifestPort of endpoint ${other} on the same (S, G)`, endpointIndex: index });
260
+ break;
261
+ }
398
262
  }
399
- return out;
400
- }
401
- xofInto(out) {
402
- if (!this.enableXOF)
403
- throw new Error("XOF is not possible after digest call");
404
- return this.writeInto(out);
405
- }
406
- xof(bytes) {
407
- anumber(bytes);
408
- return this.xofInto(new Uint8Array(bytes));
409
- }
410
- digestInto(out) {
411
- aoutput(out, this);
412
- if (this.finished)
413
- throw new Error("digest() was already called");
414
- this.enableXOF = false;
415
- this.writeInto(out);
416
- this.destroy();
417
- return out;
418
- }
419
- digest() {
420
- return this.digestInto(new Uint8Array(this.outputLen));
421
263
  }
422
- };
423
- var blake3 = /* @__PURE__ */ createXOFer((opts) => new BLAKE3(opts));
264
+ return issues;
265
+ }
424
266
 
425
267
  // ../mmt-manifest-verify/dist/source-auth.js
426
- var SOURCE_AUTH_MANIFEST_VERSION = 1;
427
- var SOURCE_AUTH_OBJECT_ENTRY_FRAME = 1;
428
- var SOURCE_AUTH_GROUP_CLOSE_FRAME = 2;
429
- var SOURCE_AUTH_OBJECT_ENTRY_LENGTH = 52;
430
- var SOURCE_AUTH_GROUP_CLOSE_LENGTH = 112;
431
- var SOURCE_AUTH_MAX_OBJECTS_PER_GROUP = 4096;
432
268
  var SOURCE_AUTH_MAX_TRUE_LENGTH = 16 * 1024 * 1024;
433
- var SOURCE_AUTH_SCOPE_LENGTH = 32;
434
269
  var SIGNATURE_DOMAIN = new TextEncoder().encode("blockcast-mmt-root-v1\0\0\0");
435
- function requireBytes(name, value, length) {
436
- if (value.byteLength !== length) {
437
- throw new Error(`${name} must be ${length} bytes, got ${value.byteLength}`);
438
- }
439
- }
440
- function requireU32(name, value) {
441
- if (!Number.isInteger(value) || value < 0 || value > 4294967295) {
442
- throw new Error(`${name} must be an unsigned 32-bit integer`);
443
- }
444
- }
445
- function requireU64(name, value) {
446
- if (value < 0n || value > 0xffffffffffffffffn) {
447
- throw new Error(`${name} must be an unsigned 64-bit integer`);
448
- }
449
- }
450
- function requireTrueLength(value) {
451
- requireU32("trueLength", value);
452
- if (value > SOURCE_AUTH_MAX_TRUE_LENGTH) {
453
- throw new Error(`trueLength exceeds the ${SOURCE_AUTH_MAX_TRUE_LENGTH}-byte profile maximum`);
454
- }
455
- }
456
- function sourceAuthObjectDigest(object) {
457
- return blake3(object);
458
- }
459
- function sourceAuthLeafHash(groupId, objectId, digest, trueLength) {
460
- requireU64("groupId", groupId);
461
- requireU32("objectId", objectId);
462
- requireBytes("digest", digest, 32);
463
- requireTrueLength(trueLength);
464
- const preimage = new Uint8Array(49);
465
- const view = new DataView(preimage.buffer);
466
- view.setBigUint64(1, groupId);
467
- view.setUint32(9, objectId);
468
- preimage.set(digest, 13);
469
- view.setUint32(45, trueLength);
470
- return blake3(preimage);
471
- }
472
- function sourceAuthMerkleRoot(entries) {
473
- if (entries.length === 0)
474
- throw new Error("Merkle tree requires at least one object");
475
- if (entries.length > SOURCE_AUTH_MAX_OBJECTS_PER_GROUP) {
476
- throw new Error(`group exceeds ${SOURCE_AUTH_MAX_OBJECTS_PER_GROUP} objects`);
477
- }
478
- const groupId = entries[0].groupId;
479
- const objectIds = /* @__PURE__ */ new Set();
480
- const ordered = [...entries].sort((left, right) => left.objectId - right.objectId);
481
- let level = ordered.map((entry) => {
482
- if (entry.groupId !== groupId)
483
- throw new Error("Merkle entries must belong to one group");
484
- if (objectIds.has(entry.objectId))
485
- throw new Error(`duplicate objectId ${entry.objectId}`);
486
- objectIds.add(entry.objectId);
487
- return sourceAuthLeafHash(entry.groupId, entry.objectId, entry.digest, entry.trueLength);
488
- });
489
- while (level.length > 1) {
490
- const parents = [];
491
- for (let index = 0; index < level.length; index += 2) {
492
- const left = level[index];
493
- const right = level[index + 1] ?? left;
494
- const preimage = new Uint8Array(65);
495
- preimage[0] = 1;
496
- preimage.set(left, 1);
497
- preimage.set(right, 33);
498
- parents.push(blake3(preimage));
499
- }
500
- level = parents;
501
- }
502
- return level[0];
503
- }
504
- function sourceAuthSignaturePreimage(authScope, groupId, objectCount, root) {
505
- requireU32("objectCount", objectCount);
506
- if (objectCount === 0 || objectCount > SOURCE_AUTH_MAX_OBJECTS_PER_GROUP) {
507
- throw new Error(`objectCount must be between 1 and ${SOURCE_AUTH_MAX_OBJECTS_PER_GROUP}`);
508
- }
509
- requireU64("groupId", groupId);
510
- requireBytes("authScope", authScope, SOURCE_AUTH_SCOPE_LENGTH);
511
- requireBytes("root", root, 32);
512
- const preimage = new Uint8Array(100);
513
- const view = new DataView(preimage.buffer);
514
- preimage.set(SIGNATURE_DOMAIN);
515
- preimage.set(authScope, 24);
516
- view.setBigUint64(56, groupId);
517
- view.setUint32(64, objectCount);
518
- preimage.set(root, 68);
519
- return preimage;
520
- }
521
- function decodeSourceAuthManifestFrame(frame) {
522
- const frameType = frame[0];
523
- const expectedLength = frameType === SOURCE_AUTH_OBJECT_ENTRY_FRAME ? SOURCE_AUTH_OBJECT_ENTRY_LENGTH : frameType === SOURCE_AUTH_GROUP_CLOSE_FRAME ? SOURCE_AUTH_GROUP_CLOSE_LENGTH : 0;
524
- if (expectedLength === 0)
525
- throw new Error(`unsupported manifest frame type ${frameType}`);
526
- if (frame.byteLength !== expectedLength) {
527
- throw new Error(`manifest frame has invalid length ${frame.byteLength} for type ${frameType}`);
528
- }
529
- if (frame[1] !== SOURCE_AUTH_MANIFEST_VERSION) {
530
- throw new Error(`unsupported manifest version ${frame[1]}`);
531
- }
532
- if (frame[2] !== 0 || frame[3] !== 0)
533
- throw new Error("manifest reserved bits must be zero");
534
- const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
535
- const groupId = view.getBigUint64(4);
536
- if (frameType === SOURCE_AUTH_OBJECT_ENTRY_FRAME) {
537
- const entry = {
538
- kind: "object",
539
- groupId,
540
- objectId: view.getUint32(12),
541
- trueLength: view.getUint32(16),
542
- digest: frame.slice(20, 52)
543
- };
544
- requireTrueLength(entry.trueLength);
545
- return entry;
546
- }
547
- const close = {
548
- kind: "close",
549
- groupId,
550
- objectCount: view.getUint32(12),
551
- root: frame.slice(16, 48),
552
- signature: frame.slice(48, 112)
553
- };
554
- if (close.objectCount === 0 || close.objectCount > SOURCE_AUTH_MAX_OBJECTS_PER_GROUP) {
555
- throw new Error(`objectCount must be between 1 and ${SOURCE_AUTH_MAX_OBJECTS_PER_GROUP}`);
556
- }
557
- return close;
558
- }
559
270
 
560
271
  // ../mmt-manifest-verify/dist/verifier.js
561
- function manifestBindingId(trackName, sourceSymbolFormat) {
562
- return JSON.stringify([trackName, sourceSymbolFormat]);
563
- }
564
- var FAILURE_REASONS = [
565
- "sigInvalid",
566
- "digestMismatch",
567
- "manifestLate",
568
- "manifestAbsent",
569
- "verifierError"
570
- ];
571
- var equalBytes = (left, right) => {
572
- if (left.byteLength !== right.byteLength)
573
- return false;
574
- let diff = 0;
575
- for (let index = 0; index < left.byteLength; index++)
576
- diff |= left[index] ^ right[index];
577
- return diff === 0;
578
- };
579
- var isPromiseLike = (value) => typeof value === "object" && value !== null && typeof value.then === "function";
580
- var ManifestVerifier = class {
581
- #config;
582
- #verifySignature;
583
- #onFailure;
584
- #tracks = /* @__PURE__ */ new Map();
585
- #stats = {
586
- verified: 0,
587
- failures: Object.fromEntries(FAILURE_REASONS.map((reason) => [reason, 0])),
588
- quarantinedBytes: 0
589
- };
590
- #disposed = false;
591
- constructor(options) {
592
- this.#config = { ...options.manifestAuth };
593
- this.#verifySignature = options.verifySignature;
594
- this.#onFailure = options.onFailure;
595
- }
596
- get config() {
597
- return this.#config;
598
- }
599
- get stats() {
600
- let quarantined = 0;
601
- for (const track of this.#tracks.values())
602
- quarantined += track.quarantine.length;
603
- return {
604
- verified: this.#stats.verified,
605
- failures: { ...this.#stats.failures },
606
- quarantined,
607
- quarantinedBytes: this.#stats.quarantinedBytes
608
- };
609
- }
610
- setMode(mode) {
611
- this.#config = { ...this.#config, mode };
612
- if (mode !== "enforce")
613
- this.#releaseAllQuarantine(false);
614
- }
615
- registerTrack(context) {
616
- const bindingId = context.bindingId ?? context.trackName;
617
- if (this.#tracks.has(bindingId)) {
618
- throw new Error(`manifest binding ${bindingId} is already registered`);
619
- }
620
- if (!Number.isFinite(context.bitrate) || context.bitrate <= 0) {
621
- throw new Error("manifest track bitrate must be > 0");
622
- }
623
- if (!Number.isFinite(context.groupDurationMs) || context.groupDurationMs <= 0) {
624
- throw new Error("manifest track groupDurationMs must be > 0");
625
- }
626
- if (context.authScope.byteLength !== 32)
627
- throw new Error("manifest authScope must be 32 bytes");
628
- if (context.publicKey.byteLength !== 32)
629
- throw new Error("manifest publicKey must be 32 bytes");
630
- for (const key of context.acceptedPublicKeys ?? []) {
631
- if (key.byteLength !== 32)
632
- throw new Error("manifest acceptedPublicKeys must contain 32-byte keys");
633
- }
634
- for (const [name, value] of Object.entries({
635
- broadcastNamespaceId: context.broadcastNamespaceId,
636
- trackName: context.trackName,
637
- codec: context.codec,
638
- timing: context.timing,
639
- fecGeometry: context.fecGeometry
640
- })) {
641
- if (value.length === 0)
642
- throw new Error(`manifest ${name} must not be empty`);
643
- }
644
- this.#tracks.set(bindingId, {
645
- context: { ...context, bindingId },
646
- groups: /* @__PURE__ */ new Map(),
647
- quarantine: [],
648
- quarantinedBytes: 0,
649
- capBytes: Math.ceil(context.bitrate * context.groupDurationMs / 8e3),
650
- manifestEntries: 0,
651
- maxManifestEntries: Math.ceil(context.bitrate * context.groupDurationMs / (8e3 * 52)),
652
- maxGroups: context.mapper.d + 1
653
- });
654
- }
655
- ingestManifestFrame(bindingId, frameBytes) {
656
- const track = this.#requireTrack(bindingId);
657
- try {
658
- const frame = decodeSourceAuthManifestFrame(frameBytes);
659
- const groupId = frame.groupId;
660
- const group = this.#group(track, groupId);
661
- if (frame.kind === "object") {
662
- if (group.close || group.signaturePending || group.failed) {
663
- this.#failure({ trackName: track.context.trackName, bindingId, groupId, objectId: frame.objectId }, "verifierError");
664
- return;
665
- }
666
- if (group.entries.has(frame.objectId)) {
667
- this.#failure({ trackName: track.context.trackName, bindingId, groupId, objectId: frame.objectId }, "verifierError");
668
- return;
669
- }
670
- if (group.entries.size >= 4096 || track.manifestEntries >= track.maxManifestEntries) {
671
- this.#failure({ trackName: track.context.trackName, bindingId, groupId, objectId: frame.objectId }, "verifierError");
672
- return;
673
- }
674
- group.entries.set(frame.objectId, frame);
675
- track.manifestEntries++;
676
- const pending = group.pending.get(frame.objectId);
677
- if (pending) {
678
- this.#failure(pending.identity, "manifestLate");
679
- this.#resolvePending(track, group, pending, frame);
680
- }
681
- if (group.pendingClose && group.entries.size === group.pendingClose.objectCount) {
682
- const close = group.pendingClose;
683
- group.pendingClose = void 0;
684
- this.#closeGroup(track, groupId, group, close);
685
- }
686
- return;
687
- }
688
- this.#closeGroup(track, groupId, group, frame);
689
- } catch {
690
- this.#failure({ trackName: track.context.trackName, bindingId, groupId: 0, objectId: 0 }, "verifierError");
691
- }
692
- }
693
- admitObject(identity, data, release, discard) {
694
- if (this.#config.mode === "off") {
695
- release();
696
- return { action: "play", verified: false };
697
- }
698
- const track = this.#tracks.get(identity.bindingId ?? identity.trackName);
699
- if (!track) {
700
- release();
701
- this.#failure(identity, "verifierError");
702
- return { action: "play", verified: false, reason: "verifierError" };
703
- }
704
- try {
705
- if (!this.#validateIdentity(track, identity)) {
706
- return this.#rejectOrShadow(identity, release, "digestMismatch");
707
- }
708
- const group = this.#group(track, BigInt(identity.groupId));
709
- if (group.failed === "sigInvalid" || group.failed === "digestMismatch") {
710
- return this.#rejectOrShadow(identity, release, group.failed);
711
- }
712
- const entry = group.entries.get(identity.objectId);
713
- if (entry)
714
- return this.#admitAgainstEntry(track, group, identity, data, release, entry, discard);
715
- if (this.#config.mode === "shadow" || this.#config.onMissingManifest === "fallback-shadow") {
716
- release();
717
- this.#failure(identity, "manifestAbsent");
718
- return { action: "play", verified: false, reason: "manifestAbsent" };
719
- }
720
- if (!this.#quarantine(track, group, { identity, data, release, discard, bytes: data.byteLength })) {
721
- return { action: "drop", verified: false };
722
- }
723
- return { action: "stall", verified: false };
724
- } catch {
725
- release();
726
- this.#failure(identity, "verifierError");
727
- return { action: "play", verified: false, reason: "verifierError" };
728
- }
729
- }
730
- dispose() {
731
- if (this.#disposed)
732
- return;
733
- this.#disposed = true;
734
- this.#releaseAllQuarantine(false);
735
- this.#tracks.clear();
736
- }
737
- #requireTrack(bindingId) {
738
- const track = this.#tracks.get(bindingId);
739
- if (!track)
740
- throw new Error(`unknown manifest binding ${bindingId}`);
741
- return track;
742
- }
743
- #group(track, groupId) {
744
- let group = track.groups.get(groupId);
745
- if (!group) {
746
- group = { entries: /* @__PURE__ */ new Map(), pending: /* @__PURE__ */ new Map(), rootVerified: false };
747
- track.groups.set(groupId, group);
748
- while (track.groups.size > track.maxGroups) {
749
- const oldest = track.groups.entries().next().value;
750
- if (!oldest)
751
- break;
752
- const [oldestId, oldestGroup] = oldest;
753
- for (const pending of [...oldestGroup.pending.values()]) {
754
- this.#removePending(track, oldestGroup, pending);
755
- this.#giveUpOnPending(pending);
756
- this.#failure(pending.identity, "manifestAbsent");
757
- }
758
- track.manifestEntries -= oldestGroup.entries.size;
759
- track.groups.delete(oldestId);
760
- }
761
- }
762
- return group;
763
- }
764
- #validateIdentity(track, identity) {
765
- const coordinates = track.context.mapper.derive(Number(identity.groupId), identity.objectId);
766
- return identity.ssId === void 0 || coordinates.ssId === identity.ssId;
767
- }
768
- #admitAgainstEntry(track, group, identity, data, release, entry, discard) {
769
- if (entry.trueLength !== data.byteLength) {
770
- return this.#rejectOrShadow(identity, release, "digestMismatch");
771
- }
772
- const digestMatches = equalBytes(sourceAuthObjectDigest(data.subarray(0, entry.trueLength)), entry.digest);
773
- if (!digestMatches)
774
- return this.#rejectOrShadow(identity, release, "digestMismatch");
775
- if (!track.context.manifestChannelAuthenticated && !group.rootVerified) {
776
- if (this.#config.mode === "shadow") {
777
- release();
778
- return { action: "play", verified: false };
779
- }
780
- if (!this.#quarantine(track, group, { identity, data, release, discard, bytes: data.byteLength })) {
781
- return { action: "drop", verified: false };
782
- }
783
- return { action: "stall", verified: false };
784
- }
785
- release();
786
- this.#stats.verified++;
787
- return { action: "play", verified: true };
788
- }
789
- #rejectOrShadow(identity, release, reason) {
790
- this.#failure(identity, reason);
791
- if (this.#config.mode === "enforce") {
792
- console.warn(JSON.stringify({ event: "manifest-enforce-drop", track: identity.trackName, group: String(identity.groupId), object: identity.objectId, reason }));
793
- return { action: "drop", verified: false, reason };
794
- }
795
- release();
796
- return { action: "play", verified: false, reason };
797
- }
798
- #resolvePending(track, group, pending, entry) {
799
- this.#removePending(track, group, pending);
800
- this.#admitAgainstEntry(track, group, pending.identity, pending.data, pending.release, entry, pending.discard);
801
- }
802
- #closeGroup(track, groupId, group, close) {
803
- if (group.close || group.signaturePending)
804
- return;
805
- const entries = [...group.entries.values()];
806
- if (entries.length !== close.objectCount) {
807
- group.pendingClose = close;
808
- const hadPending = group.pending.size > 0;
809
- if (this.#config.onMissingManifest === "fallback-shadow" || this.#config.mode === "shadow") {
810
- for (const pending of [...group.pending.values()]) {
811
- this.#removePending(track, group, pending);
812
- pending.release();
813
- this.#failure(pending.identity, "manifestAbsent");
814
- }
815
- } else {
816
- for (const pending of group.pending.values()) {
817
- this.#failure(pending.identity, "manifestAbsent");
818
- }
819
- }
820
- if (!hadPending) {
821
- this.#failure({ trackName: track.context.trackName, groupId, objectId: 0 }, "manifestAbsent");
822
- }
823
- return;
824
- }
825
- if (!equalBytes(sourceAuthMerkleRoot(entries), close.root)) {
826
- group.failed = "digestMismatch";
827
- this.#failGroup(track, groupId, group, "digestMismatch");
828
- return;
829
- }
830
- const preimage = sourceAuthSignaturePreimage(track.context.authScope, close.groupId, close.objectCount, close.root);
831
- let signatureValid;
832
- try {
833
- signatureValid = this.#verifyAcceptedSignature(track, preimage, close.signature);
834
- } catch {
835
- this.#failOpenGroup(track, groupId, group);
836
- return;
837
- }
838
- if (isPromiseLike(signatureValid)) {
839
- group.signaturePending = true;
840
- void signatureValid.then((valid) => {
841
- if (this.#disposed)
842
- return;
843
- group.signaturePending = false;
844
- this.#finishGroupSignature(track, groupId, group, close, valid);
845
- }, () => {
846
- if (this.#disposed)
847
- return;
848
- group.signaturePending = false;
849
- this.#failOpenGroup(track, groupId, group);
850
- });
851
- return;
852
- }
853
- this.#finishGroupSignature(track, groupId, group, close, signatureValid);
854
- }
855
- #finishGroupSignature(track, groupId, group, close, signatureValid) {
856
- if (!signatureValid) {
857
- group.failed = "sigInvalid";
858
- this.#failGroup(track, groupId, group, "sigInvalid");
859
- return;
860
- }
861
- group.failed = void 0;
862
- group.close = close;
863
- group.pendingClose = void 0;
864
- group.rootVerified = true;
865
- for (const pending of [...group.pending.values()]) {
866
- const entry = group.entries.get(pending.identity.objectId);
867
- if (entry)
868
- this.#resolvePending(track, group, pending, entry);
869
- else if (this.#config.onMissingManifest === "fallback-shadow") {
870
- this.#removePending(track, group, pending);
871
- pending.release();
872
- this.#failure(pending.identity, "manifestAbsent");
873
- }
874
- }
875
- }
876
- #verifyAcceptedSignature(track, message, signature) {
877
- const keys = track.context.acceptedPublicKeys ?? [track.context.publicKey];
878
- const pending = [];
879
- let hadSynchronousError = false;
880
- for (const key of keys) {
881
- try {
882
- const result = this.#verifySignature(key, message, signature);
883
- if (isPromiseLike(result)) {
884
- pending.push(Promise.resolve(result).then((valid) => valid, () => "error"));
885
- } else if (result) {
886
- return true;
887
- }
888
- } catch {
889
- hadSynchronousError = true;
890
- }
891
- }
892
- if (pending.length === 0) {
893
- if (hadSynchronousError)
894
- throw new Error("manifest signature verifier unavailable");
895
- return false;
896
- }
897
- return Promise.all(pending).then((results) => {
898
- if (results.some((valid) => valid === true))
899
- return true;
900
- if (hadSynchronousError || results.some((valid) => valid === "error")) {
901
- throw new Error("manifest signature verifier unavailable");
902
- }
903
- return false;
904
- });
905
- }
906
- #failGroup(track, groupId, group, reason) {
907
- if (group.pending.size === 0) {
908
- this.#failure({ trackName: track.context.trackName, groupId, objectId: 0 }, reason);
909
- return;
910
- }
911
- for (const pending of [...group.pending.values()]) {
912
- this.#removePending(track, group, pending);
913
- if (this.#rejectOrShadow(pending.identity, pending.release, reason).action === "drop") {
914
- pending.discard?.();
915
- }
916
- }
917
- }
918
- #removePending(track, group, pending) {
919
- if (group.pending.get(pending.identity.objectId) === pending) {
920
- group.pending.delete(pending.identity.objectId);
921
- }
922
- const index = track.quarantine.indexOf(pending);
923
- if (index >= 0)
924
- track.quarantine.splice(index, 1);
925
- track.quarantinedBytes -= pending.bytes;
926
- this.#stats.quarantinedBytes -= pending.bytes;
927
- }
928
- #quarantine(track, group, pending) {
929
- if (group.pending.has(pending.identity.objectId))
930
- return false;
931
- group.pending.set(pending.identity.objectId, pending);
932
- track.quarantine.push(pending);
933
- track.quarantinedBytes += pending.bytes;
934
- this.#stats.quarantinedBytes += pending.bytes;
935
- this.#enforceCap(track);
936
- return true;
937
- }
938
- #enforceCap(track) {
939
- while (track.quarantinedBytes > track.capBytes && track.quarantine.length > 0) {
940
- const pending = track.quarantine.shift();
941
- const group = track.groups.get(BigInt(pending.identity.groupId));
942
- if (group)
943
- group.pending.delete(pending.identity.objectId);
944
- track.quarantinedBytes -= pending.bytes;
945
- this.#stats.quarantinedBytes -= pending.bytes;
946
- this.#giveUpOnPending(pending);
947
- this.#failure(pending.identity, "manifestAbsent");
948
- console.warn(`[ManifestVerifier] quarantine cap eviction track=${pending.identity.trackName} group=${pending.identity.groupId} object=${pending.identity.objectId} disposition=${this.#config.mode === "enforce" ? "drop" : "fail-open"}`);
949
- }
950
- }
951
- /**
952
- * Stop waiting for a manifest that never arrived. In `enforce` the object is
953
- * discarded: an eviction is a rejection, not a deferred play, so unverified
954
- * media never reaches the player two groups after the stall was recorded
955
- * (BLO-30095, CTO disposition on the issue thread).
956
- *
957
- * Deliberately NOT used by `#failOpenGroup`/`#failOpenTrack` — failing open on
958
- * a genuine verifier fault is correct and stays untouched.
959
- */
960
- #giveUpOnPending(pending) {
961
- if (this.#config.mode !== "enforce") {
962
- pending.release();
963
- return;
964
- }
965
- pending.discard?.();
966
- }
967
- #failOpenTrack(track, reason) {
968
- for (const pending of [...track.quarantine]) {
969
- const group = track.groups.get(BigInt(pending.identity.groupId));
970
- if (group)
971
- this.#removePending(track, group, pending);
972
- pending.release();
973
- this.#failure(pending.identity, reason);
974
- }
975
- }
976
- #failOpenGroup(track, groupId, group) {
977
- const pending = [...group.pending.values()];
978
- if (pending.length === 0) {
979
- this.#failure({ trackName: track.context.trackName, groupId, objectId: 0 }, "verifierError");
980
- return;
981
- }
982
- for (const object of pending) {
983
- this.#removePending(track, group, object);
984
- object.release();
985
- this.#failure(object.identity, "verifierError");
986
- }
987
- }
988
- #releaseAllQuarantine(countFailure) {
989
- for (const track of this.#tracks.values()) {
990
- for (const pending of [...track.quarantine]) {
991
- const group = track.groups.get(BigInt(pending.identity.groupId));
992
- if (group)
993
- this.#removePending(track, group, pending);
994
- pending.release();
995
- if (countFailure)
996
- this.#failure(pending.identity, "verifierError");
997
- }
998
- }
999
- }
1000
- #failure(identity, reason) {
1001
- this.#stats.failures[reason]++;
1002
- this.#onFailure?.({
1003
- trackName: identity.trackName,
1004
- ...identity.bindingId === void 0 ? {} : { bindingId: identity.bindingId },
1005
- groupId: identity.groupId,
1006
- objectId: identity.objectId,
1007
- reason
1008
- });
272
+ function manifestKeyFor(keys, epoch, kid) {
273
+ if (new Set(keys.map((key) => key.kid)).size !== keys.length)
274
+ return void 0;
275
+ if (new Set(keys.map((key) => key.firstEpoch)).size !== keys.length)
276
+ return void 0;
277
+ let signer;
278
+ for (const key of keys) {
279
+ if (key.firstEpoch <= epoch && (signer === void 0 || key.firstEpoch > signer.firstEpoch))
280
+ signer = key;
1009
281
  }
1010
- };
282
+ if (signer === void 0 || kid !== void 0 && signer.kid !== kid)
283
+ return void 0;
284
+ return signer.publicKey;
285
+ }
286
+
287
+ // ../mmt-manifest-verify/dist/bc-provenance-v2.js
288
+ var BCPV2_HEADER_LENGTH = 68;
289
+ var BCPV2_SIGNATURE_LENGTH = 64;
290
+ var BCPV2_MIN_RECORD_LENGTH = BCPV2_HEADER_LENGTH + 32 + BCPV2_SIGNATURE_LENGTH;
291
+ var text = new TextEncoder();
292
+ var MAGIC = Uint8Array.from([77, 72, 77, 50]);
293
+ var SIGNING_DOMAIN = text.encode("mcast-manifest-v2\0");
1011
294
 
1012
295
  // src/multicast-auth-catalog.ts
1013
296
  var RAW_ED25519_KEY_LENGTH = 32;
1014
- var SOURCE_AUTH_SCOPE_LENGTH2 = 32;
297
+ var DEFAULT_MAX_AUTH_DELAY_MS = 200;
298
+ var DEFAULT_MANIFEST_TIMER_MS = 20;
1015
299
  var BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1016
300
  function encodeBase64Url(bytes) {
1017
301
  let output = "";
@@ -1035,18 +319,18 @@ var BASE64URL_DECODE_TABLE = (() => {
1035
319
  }
1036
320
  return table;
1037
321
  })();
1038
- function decodeBase64Url(text) {
1039
- if (text.length % 4 === 1) {
1040
- throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text}"`);
322
+ function decodeBase64Url(text2) {
323
+ if (text2.length % 4 === 1) {
324
+ throw new Error(`[multicast-auth-catalog] invalid unpadded base64url length for "${text2}"`);
1041
325
  }
1042
326
  const bytes = [];
1043
327
  let buffer = 0;
1044
328
  let bits = 0;
1045
- for (let i = 0; i < text.length; i++) {
1046
- const code = text.charCodeAt(i);
329
+ for (let i = 0; i < text2.length; i++) {
330
+ const code = text2.charCodeAt(i);
1047
331
  const value = code < 128 ? BASE64URL_DECODE_TABLE[code] : -1;
1048
332
  if (value === void 0 || value < 0) {
1049
- throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text}"`);
333
+ throw new Error(`[multicast-auth-catalog] invalid base64url character in "${text2}"`);
1050
334
  }
1051
335
  buffer = buffer << 6 | value;
1052
336
  bits += 6;
@@ -1056,20 +340,11 @@ function decodeBase64Url(text) {
1056
340
  }
1057
341
  }
1058
342
  const decoded = Uint8Array.from(bytes);
1059
- if (encodeBase64Url(decoded) !== text) {
1060
- throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text}"`);
343
+ if (encodeBase64Url(decoded) !== text2) {
344
+ throw new Error(`[multicast-auth-catalog] non-canonical base64url encoding "${text2}"`);
1061
345
  }
1062
346
  return decoded;
1063
347
  }
1064
- function decodeAuthScope(authScope) {
1065
- const bytes = decodeBase64Url(authScope);
1066
- if (bytes.byteLength !== SOURCE_AUTH_SCOPE_LENGTH2) {
1067
- throw new Error(
1068
- `[multicast-auth-catalog] authScope must decode to ${SOURCE_AUTH_SCOPE_LENGTH2} raw bytes, got ${bytes.byteLength}`
1069
- );
1070
- }
1071
- return bytes;
1072
- }
1073
348
  function decodeEd25519PublicKey(publicKey) {
1074
349
  const bytes = decodeBase64Url(publicKey);
1075
350
  if (bytes.byteLength !== RAW_ED25519_KEY_LENGTH) {
@@ -1079,188 +354,73 @@ function decodeEd25519PublicKey(publicKey) {
1079
354
  }
1080
355
  return bytes;
1081
356
  }
1082
- function isNonEmptyString(value) {
1083
- return typeof value === "string" && value.length > 0;
1084
- }
1085
- function isValidAuthScopeField(value) {
1086
- if (!isNonEmptyString(value)) return false;
1087
- try {
1088
- decodeAuthScope(value);
1089
- return true;
1090
- } catch {
1091
- return false;
1092
- }
1093
- }
1094
- function isValidPublicKeyField(value) {
1095
- if (!isNonEmptyString(value)) return false;
1096
- try {
1097
- decodeEd25519PublicKey(value);
1098
- return true;
1099
- } catch {
1100
- return false;
1101
- }
1102
- }
1103
- function hasOnlyKeys(object, allowed) {
1104
- const allowedKeys = new Set(allowed);
1105
- return Object.keys(object).every((key) => allowedKeys.has(key));
1106
- }
1107
- function isMulticastAuthTrackConfig(obj) {
1108
- if (typeof obj !== "object" || obj === null) return false;
1109
- const o = obj;
1110
- return hasOnlyKeys(o, ["mediaTrack", "manifestTrack", "authScope", "sourceSymbolFormat"]) && isNonEmptyString(o["mediaTrack"]) && isNonEmptyString(o["manifestTrack"]) && o["mediaTrack"] !== o["manifestTrack"] && isValidAuthScopeField(o["authScope"]) && isNonEmptyString(o["sourceSymbolFormat"]);
1111
- }
1112
- var VALID_COMPACTION = /* @__PURE__ */ new Set(["merkle", "none"]);
1113
- var VALID_ENFORCEMENT = /* @__PURE__ */ new Set(["shadow", "enforce"]);
1114
- function hasUniqueMulticastAuthTrackBindings(tracks) {
1115
- const bindings = tracks.flatMap((track) => {
1116
- if (typeof track !== "object" || track === null) return [];
1117
- const value = track;
1118
- if (typeof value["mediaTrack"] !== "string" || typeof value["sourceSymbolFormat"] !== "string") {
1119
- return [];
1120
- }
1121
- return [JSON.stringify([value["mediaTrack"], value["sourceSymbolFormat"]])];
1122
- });
1123
- return new Set(bindings).size === bindings.length;
1124
- }
1125
- function isMulticastAuthConfig(obj) {
1126
- if (typeof obj !== "object" || obj === null) return false;
1127
- const o = obj;
1128
- if (o["scheme"] !== "bc-provenance") return false;
1129
- if (o["hash"] !== "blake3") return false;
1130
- if (o["sig"] !== "ed25519") return false;
1131
- if (!hasOnlyKeys(o, ["scheme", "hash", "sig", "publicKey", "keyId", "previousKey", "compaction", "enforcement", "tracks"])) return false;
1132
- if (!isValidPublicKeyField(o["publicKey"])) return false;
1133
- if (!isNonEmptyString(o["keyId"])) return false;
1134
- if (o["previousKey"] !== void 0 && !isValidPublicKeyField(o["previousKey"])) return false;
1135
- if (o["previousKey"] === o["publicKey"]) return false;
1136
- if (typeof o["compaction"] !== "string" || !VALID_COMPACTION.has(o["compaction"])) return false;
1137
- if (o["enforcement"] !== void 0) {
1138
- if (typeof o["enforcement"] !== "string" || !VALID_ENFORCEMENT.has(o["enforcement"])) return false;
1139
- }
1140
- if (!Array.isArray(o["tracks"]) || o["tracks"].length === 0) return false;
1141
- const tracks = o["tracks"];
1142
- if (!tracks.every((t) => isMulticastAuthTrackConfig(t))) return false;
1143
- const typedTracks = tracks;
1144
- const scopes = typedTracks.map((t) => t.authScope);
1145
- if (new Set(scopes).size !== scopes.length) return false;
1146
- if (!hasUniqueMulticastAuthTrackBindings(typedTracks)) return false;
1147
- const manifestTracks = typedTracks.map((t) => t.manifestTrack);
1148
- if (new Set(manifestTracks).size !== manifestTracks.length) return false;
1149
- return true;
1150
- }
1151
- function resolveMulticastAuthMode(playerMode, auth) {
1152
- if (playerMode !== void 0) return playerMode;
1153
- if (auth === void 0) return "off";
1154
- return auth.enforcement ?? "shadow";
1155
- }
1156
- function resolveMulticastAuthCatalog(catalog, playerMode) {
357
+ function resolveMulticastAuthCatalog(catalog, options = {}) {
1157
358
  if (typeof catalog !== "object" || catalog === null || Array.isArray(catalog)) {
1158
359
  throw new Error("[multicast-auth-catalog] catalog must be an object");
1159
360
  }
1160
- const root = catalog;
1161
- const rawAuth = root["multicast.auth"];
1162
- if (rawAuth === void 0) {
1163
- if (playerMode === "enforce") {
1164
- throw new Error("[multicast-auth-catalog] player enforce mode requires multicast.auth");
361
+ const issues = multicastCatalogIssues(catalog, options);
362
+ const fatal = issues.find((issue) => issue.endpointIndex === void 0);
363
+ if (fatal) throw new Error(`[multicast-auth-catalog] ${fatal.path}: ${fatal.message}`);
364
+ const multicast = catalog["multicast"];
365
+ const auth = multicast?.["auth"];
366
+ if (auth === void 0) {
367
+ if (options.requireAuth) {
368
+ throw new Error("[multicast-auth-catalog] authentication is pinned but the catalog declares no multicast.auth");
1165
369
  }
1166
370
  return void 0;
1167
371
  }
1168
- if (!isMulticastAuthConfig(rawAuth)) {
1169
- throw new Error("[multicast-auth-catalog] invalid multicast.auth v2 block");
1170
- }
1171
- const rawTracks = root["tracks"];
1172
- if (!Array.isArray(rawTracks)) {
1173
- throw new Error("[multicast-auth-catalog] catalog tracks must be an array");
1174
- }
1175
- const catalogTrackNames = new Set(
1176
- rawTracks.flatMap(
1177
- (track) => typeof track === "object" && track !== null && typeof track["name"] === "string" ? [track["name"]] : []
1178
- )
1179
- );
1180
- for (const track of rawAuth.tracks) {
1181
- if (!catalogTrackNames.has(track.mediaTrack)) {
1182
- throw new Error(`[multicast-auth-catalog] unknown mediaTrack "${track.mediaTrack}"`);
1183
- }
1184
- if (!catalogTrackNames.has(track.manifestTrack)) {
1185
- throw new Error(`[multicast-auth-catalog] unknown manifestTrack "${track.manifestTrack}"`);
1186
- }
1187
- }
372
+ const ignored = new Set(issues.map((issue) => issue.endpointIndex));
373
+ const endpoints = multicast["endpoints"] ?? [];
374
+ const flows = [];
375
+ endpoints.forEach((endpoint, endpointIndex) => {
376
+ if (ignored.has(endpointIndex)) return;
377
+ const flowAuth = endpoint["auth"];
378
+ flows.push({
379
+ endpointIndex,
380
+ source: endpoint["sourceAddress"] ?? flowAuth.senderAddress,
381
+ groupAddress: endpoint["groupAddress"],
382
+ port: endpoint["port"],
383
+ bandwidth: endpoint["bandwidth"],
384
+ manifestPort: flowAuth.manifestPort,
385
+ streamId: flowAuth.streamId,
386
+ maxAuthDelayMs: flowAuth.maxAuthDelayMs ?? DEFAULT_MAX_AUTH_DELAY_MS,
387
+ manifestTimerMs: flowAuth.manifestTimerMs ?? DEFAULT_MANIFEST_TIMER_MS,
388
+ ...flowAuth.manifestTrack === void 0 ? {} : { manifestTrack: flowAuth.manifestTrack },
389
+ tracks: (endpoint["tracks"] ?? []).map(({ name, packetId }) => ({
390
+ name,
391
+ packetId
392
+ }))
393
+ });
394
+ });
1188
395
  return {
1189
- keyId: rawAuth.keyId,
1190
- acceptedPublicKeys: [
1191
- decodeEd25519PublicKey(rawAuth.publicKey),
1192
- ...rawAuth.previousKey === void 0 ? [] : [decodeEd25519PublicKey(rawAuth.previousKey)]
1193
- ],
1194
- mode: resolveMulticastAuthMode(playerMode, rawAuth),
1195
- compaction: rawAuth.compaction,
1196
- tracks: rawAuth.tracks.map((track) => ({
1197
- ...track,
1198
- authScope: decodeAuthScope(track.authScope)
1199
- }))
396
+ keys: auth.keys.map((key) => ({ kid: key.kid, publicKey: decodeEd25519PublicKey(key.publicKey), firstEpoch: key.firstEpoch })).sort((a, b) => a.firstEpoch - b.firstEpoch),
397
+ minEpoch: auth.minEpoch,
398
+ flows
1200
399
  };
1201
400
  }
401
+ function multicastAuthKeyFor(resolved, kid, epoch) {
402
+ return manifestKeyFor(resolved.keys, epoch, kid);
403
+ }
1202
404
 
1203
405
  // src/manifest-auth-plan.ts
1204
- function createManifestAuthPlan(catalog, options) {
1205
- const resolved = resolveMulticastAuthCatalog(catalog, options.playerMode);
1206
- if (!resolved || resolved.mode === "off") return void 0;
1207
- const verifier = new ManifestVerifier({
1208
- manifestAuth: {
1209
- mode: resolved.mode,
1210
- onMissingManifest: options.onMissingManifest ?? (resolved.mode === "enforce" ? "stall" : "fallback-shadow")
1211
- },
1212
- verifySignature: options.verifySignature,
1213
- ...options.onFailure === void 0 ? {} : { onFailure: options.onFailure }
1214
- });
406
+ function createManifestAuthPlan(catalog, options = {}) {
407
+ const resolved = resolveMulticastAuthCatalog(catalog, options);
408
+ if (!resolved) return void 0;
1215
409
  const byManifestTrack = /* @__PURE__ */ new Map();
1216
- const bindings = resolved.tracks.map((binding) => {
1217
- const bindingId = manifestBindingId(binding.mediaTrack, binding.sourceSymbolFormat);
1218
- const planned = {
1219
- bindingId,
1220
- mediaTrack: binding.mediaTrack,
1221
- manifestTrack: binding.manifestTrack,
1222
- sourceSymbolFormat: binding.sourceSymbolFormat
1223
- };
1224
- verifier.registerTrack({
1225
- ...options.contextFor(binding, resolved),
1226
- bindingId,
1227
- trackName: binding.mediaTrack,
1228
- sourceSymbolFormat: binding.sourceSymbolFormat,
1229
- authScope: binding.authScope,
1230
- publicKey: resolved.acceptedPublicKeys[0],
1231
- acceptedPublicKeys: resolved.acceptedPublicKeys
1232
- });
1233
- byManifestTrack.set(binding.manifestTrack, planned);
1234
- return planned;
1235
- });
1236
- let disposed = false;
410
+ for (const flow of resolved.flows) {
411
+ if (flow.manifestTrack !== void 0) byManifestTrack.set(flow.manifestTrack, flow);
412
+ }
1237
413
  return {
1238
- verifier,
1239
- mode: resolved.mode,
1240
- bindings,
414
+ keys: resolved.keys,
415
+ minEpoch: resolved.minEpoch,
416
+ flows: resolved.flows,
1241
417
  manifestTracks: [...byManifestTrack.keys()],
1242
- bindingIdFor(mediaTrack, sourceSymbolFormat) {
1243
- const bindingId = manifestBindingId(mediaTrack, sourceSymbolFormat);
1244
- return bindings.some((binding) => binding.bindingId === bindingId) ? bindingId : void 0;
1245
- },
1246
- ingestManifestPayload(manifestTrack, payload) {
1247
- const binding = byManifestTrack.get(manifestTrack);
1248
- if (!binding) throw new Error(`unknown manifest subscription track ${manifestTrack}`);
1249
- verifier.ingestManifestFrame(binding.bindingId, payload);
1250
- },
1251
- dispose() {
1252
- if (disposed) return;
1253
- disposed = true;
1254
- verifier.dispose();
1255
- }
418
+ keyFor: (kid, epoch) => multicastAuthKeyFor(resolved, kid, epoch),
419
+ flowForManifestPort: (source, groupAddress, manifestPort) => resolved.flows.find((flow) => flow.source === source && flow.groupAddress === groupAddress && flow.manifestPort === manifestPort),
420
+ flowForManifestTrack: (manifestTrack) => byManifestTrack.get(manifestTrack)
1256
421
  };
1257
422
  }
1258
423
  export {
1259
424
  createManifestAuthPlan
1260
425
  };
1261
- /*! Bundled license information:
1262
-
1263
- @noble/hashes/esm/utils.js:
1264
- (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
1265
- */
1266
426
  //# sourceMappingURL=manifest-auth-plan.js.map