@sirosfoundation/wmp-js 0.5.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/peer.js CHANGED
@@ -7,10 +7,10 @@
7
7
  */
8
8
  import { isRequest, isResponse, isNotification, createRequest, createNotification, createResponse, createErrorResponse, WMPError, } from "./jsonrpc.js";
9
9
  import { Registry, } from "./profile.js";
10
+ import { CompletionResultError, dcqlQueryIds, validateCompletionResult, validateMatchResult } from "./completion.js";
11
+ import { unsupportedError } from "./errors.js";
12
+ import { SUPPORTED_VERSIONS, negotiateVersion, parseVersion, versionRejection } from "./version.js";
10
13
  import { ErrorCode, Method, VERSION, } from "./types.js";
11
- // ---------------------------------------------------------------------------
12
- // Peer
13
- // ---------------------------------------------------------------------------
14
14
  export class Peer {
15
15
  transport;
16
16
  handler;
@@ -23,22 +23,244 @@ export class Peer {
23
23
  closed = false;
24
24
  validator;
25
25
  authorize;
26
+ validateCompletions;
27
+ onRefusedCompletion;
28
+ onSessionLost;
29
+ supportedVersions;
30
+ /**
31
+ * Capabilities negotiated for a session, bound to that session's ID; undefined
32
+ * until known or after the session ends (gating then fails closed).
33
+ */
34
+ negotiated;
35
+ /**
36
+ * Revision of the cached grant: bumped whenever it changes. An operation that
37
+ * obtains a grant snapshot over an RPC (capability list/update, resume) notes
38
+ * the revision when it starts; if the grant changed meanwhile the snapshot may
39
+ * be older than what is cached, so it can only NARROW the grant (never widen
40
+ * it): a revocation is never undone by a late answer, and no lock is held
41
+ * across the RPC.
42
+ */
43
+ capRev = 0;
44
+ /**
45
+ * Orders session establishment. Every outgoing create takes a number when it is
46
+ * issued; every installation (an outgoing create's answer, an incoming create or
47
+ * resume, a resume's answer) raises `installedSeq` to at least the numbers issued
48
+ * so far. An outgoing create's answer is installed only if its number is above
49
+ * `installedSeq`: the newest request wins whatever order answers arrive in, and
50
+ * an answer issued before another session was installed is stale.
51
+ */
52
+ sessionSeq = 0;
53
+ installedSeq = 0;
54
+ /** The grant refresh in flight (one per session lifecycle) and the refreshes requested meanwhile, per authority. */
55
+ grantRefresh;
56
+ grantRefreshPending = { remote: false, local: false };
26
57
  constructor(transport, opts) {
27
58
  this.transport = transport;
28
59
  this.handler = opts?.handler ?? {};
29
60
  this.callTimeout = opts?.callTimeout ?? 30_000;
30
61
  this.validator = opts?.validator;
31
62
  this.authorize = opts?.authorize;
63
+ this.validateCompletions = opts?.validateCompletions ?? true;
64
+ this.onRefusedCompletion = opts?.onRefusedCompletion;
65
+ this.onSessionLost = opts?.onSessionLost;
66
+ this.supportedVersions = [...(opts?.supportedVersions ?? SUPPORTED_VERSIONS)];
32
67
  // Wire up transport events.
33
68
  this.transport.on("message", (msg) => this.dispatch(msg));
34
69
  this.transport.on("error", (err) => this.onTransportError(err));
35
70
  this.transport.on("close", () => this.onTransportClose());
71
+ this.transport.on("gap", () => this.onTransportGap());
36
72
  }
37
73
  /** Register a profile. Call before starting to receive messages. */
38
74
  use(profile) {
39
75
  this.registry.register(profile);
40
76
  profile.init(this);
41
77
  }
78
+ /**
79
+ * Incremented whenever the session this peer holds state for is replaced or
80
+ * ends. A response or handler result that was requested under an earlier
81
+ * value belongs to a session that is gone and must not touch the current one.
82
+ */
83
+ lifecycle = 0;
84
+ /** A usable session identity: a non-empty string. Anything else is no identity (the grant is then unbound and admits nothing). */
85
+ static usableId(id) {
86
+ return typeof id === "string" && id !== "" ? id : undefined;
87
+ }
88
+ /** A new session: what it granted replaces what the previous one did (nothing if it omits them). */
89
+ beginSession(sessionId, capabilities) {
90
+ this.lifecycle++;
91
+ // A copy: the grant must not change when the caller's (or handler's) object does.
92
+ this.negotiated = { sessionId: Peer.usableId(sessionId), capabilities: { ...capabilities } };
93
+ this.capRev++;
94
+ this.resetFlows(); // flow state of the old session does not carry over
95
+ }
96
+ endSession() {
97
+ this.lifecycle++;
98
+ this.negotiated = undefined;
99
+ this.capRev++;
100
+ this.resetFlows();
101
+ // The transport is no longer bound to the session that ended.
102
+ this.clearTransportBinding();
103
+ }
104
+ /**
105
+ * A resume of `sessionId`; `rev` is the grant revision when the resume was
106
+ * requested. The SAME session keeps its identity: a capability set the result
107
+ * lists is a snapshot (applied like a capability result), an omitted set leaves
108
+ * the grant, and neither the lifecycle nor the flow state changes. Another
109
+ * session is a replacement: its grant is what the result lists (nothing if
110
+ * omitted), the lifecycle moves on and the old session's flow state is dropped.
111
+ */
112
+ resumeNegotiated(sessionId, capabilities, rev, source = "remote") {
113
+ const id = Peer.usableId(sessionId);
114
+ const n = this.negotiated;
115
+ if (n?.sessionId !== undefined && n.sessionId === id) {
116
+ if (capabilities !== undefined)
117
+ this.applySnapshot(n, rev, capabilities, source);
118
+ return;
119
+ }
120
+ this.lifecycle++;
121
+ this.negotiated = { sessionId: id, capabilities: { ...capabilities } };
122
+ this.capRev++;
123
+ this.resetFlows();
124
+ }
125
+ /**
126
+ * Applies a grant snapshot obtained at revision `rev`: current revision means
127
+ * it is the latest word and replaces the grant; a changed revision means it may
128
+ * be stale, so it only removes capabilities that are no longer listed.
129
+ */
130
+ applySnapshot(n, rev, snapshot, source = "remote") {
131
+ if (this.capRev === rev) {
132
+ n.capabilities = { ...snapshot };
133
+ this.capRev++;
134
+ return;
135
+ }
136
+ const have = Object.keys(n.capabilities);
137
+ const same = have.length === Object.keys(snapshot).length && have.every((k) => Object.hasOwn(snapshot, k));
138
+ // A stale snapshot that names exactly what is cached changes nothing: no
139
+ // revision bump and no refresh (which would otherwise ping-pong between peers
140
+ // whose grants never change).
141
+ if (same)
142
+ return;
143
+ // Without a local list handler a stale local snapshot only narrows, and the
144
+ // remote peer is asked for the authoritative one.
145
+ if (source === "local" && !this.handler.onCapabilityList)
146
+ source = "remote";
147
+ const kept = {};
148
+ for (const k of have) {
149
+ if (Object.hasOwn(snapshot, k))
150
+ kept[k] = n.capabilities[k];
151
+ }
152
+ n.capabilities = kept;
153
+ this.capRev++;
154
+ // The answer may have been older than what is cached, so it was only allowed to
155
+ // narrow: ask the authority for a fresh snapshot, which restores any capability
156
+ // that is really granted (a failed refresh leaves the grant narrowed). The
157
+ // authority is the remote peer for what it answered, this peer's own capability
158
+ // handler for what that returned.
159
+ this.scheduleGrantRefresh(source);
160
+ }
161
+ /**
162
+ * One fresh capability.list at a time; its answer is applied like any other (at
163
+ * the revision it was requested at). A request that arrives while one is in
164
+ * flight is remembered and runs after it, so the grant is refreshed after the
165
+ * LAST change that may have made a snapshot stale.
166
+ */
167
+ scheduleGrantRefresh(source) {
168
+ if (this.closed)
169
+ return;
170
+ // A refresh in flight for THIS session lifecycle absorbs the request (it runs
171
+ // after it); one left over from an earlier session does not hold this one up.
172
+ if (this.grantRefresh && this.grantRefresh.gen === this.lifecycle) {
173
+ this.grantRefreshPending[source] = true;
174
+ return;
175
+ }
176
+ const id = this.negotiated?.sessionId;
177
+ if (id === undefined)
178
+ return;
179
+ const gen = this.lifecycle;
180
+ const rev = this.capRev;
181
+ const mine = { gen };
182
+ this.grantRefresh = mine;
183
+ const params = { wmp: { version: this.negotiatedVersion ?? VERSION, session_id: id } };
184
+ void (async () => {
185
+ try {
186
+ if (source === "remote") {
187
+ await this.callNow(Method.CapabilityList, params);
188
+ }
189
+ else if (this.handler.onCapabilityList) {
190
+ const result = await this.handler.onCapabilityList(params);
191
+ this.refreshNegotiated(gen, id, rev, result?.capabilities, "local");
192
+ }
193
+ }
194
+ catch {
195
+ /* no fresh snapshot: the narrowed grant stands (fail closed) */
196
+ }
197
+ finally {
198
+ // Only the refresh that is still the current one clears the marker and drains.
199
+ if (this.grantRefresh === mine) {
200
+ this.grantRefresh = undefined;
201
+ let next;
202
+ if (this.grantRefreshPending.remote)
203
+ next = "remote";
204
+ else if (this.grantRefreshPending.local)
205
+ next = "local";
206
+ if (next) {
207
+ this.grantRefreshPending[next] = false;
208
+ this.scheduleGrantRefresh(next); // respects the session held NOW; the other source drains after it
209
+ }
210
+ }
211
+ }
212
+ })();
213
+ }
214
+ /**
215
+ * A capability update/list result, applied only to an existing session that is
216
+ * still the one it was requested under: `gen` and `sessionId` are what was
217
+ * current when the operation started, so a late result cannot recreate a closed
218
+ * session's grant or overwrite a newer session's; `rev` orders it against other
219
+ * changes to the grant (see `capRev`).
220
+ */
221
+ refreshNegotiated(gen, sessionId, rev, capabilities, source = "remote") {
222
+ if (typeof capabilities !== "object" || capabilities === null || Array.isArray(capabilities))
223
+ return;
224
+ const n = this.negotiated;
225
+ if (!n || this.lifecycle !== gen)
226
+ return;
227
+ if (sessionId !== undefined && n.sessionId !== undefined && sessionId !== n.sessionId)
228
+ return;
229
+ this.applySnapshot(n, rev, capabilities, source);
230
+ }
231
+ /** Whether `capability` was negotiated for the session the request names (fail closed). */
232
+ hasNegotiated(capability, requestSession) {
233
+ const n = this.negotiated;
234
+ // A grant that is not bound to a usable session identity admits nothing (fail closed).
235
+ if (!n || n.sessionId === undefined || n.sessionId === "")
236
+ return false;
237
+ // Any session id the request carries must be this session's: a present value
238
+ // of the wrong type or content is not "no id".
239
+ if (requestSession !== undefined && requestSession !== n.sessionId)
240
+ return false;
241
+ return Object.hasOwn(n.capabilities, capability);
242
+ }
243
+ /** The highest supported version (what a client offers). */
244
+ offeredVersion() {
245
+ let best;
246
+ let bestKey = -1;
247
+ for (const v of this.supportedVersions) {
248
+ const p = parseVersion(v);
249
+ if (!p)
250
+ continue;
251
+ const key = p.major * 1_000_000 + p.minor;
252
+ if (key > bestKey) {
253
+ bestKey = key;
254
+ best = v;
255
+ }
256
+ }
257
+ // Nothing valid to offer: fail before anything is sent, instead of offering a
258
+ // version this peer was not configured to speak.
259
+ if (best === undefined) {
260
+ throw new WMPError(ErrorCode.VersionNotSupported, "No valid supported protocol version configured", { supported_versions: [...this.supportedVersions] });
261
+ }
262
+ return best;
263
+ }
42
264
  /** The negotiated session ID (set after session.create). */
43
265
  get session() {
44
266
  return this.sessionId;
@@ -46,27 +268,149 @@ export class Peer {
46
268
  // -------------------------------------------------------------------------
47
269
  // PeerContext implementation (for profiles)
48
270
  // -------------------------------------------------------------------------
271
+ /**
272
+ * The queue of the flow.start request whose handler is being invoked, set only
273
+ * for the synchronous part of that invocation. Continuations registered with
274
+ * {@link afterResponse} belong to that request alone, so a start that fails
275
+ * (for example a duplicate) can only discard its own.
276
+ */
277
+ afterTarget;
278
+ /**
279
+ * PeerContext: queue `fn` to run once the response to the flow.start being
280
+ * handled was sent. Called outside that handler invocation there is no
281
+ * response to wait for, and `fn` runs on a zero-delay timer instead.
282
+ */
283
+ afterResponse(fn) {
284
+ if (this.afterTarget)
285
+ this.afterTarget.fns.push(fn);
286
+ else
287
+ setTimeout(fn, 0);
288
+ }
49
289
  async notify(method, params) {
50
290
  const msg = createNotification(method, params);
291
+ // A session close sent through the generic API ends the session exactly as
292
+ // closeSession() does; only the session that was closed has its state cleared.
293
+ const closing = method === Method.SessionClose;
294
+ const gen = this.lifecycle;
295
+ const closedId = closing ? params?.wmp?.session_id : undefined;
51
296
  await this.transport.send(msg);
297
+ if (closing && this.lifecycle === gen && (closedId === undefined || closedId === this.sessionId)) {
298
+ this.sessionId = undefined;
299
+ this.endSession();
300
+ }
301
+ // This peer ended the flow (complete or error, sent by the convenience
302
+ // methods and by profiles alike): its validation context is no longer needed.
303
+ if (method === Method.FlowComplete || method === Method.FlowError)
304
+ this.endFlow(flowIdOf(params));
305
+ }
306
+ /** PeerContext: the generation token of an active flow (see {@link PeerContext.flowGeneration}). */
307
+ flowGeneration(flowId) {
308
+ return this.recordedFlows.get(flowId);
309
+ }
310
+ /**
311
+ * PeerContext: send a flow notification on behalf of one flow generation. A
312
+ * generation that is no longer the flow's (the flow ended, was cancelled, and
313
+ * the id may have been started again) sends nothing and never touches the
314
+ * current flow's record.
315
+ */
316
+ async notifyFlow(generation, method, params) {
317
+ const id = flowIdOf(params);
318
+ // No flow id, no generation (the flow is not active) or another generation: nothing is sent.
319
+ // A missing record must not authorize a send.
320
+ if (typeof id !== "string" || generation === undefined || this.recordedFlows.get(id) !== generation) {
321
+ throw new Error("flow is no longer active");
322
+ }
323
+ // The id cannot be started again while this send is in flight: the old
324
+ // notification would otherwise reach the receiver under the id of a replacement.
325
+ this.sendingFlow.set(id, (this.sendingFlow.get(id) ?? 0) + 1);
326
+ try {
327
+ await this.transport.send(createNotification(method, params));
328
+ }
329
+ finally {
330
+ const left = (this.sendingFlow.get(id) ?? 1) - 1;
331
+ if (left <= 0)
332
+ this.sendingFlow.delete(id);
333
+ else
334
+ this.sendingFlow.set(id, left);
335
+ }
336
+ // Retire the flow only if it is still the generation that sent this.
337
+ if (this.recordedFlows.get(id) === generation)
338
+ this.endFlow(id);
339
+ }
340
+ /** Flow ids with a notification still being sent (their reuse is refused meanwhile). */
341
+ sendingFlow = new Map();
342
+ /** Drops the validation context of a flow that ended; the flow_id is free to start again. */
343
+ releaseFlow(flowId) {
344
+ if (typeof flowId !== "string")
345
+ return;
346
+ this.recordedFlows.delete(flowId);
347
+ this.releaseGen(flowId);
348
+ }
349
+ /**
350
+ * Reclaims a flow id's generation once nothing needs it: the flow is not active
351
+ * and no cancellation for it is pending (a pending one compares against it).
352
+ * Without this every finished flow would leave an entry behind for the whole
353
+ * session. A missing entry reads as generation 0.
354
+ */
355
+ releaseGen(flowId) {
356
+ if (!this.recordedFlows.has(flowId) && (this.cancelCount.get(flowId) ?? 0) === 0)
357
+ this.flowGen.delete(flowId);
52
358
  }
53
359
  async call(method, params) {
360
+ // Session create/resume through the generic API get the same validation and
361
+ // state installation as the convenience methods.
362
+ if (method === Method.SessionCreate)
363
+ return this.createVia(params);
364
+ if (method === Method.SessionResume) {
365
+ // Explicit parameters only: a missing/null/non-object value is not "resume the
366
+ // current session" (that is resumeSession()), and must not silently send and
367
+ // rotate this peer's own token.
368
+ if (typeof params !== "object" || params === null || Array.isArray(params)) {
369
+ throw new WMPError(ErrorCode.InvalidParams, "Invalid params", { reason: "session.resume needs explicit params" });
370
+ }
371
+ return this.resumeSerialized({ params: params }, this.flowEpoch, this.lifecycle);
372
+ }
373
+ return this.callNow(method, params);
374
+ }
375
+ callNow(method, params) {
54
376
  const req = createRequest(method, params);
55
377
  const id = req.id;
378
+ // Every outgoing flow.start goes through here (the convenience method and
379
+ // profiles alike), so the flow's validation context is always recorded.
380
+ const rollback = method === Method.FlowStart ? this.beginFlow(flowIdOf(params), flowTypeOf(params), params.params) : noop;
381
+ // What a capability result is checked against when it comes back: the
382
+ // lifecycle and the session the REQUEST names (else the current one).
383
+ const capturedGen = this.lifecycle;
384
+ const capturedRev = this.capRev;
385
+ const named = params?.wmp?.session_id;
386
+ const capturedSession = typeof named === "string" ? named : this.negotiated?.sessionId;
56
387
  return new Promise((resolve, reject) => {
388
+ const fail = (err) => {
389
+ rollback(); // the start did not succeed: it must not leave a context behind
390
+ reject(err);
391
+ };
57
392
  const timer = setTimeout(() => {
58
393
  this.pending.delete(id);
59
- reject(new WMPError(ErrorCode.InternalError, `Call to ${method} timed out`));
394
+ fail(new WMPError(ErrorCode.InternalError, `Call to ${method} timed out`));
60
395
  }, this.callTimeout);
61
396
  this.pending.set(id, {
62
- resolve: resolve,
63
- reject,
397
+ resolve: ((v) => {
398
+ if (method === Method.CapabilityUpdate || method === Method.CapabilityList) {
399
+ // Only the session (and lifecycle) that existed when the request went out may be refreshed.
400
+ this.refreshNegotiated(capturedGen, capturedSession, capturedRev, v?.capabilities);
401
+ }
402
+ // A cancelled flow has ended: release its context (shared by the convenience method and profiles).
403
+ if (method === Method.FlowCancel)
404
+ this.endFlow(flowIdOf(params), "cancelled"); // also remembered as ended: later actions for it are refused
405
+ resolve(v);
406
+ }),
407
+ reject: fail,
64
408
  timer,
65
409
  });
66
410
  this.transport.send(req).catch((err) => {
67
411
  this.pending.delete(id);
68
412
  clearTimeout(timer);
69
- reject(err);
413
+ fail(err);
70
414
  });
71
415
  });
72
416
  }
@@ -75,9 +419,9 @@ export class Peer {
75
419
  // -------------------------------------------------------------------------
76
420
  /** Initiate a WMP session. */
77
421
  async createSession(opts) {
78
- const wmp = { version: VERSION, sender: opts.sender };
422
+ const offered = this.offeredVersion();
79
423
  const params = {
80
- wmp,
424
+ wmp: { version: offered, sender: opts.sender },
81
425
  participants: opts.participants,
82
426
  capabilities_offered: opts.capabilities,
83
427
  security: opts.security ?? { mode: "tls" },
@@ -85,43 +429,140 @@ export class Peer {
85
429
  auth: opts.auth,
86
430
  invitation_nonce: opts.invitationNonce,
87
431
  };
88
- const result = await this.call(Method.SessionCreate, params);
89
- if (!result.wmp?.session_id || typeof result.wmp.session_id !== "string") {
432
+ return this.createVia(params);
433
+ }
434
+ /** Sends a session.create and installs the answer (validated, ordered against other session changes). */
435
+ async createVia(params) {
436
+ // The version the request offered (the generic API may send anything; the
437
+ // answer is then only held to "a version this peer speaks").
438
+ const offered = params?.wmp?.version;
439
+ const seq = ++this.sessionSeq;
440
+ const result = await this.callNow(Method.SessionCreate, params);
441
+ const newId = Peer.usableId(result.wmp?.session_id);
442
+ if (newId === undefined) {
90
443
  throw new WMPError(ErrorCode.SessionNotFound, "session.create response missing session_id");
91
444
  }
92
- if (result.wmp.version && result.wmp.version !== VERSION) {
93
- throw new WMPError(ErrorCode.VersionNotSupported, `negotiated version ${result.wmp.version} is not supported`);
94
- }
95
- this.sessionId = result.wmp.session_id;
96
- this.bindSessionToTransport(result.wmp.session_id);
97
- this.negotiatedVersion = result.wmp.version ?? VERSION;
98
- if (result.resumption_token) {
99
- this.resumptionToken = result.resumption_token;
445
+ // The newest request wins whatever order answers arrive in, and an answer
446
+ // issued before another session was installed (an overlapping create, an
447
+ // incoming create or resume) is stale: it must not replace that session.
448
+ if (seq <= this.installedSeq)
449
+ throw new StaleSessionError();
450
+ // Core 2.2.2: the responder selects the highest version it supports that
451
+ // is not above the offered one. Accept that, never a version this peer does
452
+ // not speak or one above the offer.
453
+ // The offer must have been a valid version and the answer compatible with it
454
+ // (same MAJOR, not above it) and one this peer speaks: nothing else is installed.
455
+ const selected = result.wmp.version;
456
+ if (typeof offered !== "string" || parseVersion(offered) === undefined)
457
+ throw versionRejection(offered, this.supportedVersions);
458
+ if (!selected || !(this.supportedVersions.includes(selected) && negotiateVersion(offered, [selected]) === selected)) {
459
+ throw new WMPError(ErrorCode.VersionNotSupported, `negotiated version ${selected} is not supported`, { supported_versions: [...this.supportedVersions] });
100
460
  }
461
+ this.installedSeq = Math.max(this.installedSeq, seq);
462
+ this.sessionId = newId;
463
+ this.bindSessionToTransport(newId);
464
+ this.negotiatedVersion = selected;
465
+ this.beginSession(newId, result.capabilities);
466
+ // The new session's token, or none: the previous session's must not linger.
467
+ this.resumptionToken = result.resumption_token || undefined;
101
468
  return result;
102
469
  }
103
- /** Resume a previously established WMP session using a resumption token. */
470
+ /**
471
+ * Resume a previously established WMP session using a resumption token.
472
+ * Resumes run one at a time (explicit calls and gap recovery alike): the token
473
+ * is single use, so a second resume must wait for the first to store the
474
+ * rotated one and then present that.
475
+ */
104
476
  async resumeSession(opts) {
105
- if (!this.sessionId || !this.resumptionToken) {
106
- throw new Error("no session or resumption token to resume");
477
+ // The session (lifecycle and flow epoch) this resume is requested for is noted
478
+ // NOW, before it waits its turn: if that session is closed or replaced while
479
+ // it queues, it is dropped instead of reinstalling the old session.
480
+ return this.resumeSerialized(opts, this.flowEpoch, this.lifecycle);
481
+ }
482
+ /**
483
+ * `forEpoch`: recovery work that is only valid for the session it was queued
484
+ * for; if that session was closed or replaced (or the peer closed) while it
485
+ * waited its turn, it is dropped (StaleSessionError) instead of resuming the
486
+ * session that replaced it.
487
+ */
488
+ async resumeSerialized(opts, forEpoch, forGen) {
489
+ const previous = this.resumeChain;
490
+ let release;
491
+ this.resumeChain = new Promise((r) => (release = r));
492
+ await previous;
493
+ try {
494
+ if (this.closed || this.flowEpoch !== forEpoch || this.lifecycle !== forGen)
495
+ throw new StaleSessionError();
496
+ return await this.resumeNow(opts);
107
497
  }
108
- const params = {
109
- wmp: { version: this.negotiatedVersion ?? VERSION },
110
- session_id: this.sessionId,
111
- resumption_token: this.resumptionToken,
112
- last_received_id: opts?.lastReceivedId,
113
- };
114
- const result = await this.call(Method.SessionResume, params);
115
- if (result.wmp?.session_id) {
116
- this.sessionId = result.wmp.session_id;
117
- this.bindSessionToTransport(result.wmp.session_id);
498
+ finally {
499
+ release();
118
500
  }
119
- if (result.wmp?.version) {
120
- this.negotiatedVersion = result.wmp.version;
501
+ }
502
+ resumeChain = Promise.resolve();
503
+ async resumeNow(opts) {
504
+ // Explicit parameters (the generic call() API) are used as given; otherwise
505
+ // they come from the session this peer holds.
506
+ let params;
507
+ if (opts?.params) {
508
+ params = opts.params;
121
509
  }
510
+ else {
511
+ if (!this.sessionId || !this.resumptionToken) {
512
+ throw new Error("no session or resumption token to resume");
513
+ }
514
+ params = {
515
+ wmp: { version: this.negotiatedVersion ?? VERSION },
516
+ session_id: this.sessionId,
517
+ resumption_token: this.resumptionToken,
518
+ // In the HTTP binding this is the last event ID (Transport Section 4.5).
519
+ last_received_id: opts?.lastReceivedId ?? this.transport.lastEventId,
520
+ };
521
+ }
522
+ const gen = this.lifecycle;
523
+ const epoch = this.flowEpoch;
524
+ const rev = this.capRev;
525
+ const result = await this.callNow(Method.SessionResume, params);
526
+ // The session this resume was for may have been closed or replaced while it
527
+ // was in flight: its result must not bring that session back or overwrite the
528
+ // session that replaced it.
529
+ if (this.lifecycle !== gen || this.flowEpoch !== epoch)
530
+ throw new StaleSessionError();
531
+ // An unsuccessful resume changes nothing; the caller creates a new session.
532
+ if (result.resumed !== true) {
533
+ throw new WMPError(ErrorCode.SessionExpired, "Session could not be resumed");
534
+ }
535
+ // Validate before mutating any session state: a resume that selects a
536
+ // version this peer does not speak, or one above what it offered, is a lost
537
+ // session (the caller creates a new one), not a silent switch.
538
+ const selected = result.wmp?.version;
539
+ const offered = params.wmp?.version;
540
+ if (typeof offered !== "string" || parseVersion(offered) === undefined)
541
+ throw versionRejection(offered, this.supportedVersions);
542
+ if (!selected || !(this.supportedVersions.includes(selected) && negotiateVersion(offered, [selected]) === selected)) {
543
+ throw new WMPError(ErrorCode.VersionNotSupported, `negotiated version ${selected} is not supported`, { supported_versions: [...this.supportedVersions] });
544
+ }
545
+ // The resumed session: what the result names, else the one that was asked for
546
+ // (the optional member may be left out, as on the responder path).
547
+ const resumedId = Peer.usableId(result.wmp?.session_id) ?? Peer.usableId(params.session_id);
548
+ // Only a resume that SWITCHES to another session supersedes creates still in
549
+ // flight; one that merely refreshes the current session does not.
550
+ const switching = resumedId !== undefined && resumedId !== this.sessionId;
551
+ if (resumedId !== undefined) {
552
+ // Another session's token is not this one's: dropped before any new one is applied.
553
+ if (resumedId !== this.sessionId)
554
+ this.resumptionToken = undefined;
555
+ // (Flow state: resumeNegotiated below keeps it for the same session and drops it for another.)
556
+ this.sessionId = resumedId;
557
+ this.bindSessionToTransport(resumedId);
558
+ }
559
+ this.negotiatedVersion = selected;
122
560
  if (result.resumption_token) {
123
561
  this.resumptionToken = result.resumption_token;
124
562
  }
563
+ if (switching)
564
+ this.installedSeq = Math.max(this.installedSeq, this.sessionSeq); // creates issued before this are older
565
+ this.resumeNegotiated(resumedId ?? this.sessionId, result.capabilities, rev);
125
566
  return result;
126
567
  }
127
568
  /** The current resumption token (set after session.create or session.resume). */
@@ -143,11 +584,12 @@ export class Peer {
143
584
  async closeSession(reason = "complete") {
144
585
  if (!this.sessionId)
145
586
  return;
587
+ // notify() clears this session's state once the close was sent, unless a
588
+ // replacement session was established meanwhile.
146
589
  await this.notify(Method.SessionClose, {
147
- wmp: { version: VERSION, session_id: this.sessionId },
590
+ wmp: { version: this.negotiatedVersion ?? VERSION, session_id: this.sessionId },
148
591
  reason,
149
592
  });
150
- this.sessionId = undefined;
151
593
  }
152
594
  // -------------------------------------------------------------------------
153
595
  // Flow convenience methods
@@ -257,6 +699,17 @@ export class Peer {
257
699
  }
258
700
  }
259
701
  handleRequest(req) {
702
+ // What the handler queued for after this request's response, and how to undo
703
+ // the flow it started if that response cannot be delivered.
704
+ const after = { fns: [] };
705
+ // Ordering and lifecycle are fixed on RECEIPT, before authorization (which may
706
+ // be slow): a request that arrived earlier cannot take a newer number or
707
+ // capture the lifecycle of a session that replaced the one it targets.
708
+ const ticket = {
709
+ seq: req.method === Method.SessionCreate ? ++this.sessionSeq : undefined,
710
+ gen: this.lifecycle,
711
+ rev: this.capRev,
712
+ };
260
713
  const dispatch = async () => {
261
714
  if (this.authorize) {
262
715
  const allowed = await this.authorize(req.method, req.params);
@@ -264,27 +717,89 @@ export class Peer {
264
717
  throw new WMPError(ErrorCode.NotAuthorized, `Not authorized to call ${req.method}`);
265
718
  }
266
719
  }
267
- return this.dispatchMethod(req.method, req.params);
720
+ return this.dispatchMethod(req.method, req.params, after, ticket);
268
721
  };
269
722
  if (isNotification(req)) {
723
+ // wmp.flow.start is a request: its response is what lets a profile queue
724
+ // work for after it (afterResponse). In notification form no response can
725
+ // ever be sent, so it is dropped instead of dispatched.
726
+ if (req.method === Method.FlowStart)
727
+ return;
270
728
  dispatch().catch(() => {
271
729
  /* notifications get no error response */
272
730
  });
273
731
  }
274
732
  else {
275
733
  dispatch()
276
- .then((result) => {
734
+ .then(async (result) => {
277
735
  const resp = createResponse(req.id, result);
278
- return this.transport.send(resp);
736
+ await this.transport.send(resp);
737
+ // Only now may anything the handler queued for after the response go out.
738
+ for (const fn of after.fns.splice(0)) {
739
+ try {
740
+ fn();
741
+ }
742
+ catch {
743
+ /* a queued continuation must not break the dispatcher */
744
+ }
745
+ }
279
746
  })
280
747
  .catch((err) => {
748
+ after.fns.length = 0; // this request's continuations only: they never run
749
+ after.undo?.(); // the start was acknowledged by nobody: it must not leave a flow behind
281
750
  const rpcErr = toRPCError(err);
282
751
  const resp = createErrorResponse(req.id, rpcErr);
283
752
  return this.transport.send(resp);
284
753
  });
285
754
  }
286
755
  }
287
- async dispatchMethod(method, params) {
756
+ async dispatchMethod(method, params, after, ticket = { seq: undefined, gen: this.lifecycle, rev: this.capRev }) {
757
+ // A repeat of a terminal message already processed (or refused): ignored.
758
+ // Only checked here; a flow is marked once its message passed validation.
759
+ if ((method === Method.FlowComplete || method === Method.FlowError) && isFlowIdEnvelope(params) && this.terminalSeen.has(params.flow_id)) {
760
+ return undefined;
761
+ }
762
+ // A profile may refuse an action for one of its flows before ANY validation or
763
+ // handler (select_credentials is a closed set, profile 3.2.3.1): the refusal
764
+ // must not depend on an optional schema validator accepting the message first.
765
+ // The envelope is checked, and the flow type is the one recorded at start.
766
+ if (method === Method.FlowAction) {
767
+ const fid = flowIdOf(params);
768
+ // An action for a flow that already ended (completed, failed or cancelled)
769
+ // has nothing to act on, and its validation record is gone: it must not fall
770
+ // through to the handlers unchecked. A genuine replacement start clears the marker.
771
+ if (typeof fid === "string" && this.terminalSeen.has(fid) && !this.recordedFlows.has(fid)) {
772
+ throw new WMPError(ErrorCode.InvalidParams, "Invalid params", { reason: "flow has ended" });
773
+ }
774
+ const recorded = typeof fid === "string" ? this.recordedFlows.get(fid) : undefined;
775
+ const validating = recorded ? this.registry.getFlowHandler(recorded.type) : undefined;
776
+ if (validating?.validateAction) {
777
+ // A malformed envelope for a flow whose profile judges its actions is not
778
+ // let through to the handlers: it cannot be judged, so it is refused.
779
+ if (!isFlowActionEnvelope(params)) {
780
+ throw new WMPError(ErrorCode.InvalidParams, "Invalid params", { reason: "malformed flow.action envelope" });
781
+ }
782
+ validating.validateAction(params, recorded.type);
783
+ }
784
+ }
785
+ // A completion that breaks the result rules is refused before the generic
786
+ // validator runs: a notification the validator rejected would be dropped
787
+ // silently and the receiving handler would never learn that the flow failed.
788
+ // Authorization (handleRequest) and the envelope shape are still checked.
789
+ if (method === Method.FlowComplete && this.validateCompletions) {
790
+ if (isFlowCompleteEnvelope(params)) {
791
+ const refusal = this.completionRefusal(params);
792
+ if (refusal) {
793
+ this.refuseCompletion(params, refusal);
794
+ return undefined;
795
+ }
796
+ }
797
+ else if (!this.validator) {
798
+ // Not even the basic envelope, and no schema validator to judge it: it
799
+ // is not delivered (a result nobody checked must not reach the handler).
800
+ return undefined;
801
+ }
802
+ }
288
803
  if (this.validator) {
289
804
  const errors = this.validator.validateMethod(method, params);
290
805
  if (errors) {
@@ -298,19 +813,84 @@ export class Peer {
298
813
  // Session
299
814
  case Method.SessionCreate:
300
815
  if (this.handler.onSessionCreate) {
301
- return this.handler.onSessionCreate(p);
816
+ // Core 2.2.2: the highest supported version not above the offer, or
817
+ // -32602 (malformed) / -31013 with supported_versions.
818
+ const selected = negotiateVersion(p?.wmp?.version, this.supportedVersions);
819
+ if (selected === undefined)
820
+ throw versionRejection(p?.wmp?.version, this.supportedVersions);
821
+ // Incoming creates are ordered by REQUEST (the same numbering as outgoing
822
+ // creates): a result older than a session that was already installed is
823
+ // refused, a newer one replaces an older one that finished first.
824
+ const seq = ticket.seq ?? ++this.sessionSeq;
825
+ const result = await this.handler.onSessionCreate(p);
826
+ if (result) {
827
+ // A session without a usable identity cannot be addressed, closed or
828
+ // gated: it is a handler bug, refused before any state changes.
829
+ const id = Peer.usableId(result.wmp?.session_id);
830
+ if (id === undefined)
831
+ throw new Error("session.create handler returned no session id");
832
+ if (seq <= this.installedSeq)
833
+ throw new WMPError(ErrorCode.SessionNotFound, "Session superseded");
834
+ // The negotiated version is the one that goes on the wire, whatever the handler wrote.
835
+ result.wmp = { ...result.wmp, version: selected };
836
+ this.negotiatedVersion = selected;
837
+ // The session this peer now serves: its identity, routing and what it
838
+ // granted (nothing if the result omits capabilities). A new session
839
+ // has no resumption token of ours: the old session's must not linger.
840
+ this.sessionId = id;
841
+ this.bindSessionToTransport(id);
842
+ this.resumptionToken = undefined;
843
+ this.installedSeq = Math.max(this.installedSeq, seq);
844
+ this.beginSession(id, result.capabilities);
845
+ }
846
+ return result;
302
847
  }
303
848
  break;
304
849
  case Method.SessionResume:
305
850
  if (this.handler.onSessionResume) {
306
- return this.handler.onSessionResume(p);
851
+ const selected = negotiateVersion(p?.wmp?.version, this.supportedVersions);
852
+ if (selected === undefined)
853
+ throw versionRejection(p?.wmp?.version, this.supportedVersions);
854
+ const gen = ticket.gen;
855
+ const rev = ticket.rev;
856
+ const result = await this.handler.onSessionResume(p);
857
+ if (result) {
858
+ result.wmp = { ...result.wmp, version: selected };
859
+ if (result.resumed === true) {
860
+ // A successful resume that outlived a close or replacement is not
861
+ // "resumed": the requester must not take it for a recovery.
862
+ if (this.lifecycle !== gen)
863
+ throw new WMPError(ErrorCode.SessionNotFound, "Session superseded");
864
+ this.negotiatedVersion = selected;
865
+ const resumedId = Peer.usableId(result.wmp.session_id) ?? Peer.usableId(p?.session_id);
866
+ if (resumedId !== undefined) {
867
+ if (resumedId !== this.sessionId) {
868
+ this.resumptionToken = undefined; // another session: not its token
869
+ this.installedSeq = Math.max(this.installedSeq, this.sessionSeq); // creates issued before this are older
870
+ }
871
+ this.sessionId = resumedId;
872
+ this.bindSessionToTransport(resumedId);
873
+ }
874
+ this.resumeNegotiated(resumedId, result.capabilities, rev, "local");
875
+ }
876
+ }
877
+ return result;
307
878
  }
308
879
  break;
309
- case Method.SessionClose:
880
+ case Method.SessionClose: {
881
+ // Only the close of THIS session ends its state: a delayed close for an
882
+ // earlier session must not strip the grant of the one that replaced it.
883
+ const closing = p?.wmp?.session_id;
884
+ if (closing === undefined || closing === this.sessionId || closing === this.negotiated?.sessionId) {
885
+ if (closing === undefined || closing === this.sessionId)
886
+ this.sessionId = undefined;
887
+ this.endSession();
888
+ }
310
889
  if (this.handler.onSessionClose) {
311
890
  this.handler.onSessionClose(p);
312
891
  }
313
892
  return undefined;
893
+ }
314
894
  case Method.SessionAuthenticate:
315
895
  if (this.handler.onSessionAuthenticate) {
316
896
  return this.handler.onSessionAuthenticate(p);
@@ -340,22 +920,78 @@ export class Peer {
340
920
  // Capabilities
341
921
  case Method.CapabilityUpdate:
342
922
  if (this.handler.onCapabilityUpdate) {
343
- return this.handler.onCapabilityUpdate(p);
923
+ const gen = this.lifecycle;
924
+ const rev = this.capRev;
925
+ const result = await this.handler.onCapabilityUpdate(p);
926
+ // The update changed what the session grants: later flow starts are gated by it.
927
+ this.refreshNegotiated(gen, p?.wmp?.session_id, rev, result?.capabilities, "local");
928
+ return result;
344
929
  }
345
930
  break;
346
931
  case Method.CapabilityList:
347
932
  if (this.handler.onCapabilityList) {
348
- return this.handler.onCapabilityList(p);
933
+ const gen = this.lifecycle;
934
+ const rev = this.capRev;
935
+ const result = await this.handler.onCapabilityList(p);
936
+ this.refreshNegotiated(gen, p?.wmp?.session_id, rev, result?.capabilities, "local");
937
+ return result;
349
938
  }
350
939
  break;
351
940
  // Flows — delegate to profile FlowHandlers first, then handler.
352
941
  case Method.FlowStart: {
942
+ // Both identifiers must be real strings: without them there is nothing to
943
+ // route or record, and "unsupported flow type" would be the wrong answer.
944
+ if (typeof p?.flow_type !== "string" || p.flow_type === "" || typeof p.flow_id !== "string" || p.flow_id === "") {
945
+ throw new WMPError(ErrorCode.InvalidParams, "Invalid params", { reason: "flow_type and flow_id must be non-empty strings" });
946
+ }
947
+ // The envelope carries the protocol version (Core 3.2); a start without one
948
+ // is malformed and never reaches a responder.
949
+ if (typeof p.wmp !== "object" || p.wmp === null || typeof p.wmp.version !== "string") {
950
+ throw new WMPError(ErrorCode.InvalidParams, "Invalid params", { reason: "wmp.version is required" });
951
+ }
353
952
  const fh = this.registry.getFlowHandler(p.flow_type);
354
- if (fh)
355
- return fh.startFlow(p);
356
- if (this.handler.onFlowStart)
357
- return this.handler.onFlowStart(p);
358
- break;
953
+ if (fh) {
954
+ // Core 10.3: a flow type whose capability was not negotiated is
955
+ // refused with -31005 before the profile sees it, and before anything
956
+ // is recorded for the flow. Fails closed: with no negotiated
957
+ // capabilities known, nothing counts as negotiated.
958
+ const need = fh.requiredCapability?.(p.flow_type);
959
+ if (need && !this.hasNegotiated(need, p.wmp?.session_id)) {
960
+ throw unsupportedError(p.flow_type, { capability: need });
961
+ }
962
+ }
963
+ else if (!this.handler.onFlowStart) {
964
+ // Nobody here implements this flow type.
965
+ throw unsupportedError(p?.flow_type);
966
+ }
967
+ // Rejects a duplicate active flow_id and records the flow's validation
968
+ // context; a start that fails leaves nothing (and no existing flow's
969
+ // context) changed.
970
+ const rollback = this.beginFlow(p?.flow_id, p?.flow_type, p?.params);
971
+ // If the response to this start cannot be delivered, handleRequest undoes it too.
972
+ if (after)
973
+ after.undo = rollback;
974
+ try {
975
+ // The handler may queue continuations for after the response; they go
976
+ // to THIS request's queue (the window is the synchronous invocation).
977
+ this.afterTarget = after;
978
+ let started;
979
+ try {
980
+ started = fh ? fh.startFlow(p) : this.handler.onFlowStart(p);
981
+ }
982
+ finally {
983
+ this.afterTarget = undefined;
984
+ }
985
+ return await started;
986
+ }
987
+ catch (err) {
988
+ rollback();
989
+ // A handler that does not implement this flow type: unsupported
990
+ // capability (Core 3.8.1), not an unknown method.
991
+ if (!fh && err instanceof WMPError && err.code === ErrorCode.MethodNotFound)
992
+ throw unsupportedError(p.flow_type);
993
+ throw err;
994
+ }
359
995
  }
360
996
  case Method.FlowProgress: {
361
997
  const fh = this.flowHandlerForId(p.flow_id);
@@ -378,6 +1014,7 @@ export class Peer {
378
1014
  break;
379
1015
  }
380
1016
  case Method.FlowComplete: {
1017
+ this.endFlow(p?.flow_id);
381
1018
  const fh = this.flowHandlerForId(p.flow_id);
382
1019
  if (fh) {
383
1020
  fh.handleComplete(p);
@@ -390,6 +1027,7 @@ export class Peer {
390
1027
  return undefined;
391
1028
  }
392
1029
  case Method.FlowError: {
1030
+ this.endFlow(p?.flow_id);
393
1031
  const fh = this.flowHandlerForId(p.flow_id);
394
1032
  if (fh) {
395
1033
  fh.handleError(p);
@@ -403,6 +1041,57 @@ export class Peer {
403
1041
  }
404
1042
  case Method.FlowCancel:
405
1043
  if (this.handler.onFlowCancel) {
1044
+ const flowId = p?.flow_id;
1045
+ if (typeof flowId === "string") {
1046
+ // A cancellation already processed (a resume re-sends it with a fresh
1047
+ // event ID) is acknowledged again without invoking the handler. Only a
1048
+ // CANCELLED flow: one that ended by complete/error reaches the handler.
1049
+ if (this.terminalSeen.get(flowId) === "cancelled") {
1050
+ return { wmp: p.wmp, flow_id: flowId, status: "cancelled" };
1051
+ }
1052
+ // The flow this cancellation is for: the session epoch and the flow's
1053
+ // generation (stable across the flow's completion, changed by a new flow
1054
+ // under the same id or by a session reset).
1055
+ const epoch = this.flowEpoch;
1056
+ const gen = this.flowGen.get(flowId) ?? 0;
1057
+ // A repeat for the same flow that arrives while the first is still being
1058
+ // processed shares its outcome, even if the flow completed meanwhile. A
1059
+ // replacement flow under the same id is a different generation.
1060
+ const pending = this.cancelling.get(flowId);
1061
+ if (pending?.epoch === epoch && pending.gen === gen)
1062
+ return pending.run;
1063
+ const entry = { epoch, gen, run: undefined };
1064
+ this.cancelCount.set(flowId, (this.cancelCount.get(flowId) ?? 0) + 1);
1065
+ entry.run = (async () => {
1066
+ // Yield first: the entry is installed before the handler can throw
1067
+ // (even synchronously), so its cleanup always sees it.
1068
+ await Promise.resolve();
1069
+ try {
1070
+ const result = await this.handler.onFlowCancel(p);
1071
+ // Finalize only the flow that was cancelled: if another started under
1072
+ // the id (or the session was reset) meanwhile, leave it alone.
1073
+ if (this.flowEpoch === epoch && (this.flowGen.get(flowId) ?? 0) === gen)
1074
+ this.endFlow(flowId, "cancelled");
1075
+ return result;
1076
+ }
1077
+ finally {
1078
+ if (this.cancelling.get(flowId) === entry)
1079
+ this.cancelling.delete(flowId); // a failure leaves a retry possible
1080
+ // Bookkeeping of a session that was reset meanwhile (counts and entries
1081
+ // were cleared) must not touch the new session's.
1082
+ if (this.flowEpoch === epoch) {
1083
+ const left = (this.cancelCount.get(flowId) ?? 1) - 1;
1084
+ if (left <= 0)
1085
+ this.cancelCount.delete(flowId);
1086
+ else
1087
+ this.cancelCount.set(flowId, left);
1088
+ this.releaseGen(flowId);
1089
+ }
1090
+ }
1091
+ })();
1092
+ this.cancelling.set(flowId, entry);
1093
+ return entry.run;
1094
+ }
406
1095
  return this.handler.onFlowCancel(p);
407
1096
  }
408
1097
  break;
@@ -425,6 +1114,157 @@ export class Peer {
425
1114
  }
426
1115
  throw new WMPError(ErrorCode.MethodNotFound, `Method not found: ${method}`);
427
1116
  }
1117
+ /**
1118
+ * The validation context of every ACTIVE flow (started, not yet ended), by
1119
+ * flow_id: its type and, for match, the ids of the verifier's query. Never
1120
+ * evicted to make room: a new start is refused at capacity instead of
1121
+ * weakening an existing flow's checks.
1122
+ */
1123
+ recordedFlows = new Map();
1124
+ /**
1125
+ * Flows that ended (complete, error, a refused completion or a cancel), by
1126
+ * flow_id. A finished or refused flow is not an unknown one: a further terminal
1127
+ * message for it is ignored instead of being judged by the general rules, and
1128
+ * it holds no active-flow slot. Never evicted (it lives as long as the session)
1129
+ * and cleared when the session ends or changes.
1130
+ */
1131
+ terminalSeen = new Map();
1132
+ markTerminal(flowId, kind = "ended") {
1133
+ this.terminalSeen.set(flowId, kind);
1134
+ }
1135
+ /**
1136
+ * A flow ended: drop its validation context and, if this peer knew the flow
1137
+ * (it was started here or by the remote peer and not yet ended), remember how
1138
+ * it ended. A terminal message for a flow this peer never saw start is
1139
+ * delivered as before but not remembered, so a remote peer cannot grow the
1140
+ * history with fresh ids.
1141
+ */
1142
+ endFlow(flowId, kind = "ended") {
1143
+ if (typeof flowId !== "string")
1144
+ return;
1145
+ const known = this.recordedFlows.delete(flowId);
1146
+ this.releaseGen(flowId);
1147
+ // A flow already in the history may be re-marked (a cancel of an ended flow
1148
+ // upgrades its kind) without growing it.
1149
+ if (known || this.terminalSeen.has(flowId))
1150
+ this.markTerminal(flowId, kind);
1151
+ }
1152
+ /** A new or ended session: the old session's flow state does not carry over. */
1153
+ resetFlows() {
1154
+ this.flowEpoch++;
1155
+ this.recordedFlows.clear();
1156
+ this.terminalSeen.clear();
1157
+ this.flowGen.clear();
1158
+ this.cancelling.clear(); // pending cancellations belong to the old session
1159
+ this.cancelCount.clear();
1160
+ }
1161
+ /**
1162
+ * Records a starting flow and returns the function that undoes it. Refuses
1163
+ * (-32602) a flow_id that is already active, so a second start cannot replace
1164
+ * the context of the first, and (-31007) a start at capacity.
1165
+ */
1166
+ beginFlow(flowId, flowType, params) {
1167
+ if (typeof flowId !== "string" || typeof flowType !== "string")
1168
+ return noop;
1169
+ if (this.recordedFlows.has(flowId) || this.sendingFlow.has(flowId)) {
1170
+ throw new WMPError(ErrorCode.InvalidParams, "Invalid params", { reason: "flow_id is already active" });
1171
+ }
1172
+ if (this.recordedFlows.size >= MAX_ACTIVE_FLOWS) {
1173
+ throw new WMPError(ErrorCode.RateLimited, "Too many active flows");
1174
+ }
1175
+ // The history of finished flows is bounded too, and it is never evicted (a
1176
+ // dropped marker would weaken validation): at saturation new flows are
1177
+ // refused until the session is renewed.
1178
+ if (this.terminalSeen.size >= MAX_TERMINAL_HISTORY && !this.terminalSeen.has(flowId)) {
1179
+ throw new WMPError(ErrorCode.RateLimited, "Too many finished flows in this session");
1180
+ }
1181
+ // A new flow under a reused ID is not a repeat of the old one's terminal
1182
+ // message. If the start fails the marker comes back (below).
1183
+ const hadTerminal = this.terminalSeen.get(flowId);
1184
+ this.terminalSeen.delete(flowId);
1185
+ const q = flowType === "match" && typeof params === "object" && params !== null ? params.dcql_query : undefined;
1186
+ const rec = { type: flowType, queryIds: q === undefined ? undefined : dcqlQueryIds(q) };
1187
+ this.recordedFlows.set(flowId, rec);
1188
+ const previousGen = this.flowGen.get(flowId);
1189
+ const myGen = ++this.genCounter;
1190
+ this.flowGen.set(flowId, myGen); // a new flow under this id (tentative until the start succeeds)
1191
+ return () => {
1192
+ // Only while this start's own record is still the flow's: if the
1193
+ // replacement already ended, or another flow took the id, the marker is theirs.
1194
+ if (this.recordedFlows.get(flowId) === rec) {
1195
+ this.recordedFlows.delete(flowId);
1196
+ if (hadTerminal !== undefined)
1197
+ this.terminalSeen.set(flowId, hadTerminal);
1198
+ // The start failed: the flow generation it allocated goes with it, so work
1199
+ // tied to the flow that was there before (a pending cancellation) still matches.
1200
+ if (this.flowGen.get(flowId) === myGen) {
1201
+ if (previousGen === undefined)
1202
+ this.flowGen.delete(flowId);
1203
+ else
1204
+ this.flowGen.set(flowId, previousGen);
1205
+ }
1206
+ }
1207
+ };
1208
+ }
1209
+ /**
1210
+ * The violation of a completion's result, if any. The check is selected by the
1211
+ * flow type recorded when the flow started, never by members of the result
1212
+ * (openid4x 3.3.3): a match flow's result is the closed set, and a match
1213
+ * completion without a result is refused too.
1214
+ */
1215
+ completionRefusal(p) {
1216
+ const rec = this.recordedFlows.get(p.flow_id);
1217
+ try {
1218
+ if (rec?.type === "match")
1219
+ validateMatchResult(p.result, rec.queryIds);
1220
+ else if (p.result !== undefined)
1221
+ validateCompletionResult(p.result);
1222
+ }
1223
+ catch (err) {
1224
+ if (err instanceof CompletionResultError)
1225
+ return err;
1226
+ throw err;
1227
+ }
1228
+ return undefined;
1229
+ }
1230
+ /**
1231
+ * A non-conforming completion is not delivered. The flow ends as failed: a
1232
+ * synthesized wmp.flow.error, carrying neither the result nor the violation
1233
+ * text, goes to whoever would have received the completion or the error.
1234
+ */
1235
+ refuseCompletion(p, err) {
1236
+ this.endFlow(p.flow_id); // the synthesized error ends the flow
1237
+ this.onRefusedCompletion?.(p.flow_id, err);
1238
+ const synthesized = {
1239
+ wmp: p.wmp,
1240
+ flow_id: p.flow_id,
1241
+ code: ErrorCode.InvalidParams,
1242
+ message: "Non-conforming flow result",
1243
+ };
1244
+ const fh = this.flowHandlerForId(p.flow_id);
1245
+ if (fh)
1246
+ fh.handleError(synthesized);
1247
+ else
1248
+ this.handler.onFlowError?.(synthesized);
1249
+ }
1250
+ /**
1251
+ * Cancellations being processed, by flow_id, with the flow generation they
1252
+ * belong to: a repeat for the SAME generation arriving meanwhile shares the
1253
+ * outcome; a replacement flow under the same id never does.
1254
+ */
1255
+ cancelling = new Map();
1256
+ /** Cancellations still running per flow id, of ANY generation: a generation entry is kept while one is. */
1257
+ cancelCount = new Map();
1258
+ /** Incremented whenever the flow state is reset (session closed or replaced). */
1259
+ flowEpoch = 0;
1260
+ /**
1261
+ * A per-flow-id generation that survives the flow's completion: it changes only
1262
+ * when a new flow starts under the id (and with every reset), so work tied to
1263
+ * "this flow" can tell a replacement from the same flow having ended.
1264
+ */
1265
+ flowGen = new Map();
1266
+ /** Source of unique generation numbers (a rolled-back start never reuses one). */
1267
+ genCounter = 0;
428
1268
  // Track flow_id → flow_type mapping for routing to the right FlowHandler.
429
1269
  activeFlows = new Map();
430
1270
  /** Look up the FlowHandler for an active flow by flow_id. */
@@ -455,6 +1295,81 @@ export class Peer {
455
1295
  onTransportError(_err) {
456
1296
  // Could emit events here for reconnection logic.
457
1297
  }
1298
+ /**
1299
+ * The transport lost events (410): resume the session, which re-sends the
1300
+ * latest progress of active flows and the terminal notification of ended
1301
+ * flows on the already open stream. Without a resumption token, or if the
1302
+ * resume fails, the session is lost.
1303
+ */
1304
+ onTransportGap() {
1305
+ // Recoveries run one at a time: a second resume sent before the first one's
1306
+ // response arrived would present the token the first already rotated. A gap
1307
+ // that arrives while one is queued adds nothing (the queued one covers it).
1308
+ // The session this gap belongs to: recovery work for a session that was closed
1309
+ // or replaced meanwhile is discarded, never applied to the one that replaced it.
1310
+ const epoch = this.flowEpoch;
1311
+ const gen = this.lifecycle;
1312
+ // Events were lost, and one of them may have been a capability revocation: the
1313
+ // CURRENT session's grant is withdrawn right now (gated flows fail closed), not
1314
+ // when its recovery gets its turn behind another session's pending resume. It
1315
+ // stays withdrawn until the resume answer or a fresh capability.list restores it.
1316
+ let mark;
1317
+ if (this.negotiated) {
1318
+ this.negotiated.capabilities = {};
1319
+ mark = ++this.capRev;
1320
+ }
1321
+ if (this.recoveryQueuedEpoch === epoch)
1322
+ return; // coalesce only with a queued recovery of THIS session
1323
+ this.recoveryQueuedEpoch = epoch;
1324
+ this.recovery = this.recovery.then(async () => {
1325
+ // A stale task must not clear the marker of a newer session's queued recovery.
1326
+ if (this.recoveryQueuedEpoch === epoch)
1327
+ this.recoveryQueuedEpoch = undefined;
1328
+ if (this.closed || this.flowEpoch !== epoch || this.lifecycle !== gen)
1329
+ return;
1330
+ if (!this.sessionId || !this.resumptionToken) {
1331
+ this.sessionLost(new Error("event gap and no resumption token to resume with"));
1332
+ return;
1333
+ }
1334
+ try {
1335
+ const resumed = await this.resumeSerialized(undefined, epoch, gen);
1336
+ // A resume that carried no snapshot leaves the grant withdrawn: ask for one,
1337
+ // whatever other gaps bumped the revision meanwhile.
1338
+ if (mark !== undefined && resumed?.capabilities === undefined && this.lifecycle === gen && !this.closed)
1339
+ this.scheduleGrantRefresh("remote");
1340
+ }
1341
+ catch (err) {
1342
+ // The session changed (or the peer closed) while resuming: nothing was lost.
1343
+ if (err instanceof StaleSessionError || this.closed || this.flowEpoch !== epoch || this.lifecycle !== gen)
1344
+ return;
1345
+ this.sessionLost(err instanceof Error ? err : new Error(String(err)));
1346
+ }
1347
+ });
1348
+ }
1349
+ /**
1350
+ * The session cannot be continued: the transport's binding to it is dropped
1351
+ * BEFORE the application is told, so the "create a new session" fallback the
1352
+ * callback is for does not send the dead session's id.
1353
+ */
1354
+ sessionLost(err) {
1355
+ // A session that cannot be continued may have missed a revocation: its grant
1356
+ // is invalidated (gated flows fail closed until a new session is established)
1357
+ // before the application is told. The session id and token stay readable.
1358
+ this.lifecycle++;
1359
+ this.negotiated = undefined;
1360
+ this.capRev++;
1361
+ this.resetFlows();
1362
+ this.clearTransportBinding();
1363
+ this.onSessionLost?.(err);
1364
+ }
1365
+ /** The transport is no longer bound to a session (no stale Wmp-Session-Id, cursor or event stream). */
1366
+ clearTransportBinding() {
1367
+ const t = this.transport;
1368
+ if (typeof t.clearSession === "function")
1369
+ t.clearSession();
1370
+ }
1371
+ recovery = Promise.resolve();
1372
+ recoveryQueuedEpoch;
458
1373
  onTransportClose() {
459
1374
  if (!this.closed) {
460
1375
  // Transport closed unexpectedly — reject all pending.
@@ -469,9 +1384,50 @@ export class Peer {
469
1384
  // ---------------------------------------------------------------------------
470
1385
  // Error conversion
471
1386
  // ---------------------------------------------------------------------------
1387
+ /** A resume result (or recovery) that belongs to a session that was closed or replaced meanwhile. */
1388
+ class StaleSessionError extends Error {
1389
+ constructor() {
1390
+ super("session changed while resuming");
1391
+ this.name = "StaleSessionError";
1392
+ }
1393
+ }
1394
+ /** flow_id, action and the wmp metadata object with its version: the shape the early action check needs. */
1395
+ function isFlowActionEnvelope(params) {
1396
+ if (typeof params !== "object" || params === null)
1397
+ return false;
1398
+ const p = params;
1399
+ if (typeof p.flow_id !== "string" || typeof p.action !== "string")
1400
+ return false;
1401
+ const w = p.wmp;
1402
+ return typeof w === "object" && w !== null && typeof w.version === "string";
1403
+ }
1404
+ function isFlowIdEnvelope(params) {
1405
+ return typeof params === "object" && params !== null && typeof params.flow_id === "string";
1406
+ }
1407
+ /** The shape a wmp.flow.complete must have before the early result check applies: flow_id and the wmp metadata object with its version. */
1408
+ function isFlowCompleteEnvelope(params) {
1409
+ if (typeof params !== "object" || params === null)
1410
+ return false;
1411
+ const p = params;
1412
+ if (typeof p.flow_id !== "string")
1413
+ return false;
1414
+ const w = p.wmp;
1415
+ return typeof w === "object" && w !== null && typeof w.version === "string";
1416
+ }
1417
+ function flowIdOf(params) {
1418
+ return typeof params === "object" && params !== null ? params.flow_id : undefined;
1419
+ }
1420
+ function flowTypeOf(params) {
1421
+ return typeof params === "object" && params !== null ? params.flow_type : undefined;
1422
+ }
1423
+ const noop = () => { };
1424
+ /** Most flows a peer holds validation context for at once; a new start beyond it is refused. */
1425
+ const MAX_ACTIVE_FLOWS = 4096;
1426
+ /** Most finished flows remembered per session; at that point new starts are refused until the session is renewed. */
1427
+ const MAX_TERMINAL_HISTORY = 65536;
472
1428
  function toRPCError(err) {
473
1429
  if (err instanceof WMPError) {
474
- return { code: err.code, message: err.message, data: err.data };
1430
+ return { code: err.code, message: err.rpcMessage, data: err.data };
475
1431
  }
476
1432
  // Sanitize unexpected internal errors to avoid leaking implementation details.
477
1433
  if (typeof console !== "undefined" && console.error) {