@blockcast/mmt-transport 2.1.0 → 2.2.0-main.73af0eedcbc8

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.
@@ -0,0 +1,285 @@
1
+ /**
2
+ * The browser's own `MulticastReceiver` (Chromium and Firefox, branch
3
+ * `mcast-hackathon`) behind the `window.multicast` gateway surface.
4
+ *
5
+ * The user agent verifies the in-band bc-provenance v2 (`MHM2`) records
6
+ * itself and delivers only verified data, so the records never reach the
7
+ * page. A datagram from this provider is therefore already admitted: the
8
+ * consumer marks its ingress with {@link userAgentVerifiedIngress} and the
9
+ * MMTP router in `@blockcast/mmt-container` reads it as admitted.
10
+ *
11
+ * libmmt bundles this file into several copies that one document loads (each
12
+ * container `dist` entry inlines it, beside transport's own `dist` and its
13
+ * no-modules IIFE). The provider identity therefore lives in one realm-wide
14
+ * slot keyed by `Symbol.for`, installed by whichever copy runs first, so every
15
+ * copy sees one provider, and one open gate, per scope.
16
+ */
17
+
18
+ import { readMMTPPacketId } from "@blockcast/mmt-base";
19
+ import type {
20
+ WindowMulticastGateway,
21
+ WindowMulticastSubscribeConfig,
22
+ WindowMulticastSubscription,
23
+ WindowMulticastSubscriptionState,
24
+ } from "./types.js";
25
+
26
+ // `/v1` is the provider contract's version: a copy with a changed contract
27
+ // takes a new key, so it never shares another version's provider.
28
+ // ponytail: one version per page in the player origin (all its bundles come
29
+ // from pim's one libmmt gitlink); a version handshake only if mixed versions
30
+ // ever share a page.
31
+ const REGISTRY = Symbol.for("@blockcast/mmt-transport/native-provider-registry/v1");
32
+
33
+ /**
34
+ * The mark an ingress carries in `admittedBy` when its datagram came from the
35
+ * user agent's own `MulticastReceiver`. A symbol, so no structured-cloned or
36
+ * serialised data can carry it.
37
+ */
38
+ export const USER_AGENT_VERIFIED: unique symbol = Symbol.for(
39
+ "@blockcast/mmt-transport/user-agent-verified/v1",
40
+ ) as never;
41
+
42
+ /** The one integrity scheme this provider vouches for. */
43
+ const INTEGRITY_SCHEME = "manifest-ed25519-2";
44
+
45
+ /** A multicast-contract error: `code` names the outcome, `cause` the DOMException. */
46
+ export class MulticastError extends Error {
47
+ readonly code: "capability-unsupported" | "subscription-failed" | "origin-not-trusted";
48
+ constructor(code: MulticastError["code"], message: string, cause?: unknown) {
49
+ super(message, cause === undefined ? undefined : { cause });
50
+ this.name = "MulticastError";
51
+ this.code = code;
52
+ }
53
+ }
54
+
55
+ // ponytail: the chunk and close-reason shapes are read tolerantly (array or
56
+ // `{datagrams}`, `Uint8Array` or `{data}`, string or `{reason}`); pin them to
57
+ // the prototype IDL once it is published.
58
+ function datagramsOf(chunk: unknown): Uint8Array[] {
59
+ const list = Array.isArray(chunk) ? chunk : (chunk as { datagrams?: unknown[] } | null)?.datagrams ?? [];
60
+ const out: Uint8Array[] = [];
61
+ for (const d of list) {
62
+ const data = d instanceof Uint8Array || d instanceof ArrayBuffer ? d : (d as { data?: unknown } | null)?.data;
63
+ if (data instanceof Uint8Array) out.push(data);
64
+ else if (data instanceof ArrayBuffer) out.push(new Uint8Array(data));
65
+ }
66
+ return out;
67
+ }
68
+
69
+ function reasonOf(value: unknown): unknown {
70
+ return typeof value === "object" && value !== null && "reason" in value ? (value as { reason: unknown }).reason : value;
71
+ }
72
+
73
+ interface Receiver {
74
+ readonly opened: Promise<{ readonly readable: ReadableStream<unknown> }>;
75
+ readonly closed: Promise<unknown>;
76
+ readonly integrityScheme?: string;
77
+ close(): Promise<void> | void;
78
+ }
79
+
80
+ type ReceiverConstructor = new (options: {
81
+ sourceAddress: string;
82
+ groupAddress: string;
83
+ localPort: number;
84
+ }) => Receiver;
85
+
86
+ interface NativeProviderRegistry {
87
+ isProvider(gateway: unknown): boolean;
88
+ providerFor(scope: object): WindowMulticastGateway;
89
+ }
90
+
91
+ function registry(): NativeProviderRegistry {
92
+ const g = globalThis as unknown as Record<symbol, NativeProviderRegistry | undefined>;
93
+ if (g[REGISTRY] === undefined) {
94
+ const providers = new WeakSet<object>(); // closure-private: no add() is ever exposed
95
+ const byScope = new WeakMap<object, WindowMulticastGateway>();
96
+ Object.defineProperty(g, REGISTRY, {
97
+ value: Object.freeze({
98
+ isProvider: (x: unknown) => typeof x === "object" && x !== null && providers.has(x),
99
+ providerFor: (scope: object) => {
100
+ let provider = byScope.get(scope);
101
+ if (provider === undefined) {
102
+ provider = createProvider(scope);
103
+ providers.add(provider);
104
+ byScope.set(scope, provider);
105
+ }
106
+ return provider;
107
+ },
108
+ }),
109
+ writable: false,
110
+ configurable: false,
111
+ enumerable: false,
112
+ });
113
+ }
114
+ return g[REGISTRY]!;
115
+ }
116
+
117
+ /**
118
+ * The multicast gateway for `scope`: the user agent's `MulticastReceiver`
119
+ * when it exists (one provider per scope for the realm), else
120
+ * `scope.multicast`, else undefined.
121
+ */
122
+ export function resolveMulticastGateway(scope: object = globalThis): WindowMulticastGateway | undefined {
123
+ const s = scope as { MulticastReceiver?: unknown; multicast?: WindowMulticastGateway };
124
+ if (typeof s.MulticastReceiver === "function") return registry().providerFor(scope);
125
+ if (typeof s.multicast?.subscribe === "function") return s.multicast;
126
+ return undefined;
127
+ }
128
+
129
+ /** Whether `gateway` is a native `MulticastReceiver` provider of this realm. */
130
+ export function isUserAgentVerifiedGateway(gateway: unknown): boolean {
131
+ return registry().isProvider(gateway);
132
+ }
133
+
134
+ /**
135
+ * `ingress` marked as admitted by the user agent, when `gateway` is a native
136
+ * provider; otherwise `ingress` without an `admittedBy` field (itself when it
137
+ * has none). Never copies a mark from anywhere: this is its only source.
138
+ */
139
+ export function userAgentVerifiedIngress<T extends object>(ingress: T, gateway: unknown): T {
140
+ if (isUserAgentVerifiedGateway(gateway)) return { ...ingress, admittedBy: USER_AGENT_VERIFIED };
141
+ if (!("admittedBy" in ingress)) return ingress;
142
+ const { admittedBy: _, ...rest } = ingress as T & { admittedBy?: unknown };
143
+ return rest as T;
144
+ }
145
+
146
+ function unsupported(message: string, cause?: unknown): MulticastError {
147
+ return new MulticastError("capability-unsupported", message, cause);
148
+ }
149
+
150
+ function createProvider(scope: object): WindowMulticastGateway {
151
+ // Captured once: a later reassignment never reaches this provider.
152
+ const Receiver = (scope as { MulticastReceiver: ReceiverConstructor }).MulticastReceiver;
153
+ // The first construction runs alone: Gecko consumes transient activation
154
+ // on every open, and after the first grant neither browser needs it.
155
+ let gate: Promise<unknown> | null = null;
156
+ return {
157
+ capabilities: () => Promise.resolve({ consumeModes: ["bytes"] }),
158
+ subscribe: async (config: WindowMulticastSubscribeConfig) => {
159
+ const c = config as WindowMulticastSubscribeConfig & {
160
+ relay?: string;
161
+ discovery?: string;
162
+ senderAddress?: string;
163
+ };
164
+ if (c.consume !== "bytes") throw unsupported(`consume mode ${String(c.consume)} is not supported`);
165
+ const origin = c.origin ?? "ip-multicast";
166
+ if (origin !== "ip-multicast" && !(origin === "amt" && c.discovery === "driad")) {
167
+ throw unsupported(`origin ${String(origin)} is not supported by MulticastReceiver`);
168
+ }
169
+ if (c.relay !== undefined) throw unsupported("MulticastReceiver picks its own AMT relay");
170
+ if (!c.source) throw unsupported("MulticastReceiver needs an SSM source");
171
+ if (c.senderAddress !== undefined && c.senderAddress !== c.source) {
172
+ throw unsupported("MulticastReceiver filters by source only");
173
+ }
174
+ const options = { sourceAddress: c.source, groupAddress: c.group, localPort: c.port };
175
+ if (gate !== null) await gate;
176
+ let rx: Receiver;
177
+ try {
178
+ rx = new Receiver(options);
179
+ } catch (error) {
180
+ throw unsupported("MulticastReceiver refused the request", error);
181
+ }
182
+ const opened = rx.opened;
183
+ if (gate === null) gate = opened.then(() => undefined, () => undefined);
184
+ return openSubscription(rx, opened, options, c.packetIds);
185
+ },
186
+ };
187
+ }
188
+
189
+ async function openSubscription(
190
+ rx: Receiver,
191
+ openedPromise: Receiver["opened"],
192
+ options: { sourceAddress: string; groupAddress: string; localPort: number },
193
+ packetIds: readonly number[] | undefined,
194
+ ): Promise<WindowMulticastSubscription> {
195
+ let opened: Awaited<Receiver["opened"]>;
196
+ try {
197
+ opened = await openedPromise;
198
+ } catch (error) {
199
+ throw new MulticastError("subscription-failed", "MulticastReceiver did not open", error);
200
+ }
201
+ if (rx.integrityScheme !== INTEGRITY_SCHEME) {
202
+ await rx.close();
203
+ throw unsupported(`integrity scheme ${String(rx.integrityScheme)} is not ${INTEGRITY_SCHEME}`);
204
+ }
205
+ const events = new EventTarget();
206
+ let state: WindowMulticastSubscriptionState = "connected";
207
+ let filter = packetIds?.length ? new Set(packetIds) : null;
208
+ let closing = false;
209
+ const setState = (next: WindowMulticastSubscriptionState) => {
210
+ if (state === next) return;
211
+ state = next;
212
+ events.dispatchEvent(new CustomEvent("state", { detail: next }));
213
+ };
214
+ const sourceAddress = options.sourceAddress;
215
+ const subscription = {
216
+ id: `${options.sourceAddress}|${options.groupAddress}|${options.localPort}`,
217
+ get state() {
218
+ return state;
219
+ },
220
+ delivery: "datagram" as const,
221
+ eventTypes: Object.freeze(["bytes", "packets", "state", "error"]),
222
+ setPacketIds(ids: readonly number[]) {
223
+ filter = ids.length ? new Set(ids) : null;
224
+ },
225
+ addEventListener: events.addEventListener.bind(events),
226
+ removeEventListener: events.removeEventListener.bind(events),
227
+ async unsubscribe() {
228
+ closing = true;
229
+ await rx.close();
230
+ setState("closed");
231
+ },
232
+ } as unknown as WindowMulticastSubscription;
233
+
234
+ void (async () => {
235
+ const reader = opened.readable.getReader();
236
+ try {
237
+ for (;;) {
238
+ const { value, done } = await reader.read();
239
+ if (done) break;
240
+ const packets: ArrayBuffer[] = [];
241
+ for (const data of datagramsOf(value)) {
242
+ if (filter !== null) {
243
+ const id = readMMTPPacketId(data);
244
+ if (id === null || !filter.has(id)) continue;
245
+ }
246
+ // A chunk's datagrams are views into one ArrayBuffer.
247
+ // ponytail: one copy per datagram; zero-copy only if a profile shows it.
248
+ const copy = data.slice().buffer as ArrayBuffer;
249
+ packets.push(copy);
250
+ events.dispatchEvent(Object.assign(new CustomEvent("bytes", { detail: copy }), { sourceAddress }));
251
+ }
252
+ if (packets.length > 0) events.dispatchEvent(new CustomEvent("packets", { detail: packets }));
253
+ }
254
+ } catch {
255
+ // The receiver closed; `closed` reports why.
256
+ }
257
+ })();
258
+
259
+ void rx.closed.then(
260
+ (value) => {
261
+ const reason = reasonOf(value);
262
+ if (!closing) {
263
+ if (reason === "consent-withdrawn") {
264
+ events.dispatchEvent(new CustomEvent("error", {
265
+ detail: new MulticastError("origin-not-trusted", "multicast consent withdrawn"),
266
+ }));
267
+ } else if (reason === "oversubscribed" || reason === "network") {
268
+ events.dispatchEvent(new CustomEvent("error", {
269
+ detail: new MulticastError("subscription-failed", `MulticastReceiver closed: ${reason}`),
270
+ }));
271
+ }
272
+ }
273
+ setState("closed");
274
+ },
275
+ (error) => {
276
+ if (!closing) {
277
+ events.dispatchEvent(new CustomEvent("error", {
278
+ detail: new MulticastError("subscription-failed", "MulticastReceiver failed", error),
279
+ }));
280
+ }
281
+ setState("closed");
282
+ },
283
+ );
284
+ return subscription;
285
+ }
package/src/no-modules.ts CHANGED
@@ -33,6 +33,13 @@ import {
33
33
  createMulticastSignalingReconciler,
34
34
  normalizeCatalogEndpoints,
35
35
  } from "./multicast-signaling-reconciler.js";
