@moq/net 0.4.4 → 0.4.5
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.
- package/connection/connect.d.ts.map +1 -1
- package/connection/connect.js +7 -3
- package/connection/connect.js.map +1 -1
- package/package.json +1 -1
- package/path.d.ts.map +1 -1
- package/path.js +6 -2
- package/path.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../../src/connection/connect.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,QAAQ,IAAI,cAAc,EAAE,QAAQ,IAAI,cAAc,EAAE,MAAM,cAAc,CAAC;AAE3F,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AAInC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAWpD,yGAAyG;AACzG,MAAM,WAAW,cAAc;IAC9B,yDAAyD;IACzD,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB,mGAAmG;IACnG,GAAG,CAAC,EAAE,GAAG,CAAC;IAEV;;;OAGG;IACH,KAAK,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC;CACnB;AAED;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC/B,4EAA4E;IAC5E,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,uDAAuD;IACvD,KAAK,EAAE,YAAY,GAAG,MAAM,CAAC;CAC7B;AAED,2GAA2G;AAC3G,MAAM,WAAW,iBAAkB,SAAQ,IAAI,CAAC,mBAAmB,EAAE,yBAAyB,CAAC;IAC9F;;;OAGG;IACH,uBAAuB,CAAC,EAAE,eAAe,EAAE,CAAC;IAE5C;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,GAAG,YAAY,CAAC;CAC1C;AAED,mCAAmC;AACnC,MAAM,WAAW,YAAY;IAC5B,qBAAqB;IACrB,GAAG,EAAE,GAAG,CAAC;IAET,4BAA4B;IAC5B,YAAY,CAAC,E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AC,EAAE,eAAe,EAAE,CAAC;IAE5C;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,GAAG,YAAY,CAAC;CAC1C;AAED,mCAAmC;AACnC,MAAM,WAAW,YAAY;IAC5B,qBAAqB;IACrB,GAAG,EAAE,GAAG,CAAC;IAET,4BAA4B;IAC5B,YAAY,CAAC,EAAE,iBAAiB,CAAC;IAEjC,oCAAoC;IACpC,SAAS,CAAC,EAAE,cAAc,CAAC;IAE3B;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,YAAY,CAAC;IAEzB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,cAAc,CAAC;IAEzB;;;;;;;;;OASG;IACH,OAAO,CAAC,EAAE,cAAc,CAAC;IAEzB;;;;OAIG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAcD;;;;;;GAMG;AACH,wBAAsB,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,KAAK,EAAE,EAAE,YAAY,GAAG,OAAO,CAAC,WAAW,CAAC,CAwBnF;AAiPD;;;;GAIG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,GAAG,OAAO,CAAC,UAAU,CAAC,WAAW,CAAC,CAAC,CAInG"}
|
package/connection/connect.js
CHANGED
|
@@ -250,11 +250,15 @@ async function handshakeAlpn(url, session, version, wiring) {
|
|
|
250
250
|
}
|
|
251
251
|
// Strip PEM armor and base64-decode to the raw DER bytes.
|
|
252
252
|
function pemToDer(pem) {
|
|
253
|
-
|
|
254
|
-
|
|
253
|
+
// indexOf rather than a lazy regex, which goes quadratic on repeated BEGIN lines without an END.
|
|
254
|
+
const begin = "-----BEGIN CERTIFICATE-----";
|
|
255
|
+
const start = pem.indexOf(begin);
|
|
256
|
+
const end = start < 0 ? -1 : pem.indexOf("-----END CERTIFICATE-----", start + begin.length);
|
|
257
|
+
const body = end < 0 ? "" : pem.slice(start + begin.length, end).replace(/\s+/g, "");
|
|
258
|
+
if (!body) {
|
|
255
259
|
throw new Error("invalid PEM certificate: missing -----BEGIN/END CERTIFICATE----- armor");
|
|
256
260
|
}
|
|
257
|
-
const binary = atob(
|
|
261
|
+
const binary = atob(body);
|
|
258
262
|
const der = new Uint8Array(binary.length);
|
|
259
263
|
for (let i = 0; i < binary.length; i++) {
|
|
260
264
|
der[i] = binary.charCodeAt(i);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"connect.js","sourceRoot":"","sources":["../../src/connection/connect.ts"],"names":[],"mappings":"AAAA,OAAO,OAAwC,MAAM,WAAW,CAAC;AACjE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AAEzC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AACnC,OAAO,KAAK,GAAG,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE/C,gFAAgF;AAChF,MAAM,0BAA0B,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAEnD,0FAA0F;AAC1F,gGAAgG;AAChG,MAAM,oBAAoB,GAAG,GAAG,CAAC;AA2GjC,qFAAqF;AACrF,MAAM,YAAY,GAAG,IAAI,GAAG,EAAU,CAAC;AAEvC,gDAAgD;AAChD,MAAM,aAAa,GAAG,IAAI,eAAe,EAAE,CAAC,MAAM,CAAC;AAEnD;;;;;;GAMG;AACH,MAAM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EAAE,IAAI;KAC4C,CAAC;IAExE,yEAAyE;IACzE,0EAA0E;IAC1E,kEAAkE;IAClE,mBAAmB;IACnB,MAAM,IAAI,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;QAC7B,SAAS,EAAE,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;QAChC,QAAQ;KACR,CAAC,CAAC;IAEH,2EAA2E;IAC3E,kFAAkF;IAClF,4EAA4E;IAC5E,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACzE,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import Session, { type Version as QmuxVersion } from \"@moq/qmux\";\nimport { error, fromClose } from \"../error.ts\";\nimport * as Ietf from \"../ietf/index.ts\";\nimport * as Lite from \"../lite/index.ts\";\nimport type { Consumer as OriginConsumer, Producer as OriginProducer } from \"../origin.ts\";\nimport { Stream } from \"../stream.ts\";\nimport * as Time from \"../time.ts\";\nimport * as Hex from \"../util/hex.ts\";\nimport { dev, redact } from \"../util/log.ts\";\nimport { isWebTransportSupported } from \"./browser.ts\";\nimport type { Established } from \"./established.ts\";\nimport { forwardAnnounced } from \"./forward.ts\";\nimport { exchangeSetup } from \"./handshake.ts\";\n\n// Default head start for WebTransport before attempting the WebSocket fallback.\nconst DEFAULT_WEBSOCKET_DELAY_MS = Time.Milli(500);\n\n// RESET_STREAM and CONNECTION_CLOSE are separate transport notifications. Give the latter\n// time to surface its authoritative code without letting a reset-only peer stall SETUP forever.\nconst SETUP_CLOSE_GRACE_MS = 100;\n\n/** Tuning for the WebSocket fallback used when WebTransport is unavailable or loses the connect race. */\nexport interface WebSocketProps {\n\t/** Enable the WebSocket fallback. Defaults to `true`. */\n\tenabled?: boolean;\n\n\t/** Use a different URL than WebTransport. By default, `https` maps to `wss` and `http` to `ws`. */\n\turl?: URL;\n\n\t/**\n\t * The delay in milliseconds before attempting the WebSocket fallback (default: 500).\n\t * If WebSocket won the previous race for a given URL, this is 0.\n\t */\n\tdelay?: Time.Milli;\n}\n\n/**\n * A server certificate hash used to pin a self-signed server, one entry of\n * `serverCertificateHashes`. Unlike the DOM type, `value` also accepts a hex string (the\n * format moq servers report via their certificate fingerprints), decoded automatically.\n */\nexport interface CertificateHash {\n\t/** The hash algorithm. Defaults to `sha-256` (the only supported value). */\n\talgorithm?: \"sha-256\";\n\t/** The certificate hash: raw bytes or a hex string. */\n\tvalue: BufferSource | string;\n}\n\n/** WebTransport options extended with friendlier certificate pinning (hex hashes or a raw certificate). */\nexport interface WebTransportProps extends Omit<WebTransportOptions, \"serverCertificateHashes\"> {\n\t/**\n\t * Pin the server to one or more certificate hashes. Each `value` may be raw\n\t * bytes or a hex string; the algorithm defaults to `sha-256`.\n\t */\n\tserverCertificateHashes?: CertificateHash[];\n\n\t/**\n\t * Pin the server by supplying its certificate directly; the SHA-256 hash is\n\t * computed for you. Accepts a PEM string or raw DER bytes. Use this when you\n\t * have the certificate but not its precomputed fingerprint.\n\t */\n\tserverCertificate?: string | BufferSource;\n}\n\n/** Options for {@link connect}. */\nexport interface ConnectProps {\n\t/** The relay URL. */\n\turl: URL;\n\n\t/** WebTransport options. */\n\twebtransport?: WebTransportProps;\n\n\t/** WebSocket (fallback) options. */\n\twebsocket?: WebSocketProps;\n\n\t/**\n\t * Use a pre-existing WebTransport session instead of connecting; skips the\n\t * WebTransport/WebSocket race. The publisher acquires the session's datagram\n\t * writer lock (`datagrams.writable.getWriter()`) for the session's lifetime,\n\t * so the caller must not hold it. Aborting via {@link ConnectProps.signal}\n\t * closes this session, so don't share one you intend to reuse afterwards.\n\t */\n\ttransport?: WebTransport;\n\n\t/**\n\t * Whether the relay supports broadcast discovery; see {@link Established.discovery}.\n\t * Defaults to true.\n\t */\n\tdiscovery?: boolean;\n\n\t/**\n\t * The origin whose broadcasts the session announces and serves to the peer. Omit to\n\t * publish nothing.\n\t *\n\t * The origin is borrowed, not owned: closing the session leaves its broadcasts alone,\n\t * and the same origin can back several sessions (or successive reconnects), each\n\t * announcing the table for as long as it lasts.\n\t */\n\tpublish?: OriginConsumer;\n\n\t/**\n\t * The origin the session feeds with the peer's announced broadcasts. Omit to discover\n\t * nothing.\n\t *\n\t * Everything the peer announces appears in the origin's table for the session's\n\t * lifetime, consumable by path; the entries retract when the session dies. Pass the\n\t * producer behind {@link ConnectProps.publish} to route both directions through one\n\t * origin: a locally published path is then served back to local consumers directly, and\n\t * the session still never announces the peer's own broadcasts back to it.\n\t */\n\tconsume?: OriginProducer;\n\n\t/**\n\t * Aborts the connection attempt with the signal's reason. An already-aborted\n\t * signal rejects before anything opens, and aborting after the connection is\n\t * established has no effect. Use `AbortSignal.timeout(ms)` for a deadline.\n\t */\n\tsignal?: AbortSignal;\n}\n\n/** The per-session wiring shared by every negotiated protocol path. */\ntype SessionProps = {\n\tdiscovery: boolean;\n\tpublish?: OriginConsumer;\n};\n\n// Save if WebSocket won the last race, so we won't give QUIC a head start next time.\nconst websocketWon = new Set<string>();\n\n/** The default connect signal: never aborts. */\nconst NEVER_ABORTED = new AbortController().signal;\n\n/**\n * Establishes a connection to a MOQ server.\n *\n * @param url - The URL of the server to connect to\n * @param props - Connection options\n * @returns A promise that resolves to an established session\n */\nexport async function connect({ url, ...props }: ConnectProps): Promise<Established> {\n\tconst signal = props.signal ?? NEVER_ABORTED;\n\tsignal.throwIfAborted();\n\n\t// Resolves on abort so every in-flight transport tears itself down.\n\tconst { promise: abort, resolve } = Promise.withResolvers<void>();\n\tconst onAbort = () => resolve();\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\n\tconst pending = connectInner(url, props, abort);\n\ttry {\n\t\t// A `pending` rejection propagates unless the abort beat it to the finish line.\n\t\tconst connection = await Promise.race([pending, abort.then(() => undefined)]);\n\t\tif (connection && !signal.aborted) {\n\t\t\tif (props.consume) forwardAnnounced(connection, props.consume);\n\t\t\treturn connection;\n\t\t}\n\n\t\t// Close a connection that settles after the abort.\n\t\tpending.then((conn) => conn.close()).catch(() => {});\n\t\tthrow signal.reason;\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\n\nasync function connectInner(url: URL, props: Omit<ConnectProps, \"url\">, abort: Promise<void>): Promise<Established> {\n\tconst wiring: SessionProps = {\n\t\tdiscovery: props.discovery ?? true,\n\t\tpublish: props.publish,\n\t};\n\n\tif (props.transport) {\n\t\tconst transport = props.transport;\n\t\tvoid abort.then(() => transport.close());\n\t\treturn connectTransport(url, transport, wiring);\n\t}\n\n\t// Stop transports after one connects or the caller aborts.\n\tconst { promise: raced, resolve: done } = Promise.withResolvers<void>();\n\tconst cancel = Promise.race([raced, abort]);\n\n\tconst webtransport = isWebTransportSupported() ? connectWebTransport(url, cancel, props.webtransport) : undefined;\n\n\t// Give QUIC a head start to connect before trying WebSocket, unless WebSocket has won in the past.\n\t// NOTE that QUIC should be faster because it involves 1/2 fewer RTTs.\n\tconst headstart =\n\t\t!webtransport || websocketWon.has(url.toString()) ? 0 : (props.websocket?.delay ?? DEFAULT_WEBSOCKET_DELAY_MS);\n\tconst websocket =\n\t\tprops.websocket?.enabled !== false\n\t\t\t? connectWebSocket(props.websocket?.url ?? url, headstart, cancel)\n\t\t\t: undefined;\n\n\tif (!websocket && !webtransport) {\n\t\tthrow new Error(\"no transport available; WebTransport not supported and WebSocket is disabled\");\n\t}\n\n\t// Race the available transports, using `.any` to ignore if one participant has an error.\n\t// `webtransport`/`websocket` are `Promise | undefined`, so test existence explicitly: a\n\t// promise is always truthy, so bare truthiness here would be a misused-promise.\n\tconst session = await Promise.any(\n\t\twebtransport !== undefined\n\t\t\t? websocket !== undefined\n\t\t\t\t? [websocket, webtransport]\n\t\t\t\t: [webtransport]\n\t\t\t: [websocket],\n\t);\n\tdone();\n\n\tif (!session) throw new Error(\"no transport available\");\n\n\t// Abort the setup handshake without leaking the selected transport.\n\tvoid abort.then(() => session.close());\n\n\t// Save if WebSocket won the last race, so we won't give QUIC a head start next time.\n\tif (session instanceof Session) {\n\t\t// Still a warning, not a debug line: losing the race means we fell back off QUIC.\n\t\tif (dev()) console.warn(redact(url), \"connected via WebSocket\");\n\t\twebsocketWon.add(url.toString());\n\t} else if (dev()) {\n\t\tconsole.debug(redact(url), \"connected via WebTransport\");\n\t}\n\n\t// The remaining setup is identical whether the transport was raced or supplied.\n\treturn await connectTransport(url, session as WebTransport, wiring);\n}\n\nasync function connectTransport(url: URL, session: WebTransport, wiring: SessionProps): Promise<Established> {\n\tconst closed = session.closed.then(fromClose, error);\n\tconst terminal = closed.then((cause) => {\n\t\tthrow cause ?? new Error(\"session closed during SETUP\");\n\t});\n\n\ttry {\n\t\treturn await Promise.race([terminal, negotiate(url, session, wiring)]);\n\t} catch (cause) {\n\t\t// A session shutdown can reject its SETUP stream before `closed` publishes the\n\t\t// peer's close code. Wait briefly without closing locally, since a local clean close\n\t\t// could overwrite that code. A reset-only peer is cleaned up after the grace period.\n\t\tconst pending = Symbol(\"session close pending\");\n\t\tconst final = await Promise.race([\n\t\t\tclosed,\n\t\t\tnew Promise<typeof pending>((resolve) => setTimeout(() => resolve(pending), SETUP_CLOSE_GRACE_MS)),\n\t\t]);\n\t\tif (final !== pending) {\n\t\t\tif (final) throw final;\n\t\t\tthrow cause;\n\t\t}\n\n\t\tsession.close();\n\t\tthrow cause;\n\t}\n}\n\n// Negotiate the MoQ protocol over an established transport. The caller races this against\n// the session closing so a close code is not lost behind a failed or stalled SETUP stream.\nasync function negotiate(url: URL, session: WebTransport, wiring: SessionProps): Promise<Established> {\n\t// The DOM lib has no `protocol` property yet. It is \"\" when none was negotiated, and\n\t// undefined in a browser that predates subprotocols (Firefox before 155).\n\tconst protocol: string | undefined = (session as { protocol?: string }).protocol || undefined;\n\tif (dev()) console.debug(redact(url), \"negotiated ALPN:\", protocol ?? \"(none)\");\n\n\t// Choose setup encoding based on negotiated WebTransport protocol (if any).\n\tlet setupVersion: Ietf.Version;\n\tconst modernVersion =\n\t\tprotocol === Ietf.ALPN.DRAFT_22\n\t\t\t? Ietf.Version.DRAFT_22\n\t\t\t: protocol === Ietf.ALPN.DRAFT_21\n\t\t\t\t? Ietf.Version.DRAFT_21\n\t\t\t\t: protocol === Ietf.ALPN.DRAFT_20\n\t\t\t\t\t? Ietf.Version.DRAFT_20\n\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_19\n\t\t\t\t\t\t? Ietf.Version.DRAFT_19\n\t\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_18\n\t\t\t\t\t\t\t? Ietf.Version.DRAFT_18\n\t\t\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_17\n\t\t\t\t\t\t\t\t? Ietf.Version.DRAFT_17\n\t\t\t\t\t\t\t\t: undefined;\n\tif (modernVersion !== undefined) {\n\t\treturn await handshakeAlpn(url, session, modernVersion, wiring);\n\t} else if (protocol === Ietf.ALPN.DRAFT_16) {\n\t\tsetupVersion = Ietf.Version.DRAFT_16;\n\t} else if (protocol === Ietf.ALPN.DRAFT_15) {\n\t\tsetupVersion = Ietf.Version.DRAFT_15;\n\t} else if (protocol === Lite.ALPN_07_WIP) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_07, ...wiring });\n\t} else if (protocol === Lite.ALPN_06) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_06, ...wiring });\n\t} else if (protocol === Lite.ALPN_05) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_05, ...wiring });\n\t} else if (protocol === Lite.ALPN_04) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_04, ...wiring });\n\t} else if (protocol === Lite.ALPN_03) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_03, ...wiring });\n\t} else if (protocol === Lite.ALPN || protocol === \"\" || protocol === undefined) {\n\t\tsetupVersion = Ietf.Version.DRAFT_14;\n\t} else {\n\t\tthrow new Error(`unsupported WebTransport protocol: ${protocol}`);\n\t}\n\n\tconst stream = await Stream.open(session, { version: setupVersion });\n\tawait stream.writer.u53(Lite.StreamId.ClientCompat);\n\n\tconst encoder = new TextEncoder();\n\n\tconst params = new Ietf.SetupOptions();\n\tparams.setVarint(Ietf.SetupOption.MaxRequestId, 42069n);\n\tparams.setBytes(Ietf.SetupOption.Implementation, encoder.encode(\"moq-lite-js\"));\n\tIetf.solicitIntoSetup(params);\n\tIetf.hiddenIntoSetup(params);\n\n\tconst client = new Ietf.ClientSetup({\n\t\tversions:\n\t\t\tsetupVersion === Ietf.Version.DRAFT_16\n\t\t\t\t? [Ietf.Version.DRAFT_16]\n\t\t\t\t: setupVersion === Ietf.Version.DRAFT_15\n\t\t\t\t\t? [Ietf.Version.DRAFT_15]\n\t\t\t\t\t: [Lite.Version.DRAFT_02, Lite.Version.DRAFT_01, Ietf.Version.DRAFT_14],\n\t\tparameters: params,\n\t});\n\tawait client.encode(stream.writer, setupVersion);\n\n\tconst serverCompat = await stream.reader.u53();\n\tif (serverCompat !== Lite.StreamId.ServerCompat) {\n\t\tthrow new Error(`unsupported server message type: ${serverCompat.toString()}`);\n\t}\n\n\tconst server = await Ietf.ServerSetup.decode(stream.reader, setupVersion);\n\n\tif (Object.values(Lite.Version).includes(server.version as Lite.Version)) {\n\t\treturn new Lite.Connection({\n\t\t\turl,\n\t\t\tquic: session,\n\t\t\tversion: server.version as Lite.Version,\n\t\t\tsession: stream,\n\t\t\t...wiring,\n\t\t});\n\t} else if (Object.values(Ietf.Version).includes(server.version as Ietf.Version)) {\n\t\tconst maxRequestId = server.parameters.getVarint(Ietf.SetupOption.MaxRequestId) ?? 0n;\n\t\treturn new Ietf.Connection({\n\t\t\t...wiring,\n\t\t\tclient: true,\n\t\t\turl,\n\t\t\tquic: session,\n\t\t\tcontrol: stream,\n\t\t\tmaxRequestId,\n\t\t\tversion: server.version as Ietf.IetfVersion,\n\t\t\tsolicit: Ietf.solicitFromSetup(server.parameters),\n\t\t\thidden: Ietf.hiddenFromSetup(server.parameters),\n\t\t});\n\t} else {\n\t\tthrow new Error(`unsupported server version: ${server.version.toString()}`);\n\t}\n}\n\n/**\n * Draft-17+ client handshake. ALPN already pinned the version; SETUP is\n * exchanged over a pair of uni streams using stream type 0x2F00.\n */\nasync function handshakeAlpn(\n\turl: URL,\n\tsession: WebTransport,\n\tversion: Ietf.IetfVersion,\n\twiring: SessionProps,\n): Promise<Established> {\n\tconst { control, early, solicit, hidden, cluster } = await exchangeSetup(session, version, \"moq-lite-js\");\n\n\treturn new Ietf.Connection({\n\t\t...wiring,\n\t\tclient: true,\n\t\turl,\n\t\tquic: session,\n\t\tcontrol,\n\t\tearly,\n\t\tsolicit,\n\t\thidden,\n\t\tcluster,\n\t\t// v17+ uses NativeSession which manages its own request IDs; maxRequestId is unused.\n\t\tmaxRequestId: 0n,\n\t\tversion,\n\t});\n}\n\n// One entry of the DOM `serverCertificateHashes`, derived without naming the lib type.\ntype WebTransportHash = NonNullable<WebTransportOptions[\"serverCertificateHashes\"]>[number];\n\n// Strip PEM armor and base64-decode to the raw DER bytes.\nfunction pemToDer(pem: string): Uint8Array<ArrayBuffer> {\n\tconst match = pem.match(/-----BEGIN CERTIFICATE-----([\\s\\S]+?)-----END CERTIFICATE-----/);\n\tif (!match) {\n\t\tthrow new Error(\"invalid PEM certificate: missing -----BEGIN/END CERTIFICATE----- armor\");\n\t}\n\n\tconst binary = atob(match[1].replace(/\\s+/g, \"\"));\n\tconst der = new Uint8Array(binary.length);\n\tfor (let i = 0; i < binary.length; i++) {\n\t\tder[i] = binary.charCodeAt(i);\n\t}\n\treturn der;\n}\n\n/**\n * Compute the SHA-256 hash of a certificate, the value `serverCertificateHashes`\n * pins. Accepts a PEM string or raw DER bytes. Matches the hex fingerprints a moq\n * server reports, so `Hex.fromBytes(await certificateHash(pem))` round-trips.\n */\nexport async function certificateHash(cert: string | BufferSource): Promise<Uint8Array<ArrayBuffer>> {\n\tconst der = typeof cert === \"string\" ? pemToDer(cert) : cert;\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", der);\n\treturn new Uint8Array(digest);\n}\n\n// Normalize our friendlier pinning options into the DOM `serverCertificateHashes`.\nasync function resolveCertificateHashes(options?: WebTransportProps): Promise<WebTransportHash[] | undefined> {\n\tconst hashes: WebTransportHash[] = [];\n\n\tfor (const hash of options?.serverCertificateHashes ?? []) {\n\t\tconst value = typeof hash.value === \"string\" ? Hex.toBytes(hash.value) : hash.value;\n\t\thashes.push({ algorithm: hash.algorithm ?? \"sha-256\", value });\n\t}\n\n\tif (options?.serverCertificate !== undefined) {\n\t\thashes.push({ algorithm: \"sha-256\", value: await certificateHash(options.serverCertificate) });\n\t}\n\n\treturn hashes.length > 0 ? hashes : undefined;\n}\n\nasync function connectWebTransport(\n\turl: URL,\n\tcancel: Promise<void>,\n\toptions?: WebTransportProps,\n): Promise<WebTransport | undefined> {\n\tlet finalUrl = url;\n\n\t// Our custom pinning fields are normalized separately; the rest are DOM options.\n\tconst { serverCertificate: _cert, serverCertificateHashes: _hashes, ...webtransport } = options ?? {};\n\n\tconst finalOptions: WebTransportOptions = {\n\t\tallowPooling: false,\n\t\tcongestionControl: \"low-latency\",\n\t\tprotocols: [\n\t\t\t// Lite.ALPN_07_WIP is intentionally omitted: lite-07 is work-in-progress and\n\t\t\t// not advertised by default (negotiate still accepts it if a server selects it).\n\t\t\tLite.ALPN_06,\n\t\t\tLite.ALPN_05,\n\t\t\tLite.ALPN_04,\n\t\t\tLite.ALPN_03,\n\t\t\tLite.ALPN,\n\t\t\tIetf.ALPN.DRAFT_22,\n\t\t\tIetf.ALPN.DRAFT_21,\n\t\t\tIetf.ALPN.DRAFT_20,\n\t\t\tIetf.ALPN.DRAFT_19,\n\t\t\tIetf.ALPN.DRAFT_18,\n\t\t\tIetf.ALPN.DRAFT_17,\n\t\t\tIetf.ALPN.DRAFT_16,\n\t\t\tIetf.ALPN.DRAFT_15,\n\t\t],\n\t\t...webtransport,\n\t};\n\n\t// Accumulate caller-provided pins first, then append anything we fetch below,\n\t// so a fetched fingerprint never clobbers hashes passed in via options.\n\tconst hashes = (await resolveCertificateHashes(options)) ?? [];\n\n\t// Only perform certificate fetch and URL rewrite when polyfill is not needed\n\t// This is needed because WebTransport is a butt to work with in local development.\n\tif (url.protocol === \"http:\") {\n\t\tconst fingerprintUrl = new URL(url);\n\t\tfingerprintUrl.pathname = \"/certificate.sha256\";\n\t\t// The certificate endpoint is unauthenticated, so don't hand it the token.\n\t\tfingerprintUrl.search = \"\";\n\n\t\t// Dev-only path: http:// can't be a real WebTransport origin, so we fetch the\n\t\t// self-signed cert's hash over plain HTTP and pin it. Production uses https://\n\t\t// and never reaches here. Keep this at debug so it doesn't read as a problem.\n\t\tif (dev()) {\n\t\t\tconsole.debug(\n\t\t\t\tredact(fingerprintUrl),\n\t\t\t\t\"performing an insecure fingerprint fetch; use https:// in production\",\n\t\t\t);\n\t\t}\n\n\t\t// Fetch the fingerprint from the server.\n\t\t// TODO cancel the request if the effect is cancelled.\n\t\tconst fingerprint = await Promise.race([fetch(fingerprintUrl), cancel]);\n\t\tif (!fingerprint) return undefined;\n\n\t\tconst fingerprintText = await Promise.race([fingerprint.text(), cancel]);\n\t\tif (fingerprintText === undefined) return undefined;\n\n\t\thashes.push({ algorithm: \"sha-256\", value: Hex.toBytes(fingerprintText) });\n\n\t\tfinalUrl = new URL(url);\n\t\tfinalUrl.protocol = \"https:\";\n\t}\n\n\tif (hashes.length > 0) {\n\t\tfinalOptions.serverCertificateHashes = hashes;\n\t}\n\n\tconst quic = new WebTransport(finalUrl, finalOptions);\n\n\t// Both .ready and .closed reject on failure; catch .closed to avoid an unhandled rejection.\n\tquic.closed.catch(() => {});\n\n\t// Wait for the WebTransport to connect, or for the cancel promise to resolve.\n\t// Close the connection if we lost the race.\n\tconst loaded = await Promise.race([quic.ready.then(() => true), cancel]);\n\tif (!loaded) {\n\t\tquic.close();\n\t\treturn undefined;\n\t}\n\n\treturn quic;\n}\n\n// TODO accept arguments to control the port/path used.\nasync function connectWebSocket(url: URL, delay: number, cancel: Promise<void>): Promise<Session | undefined> {\n\tconst timer = new Promise<void>((resolve) => setTimeout(resolve, delay));\n\n\tconst active = await Promise.race([cancel, timer.then(() => true)]);\n\tif (!active) return undefined;\n\n\t// moq-transport-18 and newer are pinned to qmux-01. Every other ALPN we\n\t// support is currently negotiated as `qmux-00.{alpn}` on the wire, but we\n\t// don't want to lock that in: set the value to `null` so the polyfill\n\t// advertises every QMux draft it knows about and the server picks one.\n\t// Insertion order is the negotiation preference on the wire.\n\tconst versions = {\n\t\t// Lite.ALPN_07_WIP omitted on purpose: lite-07 is work-in-progress, not advertised by default.\n\t\t[Lite.ALPN_06]: null,\n\t\t[Lite.ALPN_05]: null,\n\t\t[Lite.ALPN_04]: null,\n\t\t[Lite.ALPN_03]: null,\n\t\t[Lite.ALPN]: null,\n\t\t[Ietf.ALPN.DRAFT_22]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_21]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_20]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_19]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_18]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_17]: null,\n\t\t[Ietf.ALPN.DRAFT_16]: null,\n\t\t[Ietf.ALPN.DRAFT_15]: null,\n\t} as const satisfies Record<string, QmuxVersion | QmuxVersion[] | null>;\n\n\t// The default (`requireProtocol: false`) also advertises bare `qmux-01`,\n\t// `qmux-00`, and `webtransport` so we still interop with relays that only\n\t// know a wire-format version (today's moq-relay only accepts bare\n\t// `webtransport`).\n\tconst quic = new Session(url, {\n\t\tprotocols: Object.keys(versions),\n\t\tversions,\n\t});\n\n\t// Wait for the WebSocket to connect, or for the cancel promise to resolve.\n\t// `ready` rejects on a refused/failed connection, so a throw here is the caller's\n\t// cue to retry; a lost cancel race instead resolves and we close the loser.\n\tconst loaded = await Promise.race([quic.ready.then(() => true), cancel]);\n\tif (!loaded) {\n\t\tquic.close();\n\t\treturn undefined;\n\t}\n\n\treturn quic;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"connect.js","sourceRoot":"","sources":["../../src/connection/connect.ts"],"names":[],"mappings":"AAAA,OAAO,OAAwC,MAAM,WAAW,CAAC;AACjE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AAEzC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,KAAK,IAAI,MAAM,YAAY,CAAC;AACnC,OAAO,KAAK,GAAG,MAAM,gBAAgB,CAAC;AACtC,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,uBAAuB,EAAE,MAAM,cAAc,CAAC;AAEvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE/C,gFAAgF;AAChF,MAAM,0BAA0B,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAEnD,0FAA0F;AAC1F,gGAAgG;AAChG,MAAM,oBAAoB,GAAG,GAAG,CAAC;AA2GjC,qFAAqF;AACrF,MAAM,YAAY,GAAG,IAAI,GAAG,EAAU,CAAC;AAEvC,gDAAgD;AAChD,MAAM,aAAa,GAAG,IAAI,eAAe,EAAE,CAAC,MAAM,CAAC;AAEnD;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,KAAK,EAAgB;IAC5D,MAAM,MAAM,GAAG,KAAK,CAAC,MA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,CAAC,EAAE,SAAS;QAC/B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,SAAS;QAC/B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI;QAC1B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI;QAC1B,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI;KAC4C,CAAC;IAExE,yEAAyE;IACzE,0EAA0E;IAC1E,kEAAkE;IAClE,mBAAmB;IACnB,MAAM,IAAI,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE;QAC7B,SAAS,EAAE,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC;QAChC,QAAQ;KACR,CAAC,CAAC;IAEH,2EAA2E;IAC3E,kFAAkF;IAClF,4EAA4E;IAC5E,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACzE,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,IAAI,CAAC,KAAK,EAAE,CAAC;QACb,OAAO,SAAS,CAAC;IAClB,CAAC;IAED,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import Session, { type Version as QmuxVersion } from \"@moq/qmux\";\nimport { error, fromClose } from \"../error.ts\";\nimport * as Ietf from \"../ietf/index.ts\";\nimport * as Lite from \"../lite/index.ts\";\nimport type { Consumer as OriginConsumer, Producer as OriginProducer } from \"../origin.ts\";\nimport { Stream } from \"../stream.ts\";\nimport * as Time from \"../time.ts\";\nimport * as Hex from \"../util/hex.ts\";\nimport { dev, redact } from \"../util/log.ts\";\nimport { isWebTransportSupported } from \"./browser.ts\";\nimport type { Established } from \"./established.ts\";\nimport { forwardAnnounced } from \"./forward.ts\";\nimport { exchangeSetup } from \"./handshake.ts\";\n\n// Default head start for WebTransport before attempting the WebSocket fallback.\nconst DEFAULT_WEBSOCKET_DELAY_MS = Time.Milli(500);\n\n// RESET_STREAM and CONNECTION_CLOSE are separate transport notifications. Give the latter\n// time to surface its authoritative code without letting a reset-only peer stall SETUP forever.\nconst SETUP_CLOSE_GRACE_MS = 100;\n\n/** Tuning for the WebSocket fallback used when WebTransport is unavailable or loses the connect race. */\nexport interface WebSocketProps {\n\t/** Enable the WebSocket fallback. Defaults to `true`. */\n\tenabled?: boolean;\n\n\t/** Use a different URL than WebTransport. By default, `https` maps to `wss` and `http` to `ws`. */\n\turl?: URL;\n\n\t/**\n\t * The delay in milliseconds before attempting the WebSocket fallback (default: 500).\n\t * If WebSocket won the previous race for a given URL, this is 0.\n\t */\n\tdelay?: Time.Milli;\n}\n\n/**\n * A server certificate hash used to pin a self-signed server, one entry of\n * `serverCertificateHashes`. Unlike the DOM type, `value` also accepts a hex string (the\n * format moq servers report via their certificate fingerprints), decoded automatically.\n */\nexport interface CertificateHash {\n\t/** The hash algorithm. Defaults to `sha-256` (the only supported value). */\n\talgorithm?: \"sha-256\";\n\t/** The certificate hash: raw bytes or a hex string. */\n\tvalue: BufferSource | string;\n}\n\n/** WebTransport options extended with friendlier certificate pinning (hex hashes or a raw certificate). */\nexport interface WebTransportProps extends Omit<WebTransportOptions, \"serverCertificateHashes\"> {\n\t/**\n\t * Pin the server to one or more certificate hashes. Each `value` may be raw\n\t * bytes or a hex string; the algorithm defaults to `sha-256`.\n\t */\n\tserverCertificateHashes?: CertificateHash[];\n\n\t/**\n\t * Pin the server by supplying its certificate directly; the SHA-256 hash is\n\t * computed for you. Accepts a PEM string or raw DER bytes. Use this when you\n\t * have the certificate but not its precomputed fingerprint.\n\t */\n\tserverCertificate?: string | BufferSource;\n}\n\n/** Options for {@link connect}. */\nexport interface ConnectProps {\n\t/** The relay URL. */\n\turl: URL;\n\n\t/** WebTransport options. */\n\twebtransport?: WebTransportProps;\n\n\t/** WebSocket (fallback) options. */\n\twebsocket?: WebSocketProps;\n\n\t/**\n\t * Use a pre-existing WebTransport session instead of connecting; skips the\n\t * WebTransport/WebSocket race. The publisher acquires the session's datagram\n\t * writer lock (`datagrams.writable.getWriter()`) for the session's lifetime,\n\t * so the caller must not hold it. Aborting via {@link ConnectProps.signal}\n\t * closes this session, so don't share one you intend to reuse afterwards.\n\t */\n\ttransport?: WebTransport;\n\n\t/**\n\t * Whether the relay supports broadcast discovery; see {@link Established.discovery}.\n\t * Defaults to true.\n\t */\n\tdiscovery?: boolean;\n\n\t/**\n\t * The origin whose broadcasts the session announces and serves to the peer. Omit to\n\t * publish nothing.\n\t *\n\t * The origin is borrowed, not owned: closing the session leaves its broadcasts alone,\n\t * and the same origin can back several sessions (or successive reconnects), each\n\t * announcing the table for as long as it lasts.\n\t */\n\tpublish?: OriginConsumer;\n\n\t/**\n\t * The origin the session feeds with the peer's announced broadcasts. Omit to discover\n\t * nothing.\n\t *\n\t * Everything the peer announces appears in the origin's table for the session's\n\t * lifetime, consumable by path; the entries retract when the session dies. Pass the\n\t * producer behind {@link ConnectProps.publish} to route both directions through one\n\t * origin: a locally published path is then served back to local consumers directly, and\n\t * the session still never announces the peer's own broadcasts back to it.\n\t */\n\tconsume?: OriginProducer;\n\n\t/**\n\t * Aborts the connection attempt with the signal's reason. An already-aborted\n\t * signal rejects before anything opens, and aborting after the connection is\n\t * established has no effect. Use `AbortSignal.timeout(ms)` for a deadline.\n\t */\n\tsignal?: AbortSignal;\n}\n\n/** The per-session wiring shared by every negotiated protocol path. */\ntype SessionProps = {\n\tdiscovery: boolean;\n\tpublish?: OriginConsumer;\n};\n\n// Save if WebSocket won the last race, so we won't give QUIC a head start next time.\nconst websocketWon = new Set<string>();\n\n/** The default connect signal: never aborts. */\nconst NEVER_ABORTED = new AbortController().signal;\n\n/**\n * Establishes a connection to a MOQ server.\n *\n * @param url - The URL of the server to connect to\n * @param props - Connection options\n * @returns A promise that resolves to an established session\n */\nexport async function connect({ url, ...props }: ConnectProps): Promise<Established> {\n\tconst signal = props.signal ?? NEVER_ABORTED;\n\tsignal.throwIfAborted();\n\n\t// Resolves on abort so every in-flight transport tears itself down.\n\tconst { promise: abort, resolve } = Promise.withResolvers<void>();\n\tconst onAbort = () => resolve();\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\n\tconst pending = connectInner(url, props, abort);\n\ttry {\n\t\t// A `pending` rejection propagates unless the abort beat it to the finish line.\n\t\tconst connection = await Promise.race([pending, abort.then(() => undefined)]);\n\t\tif (connection && !signal.aborted) {\n\t\t\tif (props.consume) forwardAnnounced(connection, props.consume);\n\t\t\treturn connection;\n\t\t}\n\n\t\t// Close a connection that settles after the abort.\n\t\tpending.then((conn) => conn.close()).catch(() => {});\n\t\tthrow signal.reason;\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\n\nasync function connectInner(url: URL, props: Omit<ConnectProps, \"url\">, abort: Promise<void>): Promise<Established> {\n\tconst wiring: SessionProps = {\n\t\tdiscovery: props.discovery ?? true,\n\t\tpublish: props.publish,\n\t};\n\n\tif (props.transport) {\n\t\tconst transport = props.transport;\n\t\tvoid abort.then(() => transport.close());\n\t\treturn connectTransport(url, transport, wiring);\n\t}\n\n\t// Stop transports after one connects or the caller aborts.\n\tconst { promise: raced, resolve: done } = Promise.withResolvers<void>();\n\tconst cancel = Promise.race([raced, abort]);\n\n\tconst webtransport = isWebTransportSupported() ? connectWebTransport(url, cancel, props.webtransport) : undefined;\n\n\t// Give QUIC a head start to connect before trying WebSocket, unless WebSocket has won in the past.\n\t// NOTE that QUIC should be faster because it involves 1/2 fewer RTTs.\n\tconst headstart =\n\t\t!webtransport || websocketWon.has(url.toString()) ? 0 : (props.websocket?.delay ?? DEFAULT_WEBSOCKET_DELAY_MS);\n\tconst websocket =\n\t\tprops.websocket?.enabled !== false\n\t\t\t? connectWebSocket(props.websocket?.url ?? url, headstart, cancel)\n\t\t\t: undefined;\n\n\tif (!websocket && !webtransport) {\n\t\tthrow new Error(\"no transport available; WebTransport not supported and WebSocket is disabled\");\n\t}\n\n\t// Race the available transports, using `.any` to ignore if one participant has an error.\n\t// `webtransport`/`websocket` are `Promise | undefined`, so test existence explicitly: a\n\t// promise is always truthy, so bare truthiness here would be a misused-promise.\n\tconst session = await Promise.any(\n\t\twebtransport !== undefined\n\t\t\t? websocket !== undefined\n\t\t\t\t? [websocket, webtransport]\n\t\t\t\t: [webtransport]\n\t\t\t: [websocket],\n\t);\n\tdone();\n\n\tif (!session) throw new Error(\"no transport available\");\n\n\t// Abort the setup handshake without leaking the selected transport.\n\tvoid abort.then(() => session.close());\n\n\t// Save if WebSocket won the last race, so we won't give QUIC a head start next time.\n\tif (session instanceof Session) {\n\t\t// Still a warning, not a debug line: losing the race means we fell back off QUIC.\n\t\tif (dev()) console.warn(redact(url), \"connected via WebSocket\");\n\t\twebsocketWon.add(url.toString());\n\t} else if (dev()) {\n\t\tconsole.debug(redact(url), \"connected via WebTransport\");\n\t}\n\n\t// The remaining setup is identical whether the transport was raced or supplied.\n\treturn await connectTransport(url, session as WebTransport, wiring);\n}\n\nasync function connectTransport(url: URL, session: WebTransport, wiring: SessionProps): Promise<Established> {\n\tconst closed = session.closed.then(fromClose, error);\n\tconst terminal = closed.then((cause) => {\n\t\tthrow cause ?? new Error(\"session closed during SETUP\");\n\t});\n\n\ttry {\n\t\treturn await Promise.race([terminal, negotiate(url, session, wiring)]);\n\t} catch (cause) {\n\t\t// A session shutdown can reject its SETUP stream before `closed` publishes the\n\t\t// peer's close code. Wait briefly without closing locally, since a local clean close\n\t\t// could overwrite that code. A reset-only peer is cleaned up after the grace period.\n\t\tconst pending = Symbol(\"session close pending\");\n\t\tconst final = await Promise.race([\n\t\t\tclosed,\n\t\t\tnew Promise<typeof pending>((resolve) => setTimeout(() => resolve(pending), SETUP_CLOSE_GRACE_MS)),\n\t\t]);\n\t\tif (final !== pending) {\n\t\t\tif (final) throw final;\n\t\t\tthrow cause;\n\t\t}\n\n\t\tsession.close();\n\t\tthrow cause;\n\t}\n}\n\n// Negotiate the MoQ protocol over an established transport. The caller races this against\n// the session closing so a close code is not lost behind a failed or stalled SETUP stream.\nasync function negotiate(url: URL, session: WebTransport, wiring: SessionProps): Promise<Established> {\n\t// The DOM lib has no `protocol` property yet. It is \"\" when none was negotiated, and\n\t// undefined in a browser that predates subprotocols (Firefox before 155).\n\tconst protocol: string | undefined = (session as { protocol?: string }).protocol || undefined;\n\tif (dev()) console.debug(redact(url), \"negotiated ALPN:\", protocol ?? \"(none)\");\n\n\t// Choose setup encoding based on negotiated WebTransport protocol (if any).\n\tlet setupVersion: Ietf.Version;\n\tconst modernVersion =\n\t\tprotocol === Ietf.ALPN.DRAFT_22\n\t\t\t? Ietf.Version.DRAFT_22\n\t\t\t: protocol === Ietf.ALPN.DRAFT_21\n\t\t\t\t? Ietf.Version.DRAFT_21\n\t\t\t\t: protocol === Ietf.ALPN.DRAFT_20\n\t\t\t\t\t? Ietf.Version.DRAFT_20\n\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_19\n\t\t\t\t\t\t? Ietf.Version.DRAFT_19\n\t\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_18\n\t\t\t\t\t\t\t? Ietf.Version.DRAFT_18\n\t\t\t\t\t\t\t: protocol === Ietf.ALPN.DRAFT_17\n\t\t\t\t\t\t\t\t? Ietf.Version.DRAFT_17\n\t\t\t\t\t\t\t\t: undefined;\n\tif (modernVersion !== undefined) {\n\t\treturn await handshakeAlpn(url, session, modernVersion, wiring);\n\t} else if (protocol === Ietf.ALPN.DRAFT_16) {\n\t\tsetupVersion = Ietf.Version.DRAFT_16;\n\t} else if (protocol === Ietf.ALPN.DRAFT_15) {\n\t\tsetupVersion = Ietf.Version.DRAFT_15;\n\t} else if (protocol === Lite.ALPN_07_WIP) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_07, ...wiring });\n\t} else if (protocol === Lite.ALPN_06) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_06, ...wiring });\n\t} else if (protocol === Lite.ALPN_05) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_05, ...wiring });\n\t} else if (protocol === Lite.ALPN_04) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_04, ...wiring });\n\t} else if (protocol === Lite.ALPN_03) {\n\t\treturn new Lite.Connection({ url, quic: session, version: Lite.Version.DRAFT_03, ...wiring });\n\t} else if (protocol === Lite.ALPN || protocol === \"\" || protocol === undefined) {\n\t\tsetupVersion = Ietf.Version.DRAFT_14;\n\t} else {\n\t\tthrow new Error(`unsupported WebTransport protocol: ${protocol}`);\n\t}\n\n\tconst stream = await Stream.open(session, { version: setupVersion });\n\tawait stream.writer.u53(Lite.StreamId.ClientCompat);\n\n\tconst encoder = new TextEncoder();\n\n\tconst params = new Ietf.SetupOptions();\n\tparams.setVarint(Ietf.SetupOption.MaxRequestId, 42069n);\n\tparams.setBytes(Ietf.SetupOption.Implementation, encoder.encode(\"moq-lite-js\"));\n\tIetf.solicitIntoSetup(params);\n\tIetf.hiddenIntoSetup(params);\n\n\tconst client = new Ietf.ClientSetup({\n\t\tversions:\n\t\t\tsetupVersion === Ietf.Version.DRAFT_16\n\t\t\t\t? [Ietf.Version.DRAFT_16]\n\t\t\t\t: setupVersion === Ietf.Version.DRAFT_15\n\t\t\t\t\t? [Ietf.Version.DRAFT_15]\n\t\t\t\t\t: [Lite.Version.DRAFT_02, Lite.Version.DRAFT_01, Ietf.Version.DRAFT_14],\n\t\tparameters: params,\n\t});\n\tawait client.encode(stream.writer, setupVersion);\n\n\tconst serverCompat = await stream.reader.u53();\n\tif (serverCompat !== Lite.StreamId.ServerCompat) {\n\t\tthrow new Error(`unsupported server message type: ${serverCompat.toString()}`);\n\t}\n\n\tconst server = await Ietf.ServerSetup.decode(stream.reader, setupVersion);\n\n\tif (Object.values(Lite.Version).includes(server.version as Lite.Version)) {\n\t\treturn new Lite.Connection({\n\t\t\turl,\n\t\t\tquic: session,\n\t\t\tversion: server.version as Lite.Version,\n\t\t\tsession: stream,\n\t\t\t...wiring,\n\t\t});\n\t} else if (Object.values(Ietf.Version).includes(server.version as Ietf.Version)) {\n\t\tconst maxRequestId = server.parameters.getVarint(Ietf.SetupOption.MaxRequestId) ?? 0n;\n\t\treturn new Ietf.Connection({\n\t\t\t...wiring,\n\t\t\tclient: true,\n\t\t\turl,\n\t\t\tquic: session,\n\t\t\tcontrol: stream,\n\t\t\tmaxRequestId,\n\t\t\tversion: server.version as Ietf.IetfVersion,\n\t\t\tsolicit: Ietf.solicitFromSetup(server.parameters),\n\t\t\thidden: Ietf.hiddenFromSetup(server.parameters),\n\t\t});\n\t} else {\n\t\tthrow new Error(`unsupported server version: ${server.version.toString()}`);\n\t}\n}\n\n/**\n * Draft-17+ client handshake. ALPN already pinned the version; SETUP is\n * exchanged over a pair of uni streams using stream type 0x2F00.\n */\nasync function handshakeAlpn(\n\turl: URL,\n\tsession: WebTransport,\n\tversion: Ietf.IetfVersion,\n\twiring: SessionProps,\n): Promise<Established> {\n\tconst { control, early, solicit, hidden, cluster } = await exchangeSetup(session, version, \"moq-lite-js\");\n\n\treturn new Ietf.Connection({\n\t\t...wiring,\n\t\tclient: true,\n\t\turl,\n\t\tquic: session,\n\t\tcontrol,\n\t\tearly,\n\t\tsolicit,\n\t\thidden,\n\t\tcluster,\n\t\t// v17+ uses NativeSession which manages its own request IDs; maxRequestId is unused.\n\t\tmaxRequestId: 0n,\n\t\tversion,\n\t});\n}\n\n// One entry of the DOM `serverCertificateHashes`, derived without naming the lib type.\ntype WebTransportHash = NonNullable<WebTransportOptions[\"serverCertificateHashes\"]>[number];\n\n// Strip PEM armor and base64-decode to the raw DER bytes.\nfunction pemToDer(pem: string): Uint8Array<ArrayBuffer> {\n\t// indexOf rather than a lazy regex, which goes quadratic on repeated BEGIN lines without an END.\n\tconst begin = \"-----BEGIN CERTIFICATE-----\";\n\tconst start = pem.indexOf(begin);\n\tconst end = start < 0 ? -1 : pem.indexOf(\"-----END CERTIFICATE-----\", start + begin.length);\n\tconst body = end < 0 ? \"\" : pem.slice(start + begin.length, end).replace(/\\s+/g, \"\");\n\tif (!body) {\n\t\tthrow new Error(\"invalid PEM certificate: missing -----BEGIN/END CERTIFICATE----- armor\");\n\t}\n\n\tconst binary = atob(body);\n\tconst der = new Uint8Array(binary.length);\n\tfor (let i = 0; i < binary.length; i++) {\n\t\tder[i] = binary.charCodeAt(i);\n\t}\n\treturn der;\n}\n\n/**\n * Compute the SHA-256 hash of a certificate, the value `serverCertificateHashes`\n * pins. Accepts a PEM string or raw DER bytes. Matches the hex fingerprints a moq\n * server reports, so `Hex.fromBytes(await certificateHash(pem))` round-trips.\n */\nexport async function certificateHash(cert: string | BufferSource): Promise<Uint8Array<ArrayBuffer>> {\n\tconst der = typeof cert === \"string\" ? pemToDer(cert) : cert;\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", der);\n\treturn new Uint8Array(digest);\n}\n\n// Normalize our friendlier pinning options into the DOM `serverCertificateHashes`.\nasync function resolveCertificateHashes(options?: WebTransportProps): Promise<WebTransportHash[] | undefined> {\n\tconst hashes: WebTransportHash[] = [];\n\n\tfor (const hash of options?.serverCertificateHashes ?? []) {\n\t\tconst value = typeof hash.value === \"string\" ? Hex.toBytes(hash.value) : hash.value;\n\t\thashes.push({ algorithm: hash.algorithm ?? \"sha-256\", value });\n\t}\n\n\tif (options?.serverCertificate !== undefined) {\n\t\thashes.push({ algorithm: \"sha-256\", value: await certificateHash(options.serverCertificate) });\n\t}\n\n\treturn hashes.length > 0 ? hashes : undefined;\n}\n\nasync function connectWebTransport(\n\turl: URL,\n\tcancel: Promise<void>,\n\toptions?: WebTransportProps,\n): Promise<WebTransport | undefined> {\n\tlet finalUrl = url;\n\n\t// Our custom pinning fields are normalized separately; the rest are DOM options.\n\tconst { serverCertificate: _cert, serverCertificateHashes: _hashes, ...webtransport } = options ?? {};\n\n\tconst finalOptions: WebTransportOptions = {\n\t\tallowPooling: false,\n\t\tcongestionControl: \"low-latency\",\n\t\tprotocols: [\n\t\t\t// Lite.ALPN_07_WIP is intentionally omitted: lite-07 is work-in-progress and\n\t\t\t// not advertised by default (negotiate still accepts it if a server selects it).\n\t\t\tLite.ALPN_06,\n\t\t\tLite.ALPN_05,\n\t\t\tLite.ALPN_04,\n\t\t\tLite.ALPN_03,\n\t\t\tLite.ALPN,\n\t\t\tIetf.ALPN.DRAFT_22,\n\t\t\tIetf.ALPN.DRAFT_21,\n\t\t\tIetf.ALPN.DRAFT_20,\n\t\t\tIetf.ALPN.DRAFT_19,\n\t\t\tIetf.ALPN.DRAFT_18,\n\t\t\tIetf.ALPN.DRAFT_17,\n\t\t\tIetf.ALPN.DRAFT_16,\n\t\t\tIetf.ALPN.DRAFT_15,\n\t\t],\n\t\t...webtransport,\n\t};\n\n\t// Accumulate caller-provided pins first, then append anything we fetch below,\n\t// so a fetched fingerprint never clobbers hashes passed in via options.\n\tconst hashes = (await resolveCertificateHashes(options)) ?? [];\n\n\t// Only perform certificate fetch and URL rewrite when polyfill is not needed\n\t// This is needed because WebTransport is a butt to work with in local development.\n\tif (url.protocol === \"http:\") {\n\t\tconst fingerprintUrl = new URL(url);\n\t\tfingerprintUrl.pathname = \"/certificate.sha256\";\n\t\t// The certificate endpoint is unauthenticated, so don't hand it the token.\n\t\tfingerprintUrl.search = \"\";\n\n\t\t// Dev-only path: http:// can't be a real WebTransport origin, so we fetch the\n\t\t// self-signed cert's hash over plain HTTP and pin it. Production uses https://\n\t\t// and never reaches here. Keep this at debug so it doesn't read as a problem.\n\t\tif (dev()) {\n\t\t\tconsole.debug(\n\t\t\t\tredact(fingerprintUrl),\n\t\t\t\t\"performing an insecure fingerprint fetch; use https:// in production\",\n\t\t\t);\n\t\t}\n\n\t\t// Fetch the fingerprint from the server.\n\t\t// TODO cancel the request if the effect is cancelled.\n\t\tconst fingerprint = await Promise.race([fetch(fingerprintUrl), cancel]);\n\t\tif (!fingerprint) return undefined;\n\n\t\tconst fingerprintText = await Promise.race([fingerprint.text(), cancel]);\n\t\tif (fingerprintText === undefined) return undefined;\n\n\t\thashes.push({ algorithm: \"sha-256\", value: Hex.toBytes(fingerprintText) });\n\n\t\tfinalUrl = new URL(url);\n\t\tfinalUrl.protocol = \"https:\";\n\t}\n\n\tif (hashes.length > 0) {\n\t\tfinalOptions.serverCertificateHashes = hashes;\n\t}\n\n\tconst quic = new WebTransport(finalUrl, finalOptions);\n\n\t// Both .ready and .closed reject on failure; catch .closed to avoid an unhandled rejection.\n\tquic.closed.catch(() => {});\n\n\t// Wait for the WebTransport to connect, or for the cancel promise to resolve.\n\t// Close the connection if we lost the race.\n\tconst loaded = await Promise.race([quic.ready.then(() => true), cancel]);\n\tif (!loaded) {\n\t\tquic.close();\n\t\treturn undefined;\n\t}\n\n\treturn quic;\n}\n\n// TODO accept arguments to control the port/path used.\nasync function connectWebSocket(url: URL, delay: number, cancel: Promise<void>): Promise<Session | undefined> {\n\tconst timer = new Promise<void>((resolve) => setTimeout(resolve, delay));\n\n\tconst active = await Promise.race([cancel, timer.then(() => true)]);\n\tif (!active) return undefined;\n\n\t// moq-transport-18 and newer are pinned to qmux-01. Every other ALPN we\n\t// support is currently negotiated as `qmux-00.{alpn}` on the wire, but we\n\t// don't want to lock that in: set the value to `null` so the polyfill\n\t// advertises every QMux draft it knows about and the server picks one.\n\t// Insertion order is the negotiation preference on the wire.\n\tconst versions = {\n\t\t// Lite.ALPN_07_WIP omitted on purpose: lite-07 is work-in-progress, not advertised by default.\n\t\t[Lite.ALPN_06]: null,\n\t\t[Lite.ALPN_05]: null,\n\t\t[Lite.ALPN_04]: null,\n\t\t[Lite.ALPN_03]: null,\n\t\t[Lite.ALPN]: null,\n\t\t[Ietf.ALPN.DRAFT_22]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_21]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_20]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_19]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_18]: \"qmux-01\",\n\t\t[Ietf.ALPN.DRAFT_17]: null,\n\t\t[Ietf.ALPN.DRAFT_16]: null,\n\t\t[Ietf.ALPN.DRAFT_15]: null,\n\t} as const satisfies Record<string, QmuxVersion | QmuxVersion[] | null>;\n\n\t// The default (`requireProtocol: false`) also advertises bare `qmux-01`,\n\t// `qmux-00`, and `webtransport` so we still interop with relays that only\n\t// know a wire-format version (today's moq-relay only accepts bare\n\t// `webtransport`).\n\tconst quic = new Session(url, {\n\t\tprotocols: Object.keys(versions),\n\t\tversions,\n\t});\n\n\t// Wait for the WebSocket to connect, or for the cancel promise to resolve.\n\t// `ready` rejects on a refused/failed connection, so a throw here is the caller's\n\t// cue to retry; a lost cancel race instead resolves and we close the loser.\n\tconst loaded = await Promise.race([quic.ready.then(() => true), cancel]);\n\tif (!loaded) {\n\t\tquic.close();\n\t\treturn undefined;\n\t}\n\n\treturn quic;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@moq/net",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.4.
|
|
4
|
+
"version": "0.4.5",
|
|
5
5
|
"description": "The networking layer for Media over QUIC: real-time pub/sub with built-in caching, fan-out, and prioritization.",
|
|
6
6
|
"license": "(MIT OR Apache-2.0)",
|
|
7
7
|
"repository": {
|
package/path.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"path.d.ts","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,MAAM,KAAK,GAAG,MAAM,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AAEjD;;;;;;GAMG;AACH,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG;IAAE,OAAO,EAAE,UAAU,CAAA;CAAE,CAAC;AAExD;;;;;GAKG;AACH,e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AE,KAAK,EAAE,IAAI,EAAE,KAAK,GAAG,KAAK,GAAG,IAAI,CAiBpE;AAED;;;;;;;;;GASG;AACH,wBAAgB,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,GAAG,KAAK,CASrD;AAED,uDAAuD;AACvD,wBAAgB,KAAK,IAAI,KAAK,CAE7B;AAED;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,GAAG,QAAQ,CAKvD;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,QAAQ,GAAG,KAAK,CAkBzD;AAED;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,QAAQ,GAAG,KAAK,GAAG,SAAS,CAkBxE;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,QAAQ,CAAC,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,GAAG,QAAQ,GAAG,SAAS,CA0BzE;AAED,kEAAkE;AAClE,OAAO,EACN,kBAAkB,EAClB,cAAc,EACd,OAAO,EACP,QAAQ,EACR,KAAK,OAAO,EACZ,KAAK,WAAW,GAChB,MAAM,cAAc,CAAC"}
|
package/path.js
CHANGED
|
@@ -32,8 +32,12 @@ export function decode(raw) {
|
|
|
32
32
|
* emit a path the remote side is required to reject.
|
|
33
33
|
*/
|
|
34
34
|
export function encode(path) {
|
|
35
|
-
|
|
36
|
-
|
|
35
|
+
// Count separators with an early exit instead of splitting, so a hostile path never allocates per part.
|
|
36
|
+
let count = path === "" ? 0 : 1;
|
|
37
|
+
for (let i = path.indexOf("/"); i !== -1; i = path.indexOf("/", i + 1)) {
|
|
38
|
+
if (++count > MAX_PARTS) {
|
|
39
|
+
throw new Error(`path exceeds ${MAX_PARTS} parts`);
|
|
40
|
+
}
|
|
37
41
|
}
|
|
38
42
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C,MAAM,CAAC,EAAE,CAAC;QACtF,MAAM,IAAI,CAAC,CAAC;IACb,CAAC;IAED,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IACjC,yDAAyD;IACzD,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC;IAEzE,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC;SACpC,IAAI,CAAC,IAAI,CAAC;SACV,MAAM,CAAC,IAAI,CAAC,CAAC;IAEf,iFAAiF;IACjF,OAAO,CAAC,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAa,CAAC;AAC7D,CAAC;AAED,kEAAkE;AAClE,OAAO,EACN,kBAAkB,EAClB,cAAc,EACd,OAAO,EACP,QAAQ,GAGR,MAAM,cAAc,CAAC","sourcesContent":["/**\n * A broadcast path that provides safe prefix matching operations.\n *\n * This module provides path-aware operations that respect delimiter boundaries,\n * preventing issues like \"foo\" matching \"foobar\".\n *\n * Paths are automatically trimmed of leading and trailing slashes on creation,\n * making all slashes implicit at boundaries. A path names a point in the origin's\n * tree from its root; a leading slash never escapes that root. The same type names\n * an exact broadcast and the prefix a route or announcement covers, so a broadcast's\n * own path is the prefix it announces. See {@link Relative} for `..`-style references.\n *\n * {@link Pattern} and {@link Patterns} are re-exported from `@moq/pattern`, the owner of\n * the v1 grammar and algebra. Literal path construction and wire decoding retain\n * their existing behavior.\n *\n * @example\n * ```typescript\n * // Creation automatically trims slashes\n * const path1 = Path.from(\"/foo/bar/\");\n * const path2 = Path.from(\"foo/bar\");\n * console.log(path1 === path2); // true\n *\n * // Multiple arguments are joined with \"/\"\n * const path3 = Path.from(\"api\", \"v1\", \"users\");\n * console.log(path3); // \"api/v1/users\"\n *\n * // Safe prefix matching\n * const base = Path.from(\"api/v1\");\n * console.log(Path.hasPrefix(Path.from(\"api\"), base)); // true\n * console.log(Path.hasPrefix(Path.from(\"api/v1\"), base)); // true\n *\n * const joined = Path.join(base, Path.from(\"users\"));\n * console.log(joined); // \"api/v1/users\"\n * ```\n */\nexport type Valid = string & { __brand: \"Name\" };\n\n/**\n * A relative reference from one broadcast to another, as a hang catalog carries it.\n *\n * It may contain `..` and is meaningful only once {@link resolve}d against a base\n * {@link Valid} path. It never crosses the wire on its own. Build one with\n * {@link normalizeRelative} or {@link relative}.\n */\nexport type Relative = string & { __brand: \"Relative\" };\n\n/**\n * Maximum number of slash-separated parts in a path.\n *\n * Matches the IETF moq-transport limit of 32 fields in a namespace tuple.\n * moq-lite enforces the same bound when decoding paths off the wire.\n */\nexport const MAX_PARTS = 32;\n\n/** Build a path from one or more components, joining with \"/\" and trimming redundant slashes. */\nexport function from(...paths: string[]): Valid {\n\t// Join paths with \"/\" and then remove leading and trailing slashes, and collapse multiple slashes into one.\n\tconst joined = paths.join(\"/\");\n\treturn joined.replace(/\\/+/g, \"/\").replace(/^\\/+/, \"\").replace(/\\/+$/, \"\") as Valid;\n}\n\n/** Split a path into its slash-separated parts. The empty path has no parts. */\nexport function parts(path: Valid): string[] {\n\treturn path === \"\" ? [] : path.split(\"/\");\n}\n\n/**\n * Validate an untrusted wire string as a path, enforcing {@link MAX_PARTS}.\n *\n * Throws when the path has too many parts; use at wire decode sites.\n */\nexport function decode(raw: string): Valid {\n\tconst path = from(raw);\n\treturn encode(path);\n}\n\n/**\n * Validate a path before writing it to the wire, enforcing {@link MAX_PARTS}.\n *\n * Throws when the path has too many parts; use at wire encode sites so we never\n * emit a path the remote side is required to reject.\n */\nexport function encode(path: Valid): Valid {\n\tif (parts(path).length > MAX_PARTS) {\n\t\tthrow new Error(`path exceeds ${MAX_PARTS} parts`);\n\t}\n\treturn path;\n}\n\n/**\n * Check if a path has the given prefix, respecting path boundaries.\n *\n * Unlike String.startsWith, this ensures that \"foo\" does not match \"foobar\".\n * The prefix must either:\n * - Be exactly equal to the path\n * - Be followed by a '/' delimiter in the original path\n * - Be empty (matches everything)\n *\n * @example\n * ```typescript\n * const path = Path.from(\"foo/bar\");\n * console.log(Path.hasPrefix(Path.from(\"foo\"), path)); // true\n * console.log(Path.hasPrefix(Path.from(\"foo/\"), path)); // true (trailing slash ignored)\n * console.log(Path.hasPrefix(Path.from(\"fo\"), path)); // false\n *\n * const path2 = Path.from(\"foobar\");\n * console.log(Path.hasPrefix(Path.from(\"foo\"), path2)); // false\n * ```\n */\nexport function hasPrefix(prefix: Valid, path: Valid): boolean {\n\tif (prefix === \"\") {\n\t\treturn true;\n\t}\n\n\tif (!path.startsWith(prefix)) {\n\t\treturn false;\n\t}\n\n\t// Check if the prefix is the exact match\n\tif (path.length === prefix.length) {\n\t\treturn true;\n\t}\n\n\t// Otherwise, ensure the character after the prefix is a delimiter\n\treturn path[prefix.length] === \"/\";\n}\n\n/**\n * Strip the given prefix from a path, returning the suffix.\n *\n * Returns null if the prefix doesn't match according to hasPrefix rules.\n *\n * @example\n * ```typescript\n * const path = Path.from(\"foo/bar/baz\");\n * const suffix = Path.stripPrefix(Path.from(\"foo\"), path);\n * console.log(suffix); // \"bar/baz\"\n *\n * const suffix2 = Path.stripPrefix(Path.from(\"foo/\"), path);\n * console.log(suffix2); // \"bar/baz\"\n *\n * const noMatch = Path.stripPrefix(Path.from(\"notfound\"), path);\n * console.log(noMatch); // null\n * ```\n */\nexport function stripPrefix(prefix: Valid, path: Valid): Valid | null {\n\tif (!hasPrefix(prefix, path)) {\n\t\treturn null;\n\t}\n\n\t// Handle empty prefix case\n\tif (prefix === \"\") {\n\t\treturn path;\n\t}\n\n\t// If prefix matches exactly, return empty\n\tif (path.length === prefix.length) {\n\t\treturn \"\" as Valid;\n\t}\n\n\t// For non-empty prefix that's shorter, skip the prefix and the following slash\n\treturn path.slice(prefix.length + 1) as Valid;\n}\n\n/**\n * Join two path components together.\n *\n * @example\n * ```typescript\n * const base = Path.from(\"foo\");\n * const joined = Path.join(base, Path.from(\"bar\"));\n * console.log(joined); // \"foo/bar\"\n * ```\n */\nexport function join(path: Valid, other: Valid): Valid {\n\tif (path === \"\") {\n\t\treturn other;\n\t} else if (other === \"\") {\n\t\treturn path;\n\t} else {\n\t\t// Since paths are trimmed, we always need to add a slash\n\t\treturn `${path}/${other}` as Valid;\n\t}\n}\n\n/** The empty path, which is a prefix of every path. */\nexport function empty(): Valid {\n\treturn \"\" as Valid;\n}\n\n/**\n * Normalize a relative path reference: trim leading/trailing slashes, drop empty\n * segments, and drop redundant `.` segments. A reference made only of `.` segments\n * normalizes to `.` because it names the base's parent, while empty names the base.\n * `..` is preserved and only interpreted by {@link resolve}.\n *\n * Mirrors the Rust `path::Relative::new` normalization, so JS and Rust agree\n * byte-for-byte on the stored form. Two callers comparing normalized strings can\n * detect equivalent references while preserving the distinction between `\"\"` and `\".\"`.\n */\nexport function normalizeRelative(rel: string): Relative {\n\tconst raw = rel.split(\"/\");\n\tconst normalized = raw.filter((s) => s !== \"\" && s !== \".\").join(\"/\");\n\n\treturn (normalized === \"\" && raw.includes(\".\") ? \".\" : normalized) as Relative;\n}\n\n/**\n * Resolve a relative path reference against a base path.\n *\n * A non-empty reference replaces the last segment of the base, matching relative URL\n * resolution. `..` segments then pop another segment; other segments are appended.\n * `.` and empty segments are no-ops. Excess `..` once the base is empty is also a no-op\n * (subsequent named segments still append). An empty `rel` returns the base unchanged.\n *\n * Mirrors the Rust `Path::resolve`, used by hang catalogs to express\n * cross-broadcast track references (a rendition's `broadcast` field).\n *\n * @example\n * ```typescript\n * Path.resolve(Path.from(\"a/b/c\"), \"./source\"); // \"a/b/source\"\n * Path.resolve(Path.from(\"a/b\"), \".\"); // \"a\"\n * Path.resolve(Path.from(\"a/b/c\"), \"../source\"); // \"a/source\"\n * ```\n */\nexport function resolve(base: Valid, rel: Relative): Valid {\n\tif (rel === \"\") return base;\n\n\tconst segments = base === \"\" ? [] : base.split(\"/\");\n\tsegments.pop();\n\n\tfor (const seg of rel.split(\"/\")) {\n\t\tif (seg === \"\" || seg === \".\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (seg === \"..\") {\n\t\t\tsegments.pop();\n\t\t} else {\n\t\t\tsegments.push(seg);\n\t\t}\n\t}\n\n\treturn segments.join(\"/\") as Valid;\n}\n\n/**\n * Resolve a relative path, returning `undefined` if it escapes above the root.\n *\n * Unlike {@link resolve}, this distinguishes a valid reference to the empty root\n * path from excess `..` segments. Use it for untrusted catalog references that\n * must not be clamped to the root.\n */\nexport function tryResolve(base: Valid, rel: Relative): Valid | undefined {\n\tif (rel === \"\") return base;\n\n\tconst segments = base === \"\" ? [] : base.split(\"/\");\n\tsegments.pop();\n\n\tfor (const seg of rel.split(\"/\")) {\n\t\tif (seg === \"\" || seg === \".\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (seg === \"..\") {\n\t\t\tif (segments.pop() === undefined) return undefined;\n\t\t} else {\n\t\t\tsegments.push(seg);\n\t\t}\n\t}\n\n\treturn segments.join(\"/\") as Valid;\n}\n\n/**\n * Express `target` relative to `base`: the inverse of {@link resolve}.\n *\n * The result round-trips (`resolve(base, relative(target, base)) === target`) and never\n * walks above the root, so {@link tryResolve} accepts it too.\n *\n * A relative reference replaces the last segment of the base, matching relative URL\n * resolution, so a target nested under the base repeats the base's own last segment.\n *\n * The empty reference names the base itself, so that is what a self-reference returns.\n *\n * Returns `undefined` for a target no reference can name: a path segment may literally be\n * `.` or `..`, which resolution reads as navigation instead of as a name. Only the segments\n * past the shared prefix matter, since the rest are never emitted.\n *\n * Mirrors the Rust `Path::relative`, used to author the cross-broadcast track\n * references a hang catalog carries. Note the argument order: the target comes first,\n * the opposite of Node's `path.relative(from, to)`.\n *\n * @example\n * ```typescript\n * Path.relative(Path.from(\"a/b/c\"), Path.from(\"a/b\")); // \"b/c\"\n * Path.relative(Path.from(\"a/c\"), Path.from(\"a/b\")); // \"c\"\n * Path.relative(Path.from(\"a\"), Path.from(\"a/b\")); // \".\"\n * Path.relative(Path.from(\"a/b\"), Path.from(\"a/b\")); // \"\"\n * Path.relative(Path.from(\"a/..\"), Path.from(\"a/b\")); // undefined\n * ```\n */\nexport function relative(target: Valid, base: Valid): Relative | undefined {\n\t// Only the empty reference can name a base whose last segment is itself `.` or `..`,\n\t// since resolution replaces that segment rather than emitting it.\n\tif (target === base) return \"\" as Relative;\n\n\t// Resolution replaces the base's last segment, so walk from its parent.\n\tconst dir = base === \"\" ? [] : base.split(\"/\");\n\tdir.pop();\n\n\tconst parts = target === \"\" ? [] : target.split(\"/\");\n\n\tlet common = 0;\n\twhile (common < dir.length && common < parts.length && dir[common] === parts[common]) {\n\t\tcommon += 1;\n\t}\n\n\tconst down = parts.slice(common);\n\t// Resolution would walk on these instead of naming them.\n\tif (down.some((part) => part === \".\" || part === \"..\")) return undefined;\n\n\tconst rel = Array(dir.length - common)\n\t\t.fill(\"..\")\n\t\t.concat(down);\n\n\t// An empty reference resolves to the base itself, so name the parent explicitly.\n\treturn (rel.length === 0 ? \".\" : rel.join(\"/\")) as Relative;\n}\n\n/** Path patterns: grammar and algebra owned by `@moq/pattern`. */\nexport {\n\tcompareSpecificity,\n\tInvalidPattern,\n\tPattern,\n\tPatterns,\n\ttype Segment,\n\ttype Specificity,\n} from \"@moq/pattern\";\n"]}
|
|
1
|
+
{"version":3,"file":"path.js","sourceRoot":"","sources":["../src/path.ts"],"names":[],"mappings":"AA+CA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAE5B,iGAAiG;AACjG,MAAM,UAAU,IAAI,CAAC,GAAG,KAAe;IACtC,4GAA4G;IAC5G,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC/B,OAAO,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EA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yD;IACzD,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC;IAEzE,MAAM,GAAG,GAAG,KAAK,CAAC,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC;SACpC,IAAI,CAAC,IAAI,CAAC;SACV,MAAM,CAAC,IAAI,CAAC,CAAC;IAEf,iFAAiF;IACjF,OAAO,CAAC,GAAG,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAa,CAAC;AAC7D,CAAC;AAED,kEAAkE;AAClE,OAAO,EACN,kBAAkB,EAClB,cAAc,EACd,OAAO,EACP,QAAQ,GAGR,MAAM,cAAc,CAAC","sourcesContent":["/**\n * A broadcast path that provides safe prefix matching operations.\n *\n * This module provides path-aware operations that respect delimiter boundaries,\n * preventing issues like \"foo\" matching \"foobar\".\n *\n * Paths are automatically trimmed of leading and trailing slashes on creation,\n * making all slashes implicit at boundaries. A path names a point in the origin's\n * tree from its root; a leading slash never escapes that root. The same type names\n * an exact broadcast and the prefix a route or announcement covers, so a broadcast's\n * own path is the prefix it announces. See {@link Relative} for `..`-style references.\n *\n * {@link Pattern} and {@link Patterns} are re-exported from `@moq/pattern`, the owner of\n * the v1 grammar and algebra. Literal path construction and wire decoding retain\n * their existing behavior.\n *\n * @example\n * ```typescript\n * // Creation automatically trims slashes\n * const path1 = Path.from(\"/foo/bar/\");\n * const path2 = Path.from(\"foo/bar\");\n * console.log(path1 === path2); // true\n *\n * // Multiple arguments are joined with \"/\"\n * const path3 = Path.from(\"api\", \"v1\", \"users\");\n * console.log(path3); // \"api/v1/users\"\n *\n * // Safe prefix matching\n * const base = Path.from(\"api/v1\");\n * console.log(Path.hasPrefix(Path.from(\"api\"), base)); // true\n * console.log(Path.hasPrefix(Path.from(\"api/v1\"), base)); // true\n *\n * const joined = Path.join(base, Path.from(\"users\"));\n * console.log(joined); // \"api/v1/users\"\n * ```\n */\nexport type Valid = string & { __brand: \"Name\" };\n\n/**\n * A relative reference from one broadcast to another, as a hang catalog carries it.\n *\n * It may contain `..` and is meaningful only once {@link resolve}d against a base\n * {@link Valid} path. It never crosses the wire on its own. Build one with\n * {@link normalizeRelative} or {@link relative}.\n */\nexport type Relative = string & { __brand: \"Relative\" };\n\n/**\n * Maximum number of slash-separated parts in a path.\n *\n * Matches the IETF moq-transport limit of 32 fields in a namespace tuple.\n * moq-lite enforces the same bound when decoding paths off the wire.\n */\nexport const MAX_PARTS = 32;\n\n/** Build a path from one or more components, joining with \"/\" and trimming redundant slashes. */\nexport function from(...paths: string[]): Valid {\n\t// Join paths with \"/\" and then remove leading and trailing slashes, and collapse multiple slashes into one.\n\tconst joined = paths.join(\"/\");\n\treturn joined.replace(/\\/+/g, \"/\").replace(/^\\/+/, \"\").replace(/\\/+$/, \"\") as Valid;\n}\n\n/** Split a path into its slash-separated parts. The empty path has no parts. */\nexport function parts(path: Valid): string[] {\n\treturn path === \"\" ? [] : path.split(\"/\");\n}\n\n/**\n * Validate an untrusted wire string as a path, enforcing {@link MAX_PARTS}.\n *\n * Throws when the path has too many parts; use at wire decode sites.\n */\nexport function decode(raw: string): Valid {\n\tconst path = from(raw);\n\treturn encode(path);\n}\n\n/**\n * Validate a path before writing it to the wire, enforcing {@link MAX_PARTS}.\n *\n * Throws when the path has too many parts; use at wire encode sites so we never\n * emit a path the remote side is required to reject.\n */\nexport function encode(path: Valid): Valid {\n\t// Count separators with an early exit instead of splitting, so a hostile path never allocates per part.\n\tlet count = path === \"\" ? 0 : 1;\n\tfor (let i = path.indexOf(\"/\"); i !== -1; i = path.indexOf(\"/\", i + 1)) {\n\t\tif (++count > MAX_PARTS) {\n\t\t\tthrow new Error(`path exceeds ${MAX_PARTS} parts`);\n\t\t}\n\t}\n\treturn path;\n}\n\n/**\n * Check if a path has the given prefix, respecting path boundaries.\n *\n * Unlike String.startsWith, this ensures that \"foo\" does not match \"foobar\".\n * The prefix must either:\n * - Be exactly equal to the path\n * - Be followed by a '/' delimiter in the original path\n * - Be empty (matches everything)\n *\n * @example\n * ```typescript\n * const path = Path.from(\"foo/bar\");\n * console.log(Path.hasPrefix(Path.from(\"foo\"), path)); // true\n * console.log(Path.hasPrefix(Path.from(\"foo/\"), path)); // true (trailing slash ignored)\n * console.log(Path.hasPrefix(Path.from(\"fo\"), path)); // false\n *\n * const path2 = Path.from(\"foobar\");\n * console.log(Path.hasPrefix(Path.from(\"foo\"), path2)); // false\n * ```\n */\nexport function hasPrefix(prefix: Valid, path: Valid): boolean {\n\tif (prefix === \"\") {\n\t\treturn true;\n\t}\n\n\tif (!path.startsWith(prefix)) {\n\t\treturn false;\n\t}\n\n\t// Check if the prefix is the exact match\n\tif (path.length === prefix.length) {\n\t\treturn true;\n\t}\n\n\t// Otherwise, ensure the character after the prefix is a delimiter\n\treturn path[prefix.length] === \"/\";\n}\n\n/**\n * Strip the given prefix from a path, returning the suffix.\n *\n * Returns null if the prefix doesn't match according to hasPrefix rules.\n *\n * @example\n * ```typescript\n * const path = Path.from(\"foo/bar/baz\");\n * const suffix = Path.stripPrefix(Path.from(\"foo\"), path);\n * console.log(suffix); // \"bar/baz\"\n *\n * const suffix2 = Path.stripPrefix(Path.from(\"foo/\"), path);\n * console.log(suffix2); // \"bar/baz\"\n *\n * const noMatch = Path.stripPrefix(Path.from(\"notfound\"), path);\n * console.log(noMatch); // null\n * ```\n */\nexport function stripPrefix(prefix: Valid, path: Valid): Valid | null {\n\tif (!hasPrefix(prefix, path)) {\n\t\treturn null;\n\t}\n\n\t// Handle empty prefix case\n\tif (prefix === \"\") {\n\t\treturn path;\n\t}\n\n\t// If prefix matches exactly, return empty\n\tif (path.length === prefix.length) {\n\t\treturn \"\" as Valid;\n\t}\n\n\t// For non-empty prefix that's shorter, skip the prefix and the following slash\n\treturn path.slice(prefix.length + 1) as Valid;\n}\n\n/**\n * Join two path components together.\n *\n * @example\n * ```typescript\n * const base = Path.from(\"foo\");\n * const joined = Path.join(base, Path.from(\"bar\"));\n * console.log(joined); // \"foo/bar\"\n * ```\n */\nexport function join(path: Valid, other: Valid): Valid {\n\tif (path === \"\") {\n\t\treturn other;\n\t} else if (other === \"\") {\n\t\treturn path;\n\t} else {\n\t\t// Since paths are trimmed, we always need to add a slash\n\t\treturn `${path}/${other}` as Valid;\n\t}\n}\n\n/** The empty path, which is a prefix of every path. */\nexport function empty(): Valid {\n\treturn \"\" as Valid;\n}\n\n/**\n * Normalize a relative path reference: trim leading/trailing slashes, drop empty\n * segments, and drop redundant `.` segments. A reference made only of `.` segments\n * normalizes to `.` because it names the base's parent, while empty names the base.\n * `..` is preserved and only interpreted by {@link resolve}.\n *\n * Mirrors the Rust `path::Relative::new` normalization, so JS and Rust agree\n * byte-for-byte on the stored form. Two callers comparing normalized strings can\n * detect equivalent references while preserving the distinction between `\"\"` and `\".\"`.\n */\nexport function normalizeRelative(rel: string): Relative {\n\tconst raw = rel.split(\"/\");\n\tconst normalized = raw.filter((s) => s !== \"\" && s !== \".\").join(\"/\");\n\n\treturn (normalized === \"\" && raw.includes(\".\") ? \".\" : normalized) as Relative;\n}\n\n/**\n * Resolve a relative path reference against a base path.\n *\n * A non-empty reference replaces the last segment of the base, matching relative URL\n * resolution. `..` segments then pop another segment; other segments are appended.\n * `.` and empty segments are no-ops. Excess `..` once the base is empty is also a no-op\n * (subsequent named segments still append). An empty `rel` returns the base unchanged.\n *\n * Mirrors the Rust `Path::resolve`, used by hang catalogs to express\n * cross-broadcast track references (a rendition's `broadcast` field).\n *\n * @example\n * ```typescript\n * Path.resolve(Path.from(\"a/b/c\"), \"./source\"); // \"a/b/source\"\n * Path.resolve(Path.from(\"a/b\"), \".\"); // \"a\"\n * Path.resolve(Path.from(\"a/b/c\"), \"../source\"); // \"a/source\"\n * ```\n */\nexport function resolve(base: Valid, rel: Relative): Valid {\n\tif (rel === \"\") return base;\n\n\tconst segments = base === \"\" ? [] : base.split(\"/\");\n\tsegments.pop();\n\n\tfor (const seg of rel.split(\"/\")) {\n\t\tif (seg === \"\" || seg === \".\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (seg === \"..\") {\n\t\t\tsegments.pop();\n\t\t} else {\n\t\t\tsegments.push(seg);\n\t\t}\n\t}\n\n\treturn segments.join(\"/\") as Valid;\n}\n\n/**\n * Resolve a relative path, returning `undefined` if it escapes above the root.\n *\n * Unlike {@link resolve}, this distinguishes a valid reference to the empty root\n * path from excess `..` segments. Use it for untrusted catalog references that\n * must not be clamped to the root.\n */\nexport function tryResolve(base: Valid, rel: Relative): Valid | undefined {\n\tif (rel === \"\") return base;\n\n\tconst segments = base === \"\" ? [] : base.split(\"/\");\n\tsegments.pop();\n\n\tfor (const seg of rel.split(\"/\")) {\n\t\tif (seg === \"\" || seg === \".\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (seg === \"..\") {\n\t\t\tif (segments.pop() === undefined) return undefined;\n\t\t} else {\n\t\t\tsegments.push(seg);\n\t\t}\n\t}\n\n\treturn segments.join(\"/\") as Valid;\n}\n\n/**\n * Express `target` relative to `base`: the inverse of {@link resolve}.\n *\n * The result round-trips (`resolve(base, relative(target, base)) === target`) and never\n * walks above the root, so {@link tryResolve} accepts it too.\n *\n * A relative reference replaces the last segment of the base, matching relative URL\n * resolution, so a target nested under the base repeats the base's own last segment.\n *\n * The empty reference names the base itself, so that is what a self-reference returns.\n *\n * Returns `undefined` for a target no reference can name: a path segment may literally be\n * `.` or `..`, which resolution reads as navigation instead of as a name. Only the segments\n * past the shared prefix matter, since the rest are never emitted.\n *\n * Mirrors the Rust `Path::relative`, used to author the cross-broadcast track\n * references a hang catalog carries. Note the argument order: the target comes first,\n * the opposite of Node's `path.relative(from, to)`.\n *\n * @example\n * ```typescript\n * Path.relative(Path.from(\"a/b/c\"), Path.from(\"a/b\")); // \"b/c\"\n * Path.relative(Path.from(\"a/c\"), Path.from(\"a/b\")); // \"c\"\n * Path.relative(Path.from(\"a\"), Path.from(\"a/b\")); // \".\"\n * Path.relative(Path.from(\"a/b\"), Path.from(\"a/b\")); // \"\"\n * Path.relative(Path.from(\"a/..\"), Path.from(\"a/b\")); // undefined\n * ```\n */\nexport function relative(target: Valid, base: Valid): Relative | undefined {\n\t// Only the empty reference can name a base whose last segment is itself `.` or `..`,\n\t// since resolution replaces that segment rather than emitting it.\n\tif (target === base) return \"\" as Relative;\n\n\t// Resolution replaces the base's last segment, so walk from its parent.\n\tconst dir = base === \"\" ? [] : base.split(\"/\");\n\tdir.pop();\n\n\tconst parts = target === \"\" ? [] : target.split(\"/\");\n\n\tlet common = 0;\n\twhile (common < dir.length && common < parts.length && dir[common] === parts[common]) {\n\t\tcommon += 1;\n\t}\n\n\tconst down = parts.slice(common);\n\t// Resolution would walk on these instead of naming them.\n\tif (down.some((part) => part === \".\" || part === \"..\")) return undefined;\n\n\tconst rel = Array(dir.length - common)\n\t\t.fill(\"..\")\n\t\t.concat(down);\n\n\t// An empty reference resolves to the base itself, so name the parent explicitly.\n\treturn (rel.length === 0 ? \".\" : rel.join(\"/\")) as Relative;\n}\n\n/** Path patterns: grammar and algebra owned by `@moq/pattern`. */\nexport {\n\tcompareSpecificity,\n\tInvalidPattern,\n\tPattern,\n\tPatterns,\n\ttype Segment,\n\ttype Specificity,\n} from \"@moq/pattern\";\n"]}
|