diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index 4f8bad7637c..7f8eb1e4ada 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -60,6 +60,7 @@ route.announce(); - **A subscription asks for `ranges`.** Each [range](/concept/moq-lite#subscriptions) starts and ends at an `absolute` group, one `relative` to the latest, or the group containing a `time` (a `Timestamp`), and a reader reads only its own ranges. A read whose ranges all end finishes once every group in them is handed out, dropped, or skipped, as in Rust. A time anchor needs a timed track and `moq-lite-07-wip` over a session. Passing the old `groups` key throws a `TypeError` naming `ranges`; `withRange` only narrows reads locally. - **Hidden paths** stay out of discovery unless the announce request opts in. See [hidden broadcasts](/concept/moq-lite#hidden-broadcasts). - **Authorization is in band.** On moq-lite 07 (opt in with `versions: ["moq-lite-07-wip", "moq-lite-06"]`, listing every fallback you still want), `auth.grant` watches what the relay lets this side publish and subscribe to, and `auth.add(token)` presents another token without reconnecting, returning its `Auth.Credential` at once; `await credential.answered` waits for the peer's AUTH verdict on moq-lite 07, resolves at once on moq-transport, and rejects with `Unsupported` on older moq-lite. Publishing outside the grant closes the connection with `SessionCode.Unauthorized`, naming the path. On moq-lite, a subscription or track listing the grant stops covering resets with `StreamCode.Unauthorized` and the session stays up. On moq-transport, `auth.add(token)` only keeps the token for the requests that name it: a route created with the `Auth.Credential` it returns (`origin.route(path, { auth })`) carries it on that announcement's `PUBLISH_NAMESPACE`; `route.setAuth(other)` renews the request. A `Connection`'s `auth` handle (a getter on a pooled connection, following its URL) outlives its sessions: a token added there is presented on every reconnect and keeps riding the announcements that name it, with no re-add or re-announce. A one-shot session's `auth` ends with it, unless `Connection.connect` was given a `new Auth.Handle()` as `auth`. +- **A reconnecting `Connection` reports the peer's verdict on its tokens.** `await connection.answered()` waits for the first answer to the tokens last set (the initial ones before any set): each is granted in band, or is the connection credential a dial carried and the peer accepted. A token the set kept, the connection credential included, counts only once the peer refuses it, and nothing is re-checked after the answer. It rejects with the peer's refusal, with `Unsupported` when the session cannot carry a token in band, or with the connection's end, or with the failure that stopped it retrying its URL while no session answered, such as a refused first dial. On a version without AUTH, a close before the peer's SETUP is its refusal. An app that re-signs its credential for each dial ends the connection on a refusal by aborting `connection.auth`, which makes the loop give up with that error. - **A graceful close waits.** `await connection.close()` withdraws announcements and drains for up to one second. `moq-lite-05` and newer wait for the subscriber to receive finished tails; older Lite versions wait only for transport ACKs. IETF media streams are not drained. `abort()` ends immediately. Examples: diff --git a/js/net/api/index.api.md b/js/net/api/index.api.md index a2c0525e19c..6fcc565f178 100644 --- a/js/net/api/index.api.md +++ b/js/net/api/index.api.md @@ -241,6 +241,7 @@ export class Connection { static readonly accept: ({ ... }: Connection.AcceptProps) => Promise; readonly allocator: Signals.Getter; announced(scope?: Path.Pattern, options?: Announce.Options): Announce.Consumer; + answered(): Promise; readonly auth: Signals.Getter; static readonly certificateHash: (cert: string | BufferSource) => Promise>; static readonly checkVersions: (versions: readonly string[]) => string[]; diff --git a/js/net/src/auth_session.ts b/js/net/src/auth_session.ts index c6bbd6a3108..41add2ca507 100644 --- a/js/net/src/auth_session.ts +++ b/js/net/src/auth_session.ts @@ -164,6 +164,8 @@ export interface Pending extends Credential { readonly answered: Promise; /** Whether any session holds a grant for it now, a draining one included. */ readonly held: boolean; + /** Whether a peer granted it in band: false for a token only a request carries, which {@link answered} also resolves for. */ + readonly inband: boolean; } /** A token the application added to a {@link Handle}, presented on every session of it. */ @@ -175,6 +177,7 @@ class Token implements Pending { isAnswered = false; ended = false; + inband = false; #state: HandleState; #close!: (err: Error | null) => void; @@ -229,6 +232,8 @@ class HandleState { own = false; /** Set once the handle ends. */ closed?: Error; + /** The handle's end, for a watcher that outlives its sessions. */ + readonly end = new Signal(undefined); /** Every token the application added that has not ended. */ readonly tokens = new Set(); /** Every open session built on this handle, oldest first. */ @@ -307,6 +312,7 @@ class HandleState { abort(err: Error) { if (this.closed) return; this.closed = err; + this.end.set(err); for (const token of [...this.tokens]) this.verdict(token, err); if (this.acceptor instanceof RequestQueue) this.acceptor.close(); } @@ -338,6 +344,15 @@ export function ended(handle: Handle): Error | undefined { return stateOf(handle).closed; } +/** + * When `handle` ends, with why, for a watcher that outlives its sessions. + * + * @internal + */ +export function ending(handle: Handle): Getter { + return stateOf(handle).end; +} + /** * The tokens this side presents and the grant they earn, across every session built on it. * @@ -597,6 +612,11 @@ export interface AuthSessionProps { handle?: Handle; /** Whether the session is draining after a GOAWAY or a local close, which frees its handle for a successor. */ draining?: () => boolean; + /** + * Whether the peer's SETUP, still to come, is what accepts the connection credential: a + * session without AUTH that is live before its peer has checked the credential. + */ + awaiting?: boolean; } /** @@ -631,6 +651,9 @@ export class AuthSession { // #presented by #recount after every change to it or to an `isAnswered`. #setupPending = new Signal(0); #pending = new Signal(0); + // The peer's verdict on the connection credential this session presented: null once accepted, + // the refusal, or undefined while it has none. + #credential = new Signal(undefined); #closed = false; // Whoever answers the peer's tokens is decided once, after the task that established @@ -639,7 +662,7 @@ export class AuthSession { #decided = yieldNow(); /** Throws {@link Duplicate} while `handle` backs another active session, or the handle's end. */ - constructor({ wire, requests, peerGrant, handle, draining }: AuthSessionProps) { + constructor({ wire, requests, peerGrant, handle, draining, awaiting }: AuthSessionProps) { this.handle = handle ?? ownHandle(); this.#state = stateOf(this.handle); this.#wire = wire; @@ -647,6 +670,8 @@ export class AuthSession { this.#peerGrant = peerGrant; this.#draining = draining ?? (() => false); this.#state.attach(this); + // A session without AUTH has the peer's acceptance with its handshake, unless it awaits its SETUP. + if (!wire && !awaiting) this.#credential.set(null); // Present the connection's own credential right away, so both sides learn their // grant without waiting on the app. @@ -659,6 +684,20 @@ export class AuthSession { return !this.#closed && !this.#draining(); } + /** + * The peer's verdict on the connection credential this session presented: `null` once it + * accepted it, its refusal, or undefined while it has none, which the session ending leaves + * to the session's own close. + */ + get credential(): Getter { + return this.#credential; + } + + /** The peer's SETUP arrived, so it accepted the connection credential a session without AUTH presented. */ + accepted(): void { + if (!this.#wire) this.#credential.set(null); + } + /** The union of this session's grants, undefined until its peer first answers. */ get grant(): Getter { return this.#union; @@ -917,6 +956,7 @@ export class AuthSession { answered = granted = replied = true; delay = undefined; this.#replied = true; + if (presented.setup) this.#credential.set(null); this.#answered(presented); this.#recompute(); continue; @@ -991,6 +1031,13 @@ export class AuthSession { // Already ended by the session's close. if (presented.ended) return; + // The peer's verdict on the credential: Unsupported is the moq-transport SETUP that + // carried it accepting it before the peer declined AUTH. Anything else leaves it to the close. + if (presented.setup && !presented.withdrawn && isVerdict(refused, granted, result)) { + this.#credential.set( + result instanceof Unsupported ? null : (result ?? new Error("the peer ended the credential")), + ); + } presented.ended = true; presented.grant = undefined; // A token that ends unanswered counts as answered for enforcement: its refusal is @@ -1024,6 +1071,7 @@ export class AuthSession { /** The peer granted `presented`: it counts as answered, and so does the handle's token. */ #answered(presented: Presented) { presented.isAnswered = true; + if (presented.owner) presented.owner.inband = true; presented.owner?.answer(); } diff --git a/js/net/src/connection/answered.test.ts b/js/net/src/connection/answered.test.ts new file mode 100644 index 00000000000..b2c42ecb461 --- /dev/null +++ b/js/net/src/connection/answered.test.ts @@ -0,0 +1,270 @@ +import { expect, test } from "bun:test"; +import { Duration } from "@moq/clock"; +import { Signal } from "@moq/signals"; +import type { Request } from "../auth.ts"; +import { SessionCode, SessionError } from "../error.ts"; +import * as Lite from "../lite/index.ts"; +import { createMockTransportPair, manual, waitFor } from "../mock.ts"; +import * as Path from "../path.ts"; +import { wireOf } from "../wire.ts"; +import { accept as acceptSession } from "./index.ts"; +import { Connection } from "./pool.ts"; +import { Reload } from "./reload.ts"; + +const URL_ = new URL("https://example.com/"); +const DELAY = { initial: Duration.millis(1), multiplier: 2, max: Duration.millis(1), timeout: null }; + +/** The token a server's request carries as text, where the connection's own credential is "connection". */ +function named(request: Request): string { + return request.token.byteLength === 0 ? "connection" : new TextDecoder().decode(request.token); +} + +/** Grants everything and refuses nothing. */ +const GRANT = { publish: new Path.Patterns([Path.Pattern.all()]), subscribe: new Path.Patterns() }; + +/** + * A lite-07 relay that answers each token itself: `decide` accepts or rejects the request, and + * may hold it, such as a token a test answers later. + */ +function relay(decide: (token: string, request: Request) => void) { + const stub = function StubWebTransport(target: string | URL) { + const pair = createMockTransportPair(Lite.ALPN_07_WIP); + void acceptSession({ transport: pair.server, url: new URL(target) }).then(async (session) => { + const requests = session.auth.requests(); + for (;;) { + const request = await requests.next(); + if (!request) break; + decide(named(request), request); + } + }); + return pair.client; + }; + return stub as unknown as typeof WebTransport; +} + +/** + * A lite-06 relay, which has no AUTH: it accepts any credential but `refused`, whose session it + * closes once `release` resolves, before its SETUP. + */ +function closing(refused: string, release: Promise) { + const stub = function StubWebTransport(target: string | URL) { + const pair = createMockTransportPair(Lite.ALPN_06); + const url = new URL(target); + if (url.searchParams.get("jwt") === refused) { + void release.then(() => pair.server.close({ closeCode: SessionCode.Unauthorized, reason: "unauthorized" })); + } else { + void acceptSession({ transport: pair.server, url }); + } + return pair.client; + }; + return stub as unknown as typeof WebTransport; +} + +function loop(versions: string[], tokens: Signal) { + return new Reload({ url: URL_, versions, websocket: { enabled: false }, tokens, delay: DELAY }); +} + +/** Whether `promise` rejected with a session close of `code`, once everything pending has run. */ +async function refusal(promise: Promise): Promise { + try { + await promise; + } catch (err) { + return err instanceof SessionError ? err : undefined; + } + return undefined; +} + +/** Whether `promise` rejected, once everything pending has run. */ +async function rejection(promise: Promise): Promise { + let rejected = false; + try { + await promise; + } catch { + rejected = true; + } + expect(rejected).toBe(true); +} + +test("a set granted in band answers, and a later set the peer refuses answers with its refusal", async () => { + using clock = manual(); + const original = globalThis.WebTransport; + globalThis.WebTransport = relay((token, request) => { + if (token === "revoked") request.reject(SessionCode.Unauthorized, "no"); + else request.accept(GRANT); + }); + const tokens = new Signal(["connection", "a"]); + const reload = loop(["moq-lite-07-wip"], tokens); + try { + await clock.drive(reload.answered()); + + tokens.set(["connection", "revoked"]); + const err = await clock.drive(refusal(reload.answered())); + expect(err?.code).toBe(SessionCode.Unauthorized); + } finally { + reload.close(); + globalThis.WebTransport = original; + } +}); + +test("a close that refuses the connection credential answers a session without AUTH", async () => { + using clock = manual(); + const original = globalThis.WebTransport; + const { promise: release, resolve } = Promise.withResolvers(); + globalThis.WebTransport = closing("old", release); + const tokens = new Signal(["old"]); + const reload = loop(["moq-lite-06"], tokens); + try { + await clock.drive(waitFor(reload.established, (established) => established !== undefined)); + // A session that stayed up past the healthy bar, so its close is retried rather than ending the URL. + await clock.advance(Duration.millis(1500)); + const waiting = refusal(reload.answered()); + resolve(); + const err = await clock.drive(waiting); + expect(err?.code).toBe(SessionCode.Unauthorized); + + // The replacement is accepted by the server's SETUP, which is the answer without AUTH. + tokens.set(["new"]); + await clock.drive(reload.answered()); + } finally { + reload.close(); + globalThis.WebTransport = original; + } +}); + +test("a kept credential counts only once the peer refuses it", async () => { + using clock = manual(); + const original = globalThis.WebTransport; + const issued: { revoke(code: SessionCode, reason: string): void }[] = []; + globalThis.WebTransport = relay((token, request) => { + const grant = request.accept(GRANT); + if (token === "connection") issued.push(grant); + }); + const tokens = new Signal(["connection", "a", "b"]); + const reload = loop(["moq-lite-07-wip"], tokens); + try { + await clock.drive(reload.answered()); + + // Nothing new to grant, and the credential still stands. + tokens.set(["connection", "a"]); + await clock.drive(reload.answered()); + + issued[0]?.revoke(SessionCode.Unauthorized, "removed"); + const session = reload.established.peek(); + if (!session) throw new Error("not connected"); + await clock.drive(waitFor(wireOf(session).auth.credential, (verdict) => verdict instanceof Error)); + tokens.set(["connection"]); + const err = await clock.drive(refusal(reload.answered())); + expect(err?.code).toBe(SessionCode.Unauthorized); + } finally { + reload.close(); + globalThis.WebTransport = original; + } +}); + +test("a kept credential the peer ends cleanly after granting it refuses the next set", async () => { + using clock = manual(); + const original = globalThis.WebTransport; + const issued: { close(): void }[] = []; + globalThis.WebTransport = relay((token, request) => { + const grant = request.accept(GRANT); + if (token === "connection") issued.push(grant); + }); + const tokens = new Signal(["connection", "a"]); + const reload = loop(["moq-lite-07-wip"], tokens); + try { + await clock.drive(reload.answered()); + + issued[0]?.close(); + const session = reload.established.peek(); + if (!session) throw new Error("not connected"); + await clock.drive(waitFor(wireOf(session).auth.credential, (verdict) => verdict instanceof Error)); + + // The set keeps the dropped credential, so it is refused rather than answered by "b" alone. + tokens.set(["connection", "b"]); + await clock.drive(rejection(reload.answered())); + } finally { + reload.close(); + globalThis.WebTransport = original; + } +}); + +test("a set replaced before its answer moves the wait to the replacement", async () => { + using clock = manual(); + const original = globalThis.WebTransport; + globalThis.WebTransport = relay((token, request) => { + // "slow" is never answered. + if (token !== "slow") request.accept(GRANT); + }); + const tokens = new Signal(["connection"]); + const reload = loop(["moq-lite-07-wip"], tokens); + try { + await clock.drive(reload.answered()); + + tokens.set(["connection", "slow"]); + let answered = false; + const waiting = reload.answered().then(() => { + answered = true; + }); + await clock.advance(Duration.millis(10)); + expect(answered).toBe(false); + + tokens.set(["connection", "fast"]); + await clock.drive(waiting); + expect(answered).toBe(true); + } finally { + reload.close(); + globalThis.WebTransport = original; + } +}); + +test("a connection answers once its loop ends with the abort's error", async () => { + using clock = manual(); + const original = globalThis.WebTransport; + globalThis.WebTransport = relay((token, request) => { + if (token !== "slow") request.accept(GRANT); + }); + const tokens = new Signal(["connection", "slow"]); + const connection = new Connection({ + url: URL_, + versions: ["moq-lite-07-wip"], + websocket: { enabled: false }, + tokens, + delay: DELAY, + }); + try { + await clock.advance(Duration.millis(10)); + const waiting = refusal(connection.answered()); + connection.auth.peek()?.abort(new SessionError(SessionCode.Unauthorized)); + const err = await clock.drive(waiting); + expect(err?.code).toBe(SessionCode.Unauthorized); + } finally { + connection.close(); + globalThis.WebTransport = original; + } +}); + +test("a first dial the peer refuses answers with its failure", async () => { + using clock = manual(); + const original = globalThis.WebTransport; + // Closed before the handshake finishes, so the dial never yields a session. + globalThis.WebTransport = function StubWebTransport() { + const pair = createMockTransportPair(Lite.ALPN_06); + pair.server.close({ closeCode: SessionCode.Unauthorized, reason: "unauthorized" }); + return pair.client; + } as unknown as typeof WebTransport; + const reload = loop(["moq-lite-06"], new Signal(["old"])); + try { + const err = await clock.drive(refusal(reload.answered())); + expect(err?.code).toBe(SessionCode.Unauthorized); + } finally { + reload.close(); + globalThis.WebTransport = original; + } +}); + +test("releasing a connection that holds no loop ends its wait", async () => { + const connection = new Connection({ tokens: ["old"] }); + const waiting = connection.answered(); + connection.close(); + await expect(waiting).rejects.toThrow("connection closed"); +}); diff --git a/js/net/src/connection/pool.ts b/js/net/src/connection/pool.ts index c5f66c166c7..f28f418ea28 100644 --- a/js/net/src/connection/pool.ts +++ b/js/net/src/connection/pool.ts @@ -232,6 +232,7 @@ export class Connection { readonly #allocator = new Signal(undefined); readonly #viewers = new Signal | undefined>(undefined); readonly #auth = new Signal(undefined); + readonly #loop = new Signal(undefined); readonly #error = new Signal(undefined); #signals: Effect; @@ -289,6 +290,7 @@ export class Connection { effect.set(this.#allocator, lease.connection.allocator, undefined); effect.set(this.#viewers, lease.connection.viewers, undefined); effect.set(this.#auth, lease.connection.auth, undefined); + effect.set(this.#loop, lease.connection, undefined); // Proxy the shared loop's outputs, so this handle reads like its own connection. effect.run((nested) => nested.set(this.#status, nested.get(lease.connection.status), "disconnected")); @@ -341,6 +343,7 @@ export class Connection { effect.set(this.#allocator, loop.allocator, undefined); effect.set(this.#viewers, loop.viewers, undefined); effect.set(this.#auth, loop.auth, undefined); + effect.set(this.#loop, loop, undefined); }); signals.run((effect) => effect.set(this.#status, effect.get(loop.status), "disconnected")); signals.run((effect) => effect.set(this.#established, effect.get(loop.established), undefined)); @@ -397,6 +400,43 @@ export class Connection { return this.#established.peek()?.stats(); } + /** + * Resolve once the peer first answers the latest {@link ConnectionProps.tokens}, as Rust's + * `Tokens::poll_answered` does: each token the latest set newly presented, or the initial + * ones before any set, is granted in band, or is the connection credential a dial carried and + * the peer accepted. A token the set kept, the connection credential included, counts only + * once the peer refuses it, and nothing is re-checked after the answer. A set replaced before + * its answer moves the wait to the new one, and a connection with no tokens answers at once. + * + * An app that re-signs its credential for each dial can end the connection on a refusal by + * aborting its {@link auth} handle, which makes the loop give up with that error. + * + * Waits while no connection is held, such as before a URL is set. + * + * @throws The peer's refusal, an `Unsupported` error when the session cannot carry a token in + * band, the connection's end such as an abort of its auth handle, or the failure that stopped + * it retrying its URL while no session answered, such as a refused first dial. + */ + async answered(): Promise { + for (;;) { + const closed = this.#closed.peek(); + if (closed !== undefined) throw closed ?? new Error("connection closed"); + const loop = this.#loop.peek(); + // A new loop, such as one a version change built, restarts the wait. + const { promise: moved, resolve } = Promise.withResolvers<"moved">(); + const stop = this.#loop.changed(() => resolve("moved")); + // Closing this handle ends the wait, even with no loop to notice. + const closing = this.#closed.changed(() => resolve("moved")); + try { + const answered = loop?.answered().then(() => "answered" as const); + if ((await Promise.race(answered ? [answered, moved] : [moved])) === "answered") return; + } finally { + stop(); + closing(); + } + } + } + /** * Release this handle. The shared connection drains and closes once its last handle is * gone and the linger window passes; other handles on the URL are unaffected. Idempotent. diff --git a/js/net/src/connection/reload.ts b/js/net/src/connection/reload.ts index c040a34842a..90f5e77c788 100644 --- a/js/net/src/connection/reload.ts +++ b/js/net/src/connection/reload.ts @@ -25,7 +25,7 @@ import { DEFAULT_HANDOVER, dialed, type Goaway, type Handover, handover, pinnedT import type { Session } from "./session.ts"; import { estimates, type Probe } from "./stats.ts"; import { tick } from "./ticker.ts"; -import { heldOf } from "./tokens.ts"; +import { heldOf, Verdict } from "./tokens.ts"; /** * The wait before a session on the WebSocket fallback first probes WebTransport, before jitter. @@ -272,6 +272,9 @@ export class Reload { */ readonly auth = new AuthHandle(); + // The peer's verdict on the latest tokens, across reconnects. + readonly #verdict: Verdict; + /** Protocol versions to offer, most preferred first, kept across retries and redirects. */ readonly versions?: readonly string[]; @@ -392,6 +395,7 @@ export class Reload { this.url = Signal.from(props?.url); this.enabled = Signal.from(props?.enabled ?? true); this.tokens = Signal.from(props?.tokens ?? []); + this.#verdict = new Verdict(this.tokens, this.auth); this.delay = props?.delay ?? {}; // Validated here, like the timeout, rather than by every retry. pacing(this.delay); @@ -488,6 +492,8 @@ export class Reload { // The live session holds the current tokens on AUTH; a dial picks them up itself. this.#signals.run((effect) => { const tokens = effect.get(this.tokens); + // Before the held tokens change, so a token the set kept is judged by what it was. + this.#verdict.refresh(); const connection = effect.get(this.established); if (connection) heldOf(connection)?.update(tokens); }); @@ -578,6 +584,7 @@ export class Reload { this.#deadline ??= this.#window(now()); this.#setDialing(true); + this.#verdict.dialing(); const tokens = reached?.tokens ?? this.tokens.peek(); let connection: Session; const reusing = reached; @@ -615,6 +622,7 @@ export class Reload { return; } current = connection; + this.#verdict.connected(connection); // The replacement serves now; a predecessor keeps draining its groups in flight. this.#serve(connection); @@ -1001,6 +1009,7 @@ export class Reload { } #giveUp(cause: Error): void { + this.#verdict.gaveUp(cause); this.#error.set(cause); this.#givenUpHref = this.#sequenceHref; this.#resetSequence(); @@ -1014,6 +1023,21 @@ export class Reload { this.#retire(); } + /** + * Resolve once the peer first answers the latest {@link tokens}, like Rust's `Tokens::poll_answered`. + * + * It covers the tokens the latest set newly presented, or the initial ones before any set: + * each is granted in band, or is the connection credential a dial carried and the peer + * accepted. A token the set kept, the connection credential included, counts only once the + * peer refuses it, and nothing is re-checked after the answer. Rejects with the peer's refusal, + * `Unsupported` when a session cannot carry a token in band, the loop's end, or the failure that + * stopped it retrying its URL while no session answered, such as a refused first dial. A set replaced + * before its answer moves the wait to the new one. + */ + answered(): Promise { + return this.#verdict.answered(); + } + /** Stop reconnecting, drain and close the current connection, and settle {@link Reload.closed}. Idempotent. */ close(abort?: Error) { this.#signals.close(); diff --git a/js/net/src/connection/tokens.test.ts b/js/net/src/connection/tokens.test.ts index e5a5a73988a..759e88f9640 100644 --- a/js/net/src/connection/tokens.test.ts +++ b/js/net/src/connection/tokens.test.ts @@ -62,7 +62,13 @@ function handle() { const fake = { present(token: string) { presented.push(token); - const pending = { held: false, answered: Promise.resolve(), close: () => closed.push(token) }; + const pending = { + held: false, + inband: true, + answered: Promise.resolve(), + closed: new Promise(() => {}), + close: () => closed.push(token), + }; pending.answered = new Promise((resolve) => answers.set(token, () => { pending.held = true; diff --git a/js/net/src/connection/tokens.ts b/js/net/src/connection/tokens.ts index 2ddb72f9599..57829193557 100644 --- a/js/net/src/connection/tokens.ts +++ b/js/net/src/connection/tokens.ts @@ -1,5 +1,8 @@ +import { type Getter, Signal } from "@moq/signals"; import { type Handle, Unsupported } from "../auth.ts"; -import type { Pending } from "../auth_session.ts"; +import { ending, type Pending } from "../auth_session.ts"; +import { error } from "../error.ts"; +import { wireOf } from "../wire.ts"; import type { Session } from "./session.ts"; /** What one dial presents, decided from its URL, the offered versions, and the tokens. @internal */ @@ -61,6 +64,10 @@ interface Entry { pending: boolean; /** Withdrawn by us, so its rejected answer is no refusal. */ withdrawn: boolean; + /** The peer's first verdict: `null` once granted, its refusal, or undefined while unanswered. */ + answer?: Error | null; + /** Why the peer ended the token for good: its refusal or revocation, or the handle's end. */ + end?: Error; } /** @@ -78,12 +85,45 @@ export class Held { #credential: Presentation; #entries = new Map(); #retiring: Entry[] = []; + #changed = new Signal(0); constructor(handle: Handle, credential: Presentation) { this.#handle = handle; this.#credential = credential; } + /** Bumps whenever a held token is answered or ends. */ + get changed(): Signal { + return this.#changed; + } + + /** The credential the latest dial presented as the connection's, which no AUTH stream carries. */ + get connection(): string | undefined { + return this.#credential.connection; + } + + /** Whether `token` rides its own AUTH stream. */ + has(token: string): boolean { + return this.#entries.has(token); + } + + /** + * The peer's first verdict on held `token`: `null` once granted in band, its refusal, or + * undefined while it has none. A token only a request carries is unsupported, not granted. + */ + verdict(token: string): Error | null | undefined { + return this.#entries.get(token)?.answer; + } + + /** Why the peer ended the first of `tokens` that is held, for good. */ + ended(tokens: readonly string[]): Error | undefined { + for (const token of tokens) { + const end = this.#entries.get(token)?.end; + if (end) return end; + } + return undefined; + } + /** A new dial on the handle, whose credential decides which tokens ride AUTH. */ dialed(credential: Presentation, tokens: readonly string[]) { this.#credential = credential; @@ -121,13 +161,32 @@ export class Held { auth = this.#handle.present(token); } catch (err) { refused(err); + entry.answer = error(err); + entry.end = entry.answer; entry.pending = false; return entry; } entry.auth = auth; - auth.answered.catch(refused).finally(() => { - entry.pending = false; - this.#settle(); + auth.answered + .then( + () => { + entry.answer = auth.inband ? null : new Unsupported(); + }, + (err: unknown) => { + entry.answer = error(err); + refused(err); + }, + ) + .finally(() => { + entry.pending = false; + this.#changed.update((n) => n + 1); + this.#settle(); + }); + // Withdrawn by us, it ends with no verdict of the peer's. + void auth.closed.then((end) => { + if (entry.withdrawn) return; + entry.end = end ?? new Error("the peer ended the token"); + this.#changed.update((n) => n + 1); }); return entry; } @@ -165,3 +224,202 @@ export function hold(connection: Session, credential: Presentation, tokens: read export function heldOf(connection: Session): Held | undefined { return held.get(connection.auth); } + +/** The latest dial's session, whose own answer to the connection credential counts. */ +interface Connected { + credential: Getter; + /** Why the session closed, once it did. */ + closed?: Error; +} + +/** + * The peer's verdict on the tokens a connection last set, across its reconnects, like Rust's + * `Tokens::poll_answered`. + * + * It covers the tokens the latest set newly presented, or the initial ones before any set: each + * is granted in band, or is the connection credential a dial carried and the peer accepted. + * A token the set kept, the connection credential included, counts only once the peer refuses + * it. The first verdict is the answer, and nothing is re-checked after it: a later revocation, or + * a new session that refuses a token an earlier one granted, changes nothing. + * + * @internal + */ +export class Verdict { + #source: Getter; + #tokens: readonly string[]; + // The tokens the latest set newly presented whose verdict is not yet known. + #fresh: string[]; + // The first verdict on the latest set: null once granted. + #latched?: { outcome: Error | null }; + // The connection credential the latest dial presented, once it connected. + #dialed?: string; + #connected?: Connected; + #held?: Held; + // Why the loop ended, which answers a set no session will. + #closed?: Error; + // Why the loop stopped retrying its URL, such as a refused first dial: no session will answer + // until a new sequence dials, so a waiting set fails with it, but it is no verdict to latch. + #gaveUp?: Error; + // Bumped whenever an input changes, so a waiting answer looks again. + #epoch = new Signal(0); + #stops: (() => void)[] = []; + // Stops watching the latest session's credential. + #unwatch?: () => void; + + constructor(source: Getter, handle: Handle) { + this.#source = source; + this.#tokens = source.peek(); + this.#fresh = [...new Set(this.#tokens)]; + this.#stops.push( + ending(handle).subscribe((err) => { + if (err) this.#end(err); + }), + ); + } + + /** Resolve once the peer first answers the latest set: rejects with its refusal, `Unsupported` when a session cannot carry a token in band, or the connection's end. */ + async answered(): Promise { + for (;;) { + this.#sync(); + this.#record(); + if (this.#latched) { + if (this.#latched.outcome) throw this.#latched.outcome; + return; + } + if (this.#gaveUp) throw this.#gaveUp; + await this.#epoch.changed(); + } + } + + /** A dial starts: its session answers the connection credential from here, so the last one's answer is kept first. */ + dialing(): void { + this.#sync(); + this.#record(); + this.#gaveUp = undefined; + this.#dialed = undefined; + this.#connected = undefined; + this.#release(); + this.#notify(); + } + + /** The latest dial built `session`, even one that already closed: that close may be its answer. */ + connected(session: Session): void { + this.#sync(); + this.#record(); + this.#release(); + const held = heldOf(session); + if (held && held !== this.#held) this.#stops.push(held.changed.subscribe(() => this.#notify())); + this.#held = held; + this.#dialed = held?.connection; + const connected: Connected = { credential: wireOf(session).auth.credential }; + this.#connected = connected; + this.#unwatch = connected.credential.subscribe(() => this.#notify()); + void session.closed.then((end) => { + // The close is the answer of a session still unanswered: the loop redials with the same credential. + connected.closed = end ?? new Error("the session closed before the peer accepted its credential"); + if (this.#connected === connected) this.#notify(); + }); + this.#notify(); + } + + /** The loop stopped retrying its URL with `err`, which fails a set still waiting for a session. */ + gaveUp(err: Error): void { + this.#gaveUp = err; + this.#notify(); + } + + /** The tokens the source holds may have changed, such as a set the effect has yet to see. */ + refresh(): void { + this.#notify(); + } + + /** The loop ended with `err`, which answers a set no session will. */ + #end(err: Error): void { + this.#sync(); + this.#record(); + this.#closed ??= err; + this.#release(); + for (const stop of this.#stops.splice(0)) stop(); + this.#notify(); + } + + /** Take the tokens the source holds now, before an effect would have. */ + #sync(): void { + const tokens = this.#source.peek(); + if (tokens === this.#tokens || sameTokens(tokens, this.#tokens)) return; + const kept = new Set(this.#tokens); + // A token still waiting on its verdict stays fresh when the new set keeps it. + const fresh = [...new Set(tokens)].filter( + (token) => !kept.has(token) || (this.#fresh.includes(token) && this.#verdict(token) === undefined), + ); + this.#fresh = fresh; + this.#tokens = tokens; + this.#latched = undefined; + } + + #release(): void { + this.#unwatch?.(); + this.#unwatch = undefined; + } + + #notify(): void { + this.#sync(); + this.#record(); + this.#epoch.update((n) => n + 1); + } + + /** The connection credential the latest dial presented, when the tokens still name it. */ + #named(): string | undefined { + const connection = this.#dialed; + return connection !== undefined && this.#tokens.includes(connection) ? connection : undefined; + } + + /** The peer's verdict on the connection credential: `null` once accepted, undefined while it has none or no session is live. */ + #credential(): Error | null | undefined { + const connected = this.#connected; + if (!connected) return undefined; + // A session closed before the peer answered is cut off: its close is the answer. + const own = connected.credential.peek(); + return own !== undefined ? own : connected.closed; + } + + /** The peer's verdict on `token` of the latest set, undefined while it has none. */ + #verdict(token: string): Error | null | undefined { + if (this.#held?.has(token)) return this.#held.verdict(token); + // Not presented until the first dial. + return this.#named() === token ? this.#credential() : undefined; + } + + /** The answer to the latest set: the first refusal of any token it names, or `null` once every fresh token is granted. Undefined while one still waits. */ + #answer(): Error | null | undefined { + if (this.#latched) return this.#latched.outcome; + if (this.#closed) return this.#closed; + const ended = this.#held?.ended(this.#tokens); + if (ended) return ended; + const credential = this.#named() === undefined ? undefined : this.#credential(); + if (credential) return credential; + let waiting = false; + for (const token of this.#fresh) { + const verdict = this.#verdict(token); + if (verdict) return verdict; + if (verdict === undefined) waiting = true; + } + return waiting ? undefined : null; + } + + /** Keep each verdict the latest set has so far, before a dial, a new session, or a dropped one takes away where it came from. */ + #record(): void { + if (this.#latched) return; + const outcome = this.#answer(); + if (outcome !== undefined) { + if (outcome === null) this.#fresh = []; + this.#latched = { outcome }; + return; + } + this.#fresh = this.#fresh.filter((token) => this.#verdict(token) !== null); + } +} + +function sameTokens(a: readonly string[], b: readonly string[]): boolean { + return a.length === b.length && a.every((token, i) => token === b[i]); +} diff --git a/js/net/src/lite/connection.ts b/js/net/src/lite/connection.ts index 567c614678b..c24f2118df2 100644 --- a/js/net/src/lite/connection.ts +++ b/js/net/src/lite/connection.ts @@ -229,6 +229,8 @@ export class Connection implements Session { }, handle, draining: () => this.#goaway.peek() !== undefined || this.#phase.kind !== "open", + // Without AUTH, the server checks a client's credential before its SETUP, which the client reads after going live. + awaiting: client && hasSetupStream(version) && !hasAuth(version), }); // Left before anything observes the close, so a successor on the same handle never // finds this session still active. @@ -608,6 +610,7 @@ export class Connection implements Session { if (!this.#client && setup.path !== undefined) throw new ProtocolViolation("Path on a URI-carrying binding"); this.#peerSetup.set(setup); + this.#auth.accepted(); this.#peerRole.set(setup.role); this.#peerImplementation.resolve(setup.implementation); } else { diff --git a/quest/m1/js-tokens-answered.md b/quest/m1/js-tokens-answered.md deleted file mode 100644 index 6da9d547143..00000000000 --- a/quest/m1/js-tokens-answered.md +++ /dev/null @@ -1,45 +0,0 @@ -# [S] JS learns the verdict on its connection credential - -## Goal - -A reconnecting JS `Connection` tells the app the peer's verdict on the -tokens it last set, as Rust's `Tokens::poll_answered` does: granted, or the -peer's refusal, a close that refuses the connection credential included. An -app that re-signs its credential for each dial, such as kixel.ai's `Device`, -can then end the connection when a device that was live is removed or -revoked. Non-goals: changing when the loop retries -([moq-dev/moq#8618](https://github.com/moq-dev/moq/pull/8618) keeps -retrying a refusal after a healthy session, and -[moq-dev/moq#8817](https://github.com/moq-dev/moq/pull/8817) ends only a first -session refused before it is healthy), and in-band AUTH retry hints -([moq-dev/moq#8836](https://github.com/moq-dev/moq/pull/8836)). - -## Plan - -Decided 2026-11-15 (maintainer, `/quest-plan` from kixel.ai's `/quest-run`, -for kixel.ai's `quest/m0/mesh/refused.md`): ✅ JS parity with Rust's -`Tokens` verdict (rejected: no moq quest, relying on first-dial-refusal -alone, which leaves a removed live device redialing forever; changing the -retry policy, which reverses #8618). - -JS already replaces the tokens (`Reload.tokens`, a `Signal`, presented at -once on a live session with AUTH and by every later dial), but exposes no -verdict: `Connection` hides its sessions, and a refused redial leaves the -grant undefined, so the app cannot tell a refusal from a drop. - -Recommended shape, settled with its consumer: the reconnecting connection -exposes the verdict on the latest `tokens` set, mirroring -`Tokens::poll_answered` (`rs/moq-net/src/auth/tokens.rs`) rule for rule. A -token the set kept, the connection credential included, counts only once -the peer refuses it, and nothing is re-checked after the answer. The session -the latest dial built counts its close as the answer when that close refuses -the connection credential, on versions without AUTH too. The app ends the -loop by aborting its auth handle, which already makes the loop give up with -that error. - -Tests, beside `js/net/src/connection/tokens.test.ts` and `reload.test.ts`: a -set granted in band on lite-07, a set refused by a closing session on a -version without AUTH, a kept credential that counts only on refusal, and a -set replaced before its answer. - -Public API: an addition to `@moq/net`'s `Connection`. Wire: none.