36
+ import {
37
+ isUserAgentVerifiedGateway,
38
+ MulticastError,
39
+ resolveMulticastGateway,
40
+ USER_AGENT_VERIFIED,
41
+ userAgentVerifiedIngress,
42
+ } from "./multicast-receiver-gateway.js";
36
43
  import { MulticastSubscriptionPool } from "./multicast-subscription-pool.js";
37
44
  import { endpointKey, selectMulticastTier } from "./multicast-tier.js";
38
45
  import {
@@ -58,6 +65,8 @@ const api = {
58
65
  hasUnicastMediaRenditions,
59
66
  isRecoverableMulticastSignalReadError,
60
67
  isMulticastOnlyCatalog,
68
+ isUserAgentVerifiedGateway,
69
+ MulticastError,
61
70
  MulticastOrchestrator,
62
71
  MulticastSubscriptionPool,
63
72
  MOQT_PUBLISHER_PRIORITY,
@@ -78,6 +87,7 @@ const api = {
78
87
  normalizeMulticastEndpoint,
79
88
  readPlayerMulticastConfig,
80
89
  readUrlMulticastConfig,
90
+ resolveMulticastGateway,
81
91
  toWindowMulticastSubscribeConfig,
82
92
  requiresMulticastCapability,
83
93
  runUnicastFallback,
@@ -87,6 +97,8 @@ const api = {
87
97
  selectMulticastTier,
88
98
  selectRepairEndpointsForTracks,
89
99
  urlOverrideBlocksMulticastCandidate,
100
+ USER_AGENT_VERIFIED,
101
+ userAgentVerifiedIngress,
90
102
  withCatalogNamespace,
91
103
  withMulticastEndpoints,
92
104
  wireStarvationDetector,